Skip to main content

latexml_core/
token.rs

1use std::{borrow::Cow, fmt, fmt::Display, rc::Rc};
2
3use crate::{
4  Digested,
5  common::{
6    arena::{self, SymStr},
7    dimension::Dimension,
8    error::*,
9    float::Float,
10    glue::Glue,
11    mudimension::MuDimension,
12    muglue::MuGlue,
13    number::Number,
14    numeric_ops::NumericOps,
15    store::Stored,
16  },
17  definition::{Definition, register::Register},
18  state,
19  tokens::Tokens,
20};
21
22static CONTROLNAME: &[&str] = &[
23  "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO",
24  "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS",
25  "GS", "RS", "US",
26];
27
28/// A Token category code, as in TeX
29///
30/// Two bytes (`#[repr(u16)]`), so that [`Token`] (`text` u32, `code`, `prov` u16) has no padding byte: with one, every
31/// move of a token on the gullet's read path (`Option<Token>`, `CheckedRead::Tok`, the `Result` slot) copied the pad
32/// and `prov` as a 3-byte blob, byte by byte (`token_layout_code_at_byte_4`).
33#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
34#[repr(u16)]
35pub enum Catcode {
36  ESCAPE,
37  BEGIN,
38  END,
39  MATH,
40  ALIGN,
41  EOL,
42  PARAM,
43  SUPER,
44  SUB,
45  IGNORE,
46  SPACE,
47  LETTER,
48  OTHER,
49  ACTIVE,
50  COMMENT,
51  INVALID,
52  CS,
53  MARKER,
54  ARG,
55}
56
57impl From<u8> for Catcode {
58  fn from(num: u8) -> Catcode {
59    use crate::token::Catcode::*;
60    match num {
61      0 => ESCAPE,
62      1 => BEGIN,
63      2 => END,
64      3 => MATH,
65      4 => ALIGN,
66      5 => EOL,
67      6 => PARAM,
68      7 => SUPER,
69      8 => SUB,
70      9 => IGNORE,
71      10 => SPACE,
72      11 => LETTER,
73      12 => OTHER,
74      13 => ACTIVE,
75      14 => COMMENT,
76      15 => INVALID,
77      16 => CS,
78      17 => MARKER,
79      18 => ARG,
80      _ => {
81        // let message = s!("Unrecognized catcode: {:?}", num);
82        // Warn!("unknown", "catcode", None, message);
83        IGNORE
84      },
85    }
86  }
87}
88
89impl From<Catcode> for u8 {
90  fn from(cc: Catcode) -> u8 {
91    use crate::token::Catcode::*;
92    match cc {
93      ESCAPE => 0,
94      BEGIN => 1,
95      END => 2,
96      MATH => 3,
97      ALIGN => 4,
98      EOL => 5,
99      PARAM => 6,
100      SUPER => 7,
101      SUB => 8,
102      IGNORE => 9,
103      SPACE => 10,
104      LETTER => 11,
105      OTHER => 12,
106      ACTIVE => 13,
107      COMMENT => 14,
108      INVALID => 15,
109      CS => 16,
110      MARKER => 17,
111      ARG => 18,
112    }
113  }
114}
115
116impl Catcode {
117  /// a debug-friendly name
118  pub fn name(self) -> &'static str {
119    use crate::token::Catcode::*;
120    match self {
121      // Primitive
122      ESCAPE => "Escape",
123      BEGIN => "Begin",
124      END => "End",
125      MATH => "Math",
126      ALIGN => "Align",
127      EOL => "EOL",
128      PARAM => "Parameter",
129      SUPER => "Superscript",
130      SUB => "Subscript",
131      SPACE => "Space",
132      // Non-primitive
133      IGNORE => "Ignore",
134      LETTER => "Letter",
135      OTHER => "Other",
136      ACTIVE => "Active",
137      COMMENT => "Comment",
138      INVALID => "Invalid",
139      CS => "ControlSequence",
140      MARKER => "Marker",
141      ARG => "Arg",
142    }
143  }
144
145  /// SymStr form of `name()` — each variant caches its interned
146  /// symbol via `pin!`. Used by `Token::get_cs_name` /
147  /// `pin_cs_name` to avoid a per-call `pin_static` hash probe
148  /// (fires on every primitive-token definition lookup).
149  pub fn name_sym(self) -> SymStr {
150    use crate::token::Catcode::*;
151    match self {
152      ESCAPE => crate::pin!("Escape"),
153      BEGIN => crate::pin!("Begin"),
154      END => crate::pin!("End"),
155      MATH => crate::pin!("Math"),
156      ALIGN => crate::pin!("Align"),
157      EOL => crate::pin!("EOL"),
158      PARAM => crate::pin!("Parameter"),
159      SUPER => crate::pin!("Superscript"),
160      SUB => crate::pin!("Subscript"),
161      SPACE => crate::pin!("Space"),
162      IGNORE => crate::pin!("Ignore"),
163      LETTER => crate::pin!("Letter"),
164      OTHER => crate::pin!("Other"),
165      ACTIVE => crate::pin!("Active"),
166      COMMENT => crate::pin!("Comment"),
167      INVALID => crate::pin!("Invalid"),
168      CS => crate::pin!("ControlSequence"),
169      MARKER => crate::pin!("Marker"),
170      ARG => crate::pin!("Arg"),
171    }
172  }
173  /// a \meaning-friendly name
174  pub fn meaning(self) -> &'static str {
175    use crate::token::Catcode::*;
176    match self {
177      ESCAPE => "the escape character",
178      BEGIN => "begin-group character",
179      END => "end-group character",
180      MATH => "math shift character",
181      ALIGN => "alignment tab character",
182      EOL => "end-of-line character",
183      PARAM => "macro parameter character",
184      SUPER => "superscript character",
185      SUB => "subscript character",
186      IGNORE => "ignored character",
187      SPACE => "blank space",
188      LETTER => "the letter",
189      OTHER => "the character",
190      ACTIVE => "active character",
191      COMMENT => "comment character",
192      INVALID => "invalid character",
193      _ => "",
194    }
195  }
196  /// a short name helpful for Token debugging
197  pub fn short_name(self) -> &'static str {
198    use crate::token::Catcode::*;
199    match self {
200      ESCAPE => "T_ESCAPE",
201      BEGIN => "T_BEGIN",
202      END => "T_END",
203      MATH => "T_MATH",
204      ALIGN => "T_ALIGN",
205      EOL => "T_EOL",
206      PARAM => "T_PARAM",
207      SUPER => "T_SUPER",
208      SUB => "T_SUB",
209      IGNORE => "T_IGNORE",
210      SPACE => "T_SPACE",
211      LETTER => "T_LETTER",
212      OTHER => "T_OTHER",
213      ACTIVE => "T_ACTIVE",
214      COMMENT => "T_COMMENT",
215      INVALID => "T_INVALID",
216      CS => "T_CS",
217      MARKER => "T_MARKER",
218      ARG => "T_ARG",
219    }
220  }
221
222  // ======================================================================
223  // Categories of Category codes.
224  // For Tokens with these catcodes, only the catcode is relevant for comparison.
225  // (if they even make it to a stage where they get compared)
226  /// TeX-primitive codes
227  pub fn is_primitive(self) -> bool {
228    use crate::token::Catcode::*;
229    match self {
230      // Primitives
231      ESCAPE | BEGIN | END | MATH | ALIGN | EOL | PARAM | SUPER | SUB | SPACE => true,
232      // Non-primitive
233      IGNORE | LETTER | OTHER | ACTIVE | COMMENT | INVALID | CS | MARKER | ARG => false,
234    }
235  }
236  /// Catcodes with associated primitives
237  pub fn is_executable(self) -> bool {
238    use crate::token::Catcode::*;
239    match self {
240      // Executable
241      BEGIN | END | MATH | ALIGN | SUPER | SUB | ACTIVE | CS => true,
242      // Non-executable
243      EOL | ESCAPE | PARAM | SPACE | IGNORE | LETTER | OTHER | COMMENT | INVALID | MARKER | ARG => {
244        false
245      },
246    }
247  }
248  /// Catcodes which can be neutralized
249  pub fn is_neutralizable(self) -> bool {
250    use crate::token::Catcode::*;
251    match self {
252      // Neutralizable
253      MATH | ALIGN | PARAM | SUPER | SUB | ACTIVE => true,
254      // Non-neutralizable
255      ESCAPE | BEGIN | END | EOL | IGNORE | SPACE | LETTER | OTHER | COMMENT | INVALID | CS
256      | MARKER | ARG => false,
257    }
258  }
259  /// Shorthand to match the "active" and "command sequence" catcodes
260  pub fn is_active_or_cs(self) -> bool {
261    use crate::token::Catcode::*;
262    matches!(self, ACTIVE | CS)
263  }
264  /// Tokens which can be absorbed without side-effects
265  pub fn is_absorbable(self) -> bool {
266    use crate::token::Catcode::*;
267    // Absorbable
268    matches!(self, SPACE | LETTER | OTHER | COMMENT)
269  }
270  /// Gullet can only hold comment and marker tokens
271  pub fn is_gullet_holdable(self) -> bool {
272    use crate::token::Catcode::*;
273    matches!(self, COMMENT | MARKER)
274  }
275  /// Catcodes that are of note for balanced reads.
276  pub fn is_balanced_interesting(self) -> bool {
277    use crate::token::Catcode::*;
278    // `gullet::is_balanced` reacts to BEGIN,END,MARKER coded tokens
279    matches!(self, BEGIN | END | MARKER)
280  }
281}
282
283/// The core immutable syntactic primitive resulting from TeX's read-in and expansion process
284/// We allow the fields to be public, so that we can use builder macros such as
285/// ```
286/// macro_rules! T_SPACE(() => {
287///     Token { text: arena::pin_static(" "), code: Catcode::SPACE}
288///   });
289/// ```
290///
291/// `#[repr(C)]` pins the field order `text`, `code`, `prov` (`loc`): `code` stays at byte 4, where it sat before
292/// `prov` existed, and with a two-byte [`Catcode`] the struct has no padding (`prov` at 6). Rust's default layout put
293/// `prov` at 4 and `code` at 6, which made every move of a token through `Option<Token>`, `CheckedRead::Tok` and the
294/// read path's `Result` slot a 4-piece field-wise copy (`gullet::read_internal_token_checked`: +1.29 % instructions
295/// on an empty article; +1.14 % with `repr(C)` alone, the pad byte still copied apart; +0.65 % gap-free). The guard
296/// is `token_layout_code_at_byte_4`.
297#[derive(Copy, Clone)]
298#[repr(C)]
299pub struct Token {
300  /// an arena id the character content for this token
301  pub text: SymStr,
302  /// a TeX catcode
303  pub code: Catcode,
304  /// Out-of-band field provenance (`0` = none): the frontmatter field whose stored value this token
305  /// is a token of (the kernel `\title`/`\author` stamp their store, latexml_engine `\lx@field@mark`), so the
306  /// ink digested from it is known for that field's print. Not part of TeX's token: **excluded from `PartialEq`**
307  /// (`\ifx`, `\meaning`, `\pdfstrcmp`, xstring compare as pdflatex does), never written, never dumped. It sits in
308  /// what was the struct's padding: `Token` stays 8 bytes (`token_size_invariant`). OXIDIZED_DESIGN #715.
309  pub prov: u16,
310  /// Origin handle into the per-conversion token-origin side arena (1-based;
311  /// `0` = no recorded origin). Present only under the `token-locators` feature
312  /// (the opt-in source-map precision build); `Token` stays 8 bytes otherwise.
313  /// Set in `read_token`; carried through expansion so a digested run can recover
314  /// its exact source span. **Excluded from `PartialEq`** (tokens compare by
315  /// meaning, not origin — see `impl PartialEq`). See docs/performance/SOURCE_PROVENANCE.md
316  /// §3.1.1.
317  #[cfg(feature = "token-locators")]
318  pub loc:  u32,
319}
320
321impl fmt::Debug for Token {
322  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
323    if self.code == Catcode::ARG {
324      self.with_str(|text| write!(f, "\"#{}\"", text))
325    } else {
326      self.with_str(|text| write!(f, "{:?}", text))
327    }
328  }
329}
330
331impl Display for Token {
332  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
333    if self.code == Catcode::ARG {
334      write!(f, "#")?;
335    }
336    self.with_str(|text| write!(f, "{}", text))
337  }
338}
339
340/// Compare two tokens; They are equal if they both have same catcode & string
341// [We pretend all SPACE's are the same, since we'd like to hide newline's in there!]
342// NOTE: That another popular equality checks whether the "meaning" (defn) are the same.
343// That is NOT done here; see Equals(x,y) and XEquals(x,y)
344impl PartialEq for Token {
345  fn eq(&self, other: &Token) -> bool {
346    self.code == other.code && (self.code == Catcode::SPACE || (self.text == other.text))
347  }
348}
349
350/// The comparison is reflexive (a token is equal to itself, a space to any space).
351impl Eq for Token {}
352
353/// Hashes what [`PartialEq`] compares: the catcode, and the text unless a space (every space is one), so that equal
354/// tokens hash alike (a set of the distinct tokens read: the frontmatter rehearsal's `\let`-copy scan).
355impl std::hash::Hash for Token {
356  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
357    self.code.hash(state);
358    if self.code != Catcode::SPACE {
359      self.text.hash(state);
360    }
361  }
362}
363
364// Per-symbol memo for `Token::is_noexpand_family`, indexed by the symbol's
365// arena index: 0 = not yet computed, 1 = not in the family, 2 = in the family.
366// Sound because the arena is append-only (a symbol's text never changes);
367// MUST be cleared alongside `arena::reset()` (see
368// `reset_noexpand_family_memo`, called from `reset_thread_engine`) since a
369// reset renumbers symbols. A symbol's index is its byte offset in the arena's
370// buffer (not a dense index), so the memo covers only the first
371// `NOEXPAND_MEMO_SPAN` bytes and a later symbol is checked directly: unbounded,
372// the memo grew with every byte interned, to 1.5 GB after a long pgf path
373// (tkz-grapheur), and in `cortex_worker`, which never resets the arena, with
374// the worker's whole lifetime. Ordinary papers' arenas are 8-21 MB, inside the
375// span, so for them the memo is as before. A map keyed by symbol bounds it
376// too, but costs +0.5 % instructions on typical papers (the 24-paper C2 set).
377thread_local! {
378  static NOEXPAND_FAMILY_MEMO: std::mem::ManuallyDrop<std::cell::RefCell<Vec<u8>>> =
379    const { std::mem::ManuallyDrop::new(std::cell::RefCell::new(Vec::new())) };
380}
381/// The arena byte span the [`Token::is_noexpand_family`] memo covers (64 MiB).
382const NOEXPAND_MEMO_SPAN: usize = 1 << 26;
383
384/// Clear the [`Token::is_noexpand_family`] per-symbol memo. Companion to
385/// `arena::reset()` — symbol indices are reused after a reset, so stale
386/// entries would alias unrelated strings (same bug class as the REPORT-map
387/// fix, `7b64a48ad1`). The storage is freed, not only emptied: a leaked per-thread static has no destructor, so what a
388/// reset keeps would outlive a thread that exits (the memo runs to megabytes, one byte per arena byte).
389pub fn reset_noexpand_family_memo() {
390  NOEXPAND_FAMILY_MEMO.with(|memo| *memo.borrow_mut() = Vec::new());
391}
392
393/// Name of the bare no-op control sequence `\noexpand` collapses to, and the
394/// prefix of every member of the no-expand family. See [`Token::is_noexpand_family`].
395pub const NOEXPAND_PREFIX: &str = "\\special_relax";
396/// Separator byte between the `\special_relax` prefix and the shadowed token's
397/// text in a family token's name. `\x01` is never valid in a CS name or active
398/// char, so `\special_relax\x01\foo` is unambiguous and cannot collide with a
399/// real CS such as a (hypothetical) `\special_relaxfoo`.
400pub const NOEXPAND_SEP: u8 = 1;
401
402/// Build the no-expand family token shadowing `shadowed` — the per-token,
403/// dump-safe representation of `\noexpand <shadowed>` (faithful to TeX's
404/// `no_expand_flag`: the shadowed identity is preserved in the name; the family
405/// resolves to `\relax` meaning). `shadowed` is an expandable/undefined CS or
406/// active token (the only things `\noexpand` wraps; see `is_dont_expandable`).
407pub fn noexpand_family(shadowed: &Token) -> Token {
408  let text = shadowed.with_str(|s| format!("{NOEXPAND_PREFIX}{}{s}", NOEXPAND_SEP as char));
409  Token {
410    text: arena::pin(text),
411    code: Catcode::CS,
412    prov: 0,
413    #[cfg(feature = "token-locators")]
414    loc: 0,
415  }
416}
417
418// Note: given that we are pinning the strings in an arena,
419//  once we have a token of a certain kind it is now faster to clone
420//  a known token than it is to build a new one
421//  (as the arena lookup is a hair slower than copying a u32)
422
423thread_static! {
424  /// constant for a BEGIN "{" token
425  pub static TOKEN_BEGIN: Token = Token {
426    text: arena::pin_static("{"),
427    code: Catcode::BEGIN,
428    prov: 0,
429    #[cfg(feature = "token-locators")]
430    loc: 0,
431  };
432}
433thread_static! {
434  /// constant for an END "}" token
435  pub static TOKEN_END: Token = Token {
436    text: arena::pin_static("}"),
437    code: Catcode::END,
438    prov: 0,
439    #[cfg(feature = "token-locators")]
440    loc: 0,
441  };
442}
443thread_static! {
444  /// constant for a MATH "$" token
445  pub static TOKEN_MATH: Token = Token {
446    text: arena::pin_static("$"),
447    code: Catcode::MATH,
448    prov: 0,
449    #[cfg(feature = "token-locators")]
450    loc: 0,
451  };
452}
453thread_static! {
454  /// constant for an ALIGN "&" token
455  pub static TOKEN_ALIGN: Token = Token {
456    text: arena::pin_static("&"),
457    code: Catcode::ALIGN,
458    prov: 0,
459    #[cfg(feature = "token-locators")]
460    loc: 0,
461  };
462}
463thread_static! {
464  /// constant for a PARAM "#" token
465  pub static TOKEN_PARAM: Token = Token {
466    text: arena::pin_static("#"),
467    code: Catcode::PARAM,
468    prov: 0,
469    #[cfg(feature = "token-locators")]
470    loc: 0,
471  };
472}
473thread_static! {
474  /// constant for a SUPER "^" token
475  pub static TOKEN_SUPER: Token = Token {
476    text: arena::pin_static("^"),
477    code: Catcode::SUPER,
478    prov: 0,
479    #[cfg(feature = "token-locators")]
480    loc: 0,
481  };
482}
483thread_static! {
484  /// constant for a SUB "_" token
485  pub static TOKEN_SUB: Token = Token {
486    text: arena::pin_static("_"),
487    code: Catcode::SUB,
488    prov: 0,
489    #[cfg(feature = "token-locators")]
490    loc: 0,
491  };
492}
493thread_static! {
494  /// constant for a SPACE " " token
495  pub static TOKEN_SPACE: Token = Token {
496    text: arena::pin_static(" "),
497    code: Catcode::SPACE,
498    prov: 0,
499    #[cfg(feature = "token-locators")]
500    loc: 0,
501  };
502}
503thread_static! {
504  /// constant for a CR "\n" token
505  pub static TOKEN_CR: Token = Token {
506    text: arena::pin_static("\n"),
507    code: Catcode::SPACE,
508    prov: 0,
509    #[cfg(feature = "token-locators")]
510    loc: 0,
511  };
512}
513thread_static! {
514  /// constant for T_CS("\relax")
515  pub static TOKEN_RELAX: Token = Token {
516    text: arena::pin_static("\\relax"),
517    code: Catcode::CS,
518    prov: 0,
519    #[cfg(feature = "token-locators")]
520    loc: 0,
521  };
522}
523thread_static! {
524  /// constant for T_CS("\expandafter")
525  pub static TOKEN_EXPANDAFTER: Token = Token {
526    text: arena::pin_static("\\expandafter"),
527    code: Catcode::CS,
528    prov: 0,
529    #[cfg(feature = "token-locators")]
530    loc: 0,
531  };
532}
533thread_static! {
534  /// constant for T_CS("\endcsname")
535  pub static TOKEN_ENDCSNAME: Token = Token {
536    text: arena::pin_static("\\endcsname"),
537    code: Catcode::CS,
538    prov: 0,
539    #[cfg(feature = "token-locators")]
540    loc: 0,
541  };
542}
543
544/// Eagerly initialize this thread's pre-built per-thread token
545/// constants. Each one's initializer interns its control-sequence
546/// name via `arena::pin_static`, so they must be forced AFTER
547/// [`arena::force_init`](crate::common::arena::force_init) and before any
548/// code accesses them during another root's initialization — otherwise the
549/// first access re-entrantly initializes the token from within that other
550/// root's init, the macOS thread-local hazard (rust-lang/rust#29594,
551/// issue #217). No behavioral change on Linux.
552pub(crate) fn force_init() {
553  for token in constants() {
554    let _ = &**token;
555  }
556}
557
558/// The token constants in their [`force_init`] order.
559fn constants() -> [&'static crate::aux_macros::ThreadRoot<Token>; 12] {
560  [
561    &TOKEN_BEGIN,
562    &TOKEN_END,
563    &TOKEN_MATH,
564    &TOKEN_ALIGN,
565    &TOKEN_PARAM,
566    &TOKEN_SUPER,
567    &TOKEN_SUB,
568    &TOKEN_SPACE,
569    &TOKEN_CR,
570    &TOKEN_RELAX,
571    &TOKEN_EXPANDAFTER,
572    &TOKEN_ENDCSNAME,
573  ]
574}
575
576/// After `arena::reset`, pin the constants' texts again in [`force_init`]'s order. On a thread whose engine was
577/// forced first (`init_thread_engine`) the empty arena gives back the same symbols, so the constants (built once per
578/// thread, never rebuilt) stay valid for the thread's next conversion; `false` if one differs.
579pub(crate) fn repin_constants() -> bool {
580  const TEXTS: [&str; 12] = [
581    "{",
582    "}",
583    "$",
584    "&",
585    "#",
586    "^",
587    "_",
588    " ",
589    "\n",
590    "\\relax",
591    "\\expandafter",
592    "\\endcsname",
593  ];
594  let mut same = true;
595  for (token, text) in constants().into_iter().zip(TEXTS) {
596    same &= arena::pin_static(text) == token.text;
597  }
598  same
599}
600
601#[macro_export]
602/// macro for a BEGIN "{" token
603macro_rules! T_BEGIN(() => { *$crate::token::TOKEN_BEGIN });
604#[macro_export]
605/// macro for a new END "{" token
606macro_rules! T_END(() => { *$crate::token::TOKEN_END });
607/// macro for a MATH "$" token
608#[macro_export]
609macro_rules! T_MATH(() => { *$crate::token::TOKEN_MATH });
610/// macro for an ALIGN "&" token
611#[macro_export]
612macro_rules! T_ALIGN(() => { *$crate::token::TOKEN_ALIGN });
613/// macro for a PARAM "#" token
614#[macro_export]
615macro_rules! T_PARAM(() => { *$crate::token::TOKEN_PARAM });
616/// macro for a SUPER "^" token
617#[macro_export]
618macro_rules! T_SUPER(() => { *$crate::token::TOKEN_SUPER });
619/// macro for a SUB "_" token
620#[macro_export]
621macro_rules! T_SUB(() => { *$crate::token::TOKEN_SUB });
622/// macro for a SPACE token (default " ")
623#[macro_export]
624macro_rules! T_SPACE(() => { *$crate::token::TOKEN_SPACE };
625($text:literal) => {
626  Token { text: $crate::pin!($text), code: Catcode::SPACE,
627      prov: 0, #[cfg(feature = "token-locators")] loc: 0
628    }
629});
630/// macro for a CR "\n" token
631#[macro_export]
632macro_rules! T_CR(() => { *$crate::token::TOKEN_CR });
633/// macro for a LETTER token
634#[macro_export]
635macro_rules! T_LETTER {
636  ($text:literal) => {
637    Token {
638      text: $crate::pin!($text),
639      code: Catcode::LETTER,
640      prov: 0,
641      #[cfg(feature = "token-locators")]
642      loc: 0,
643    }
644  };
645  ($text:expr_2021) => {
646    Token {
647      text: $crate::common::arena::pin($text),
648      code: Catcode::LETTER,
649      prov: 0,
650      #[cfg(feature = "token-locators")]
651      loc: 0,
652    }
653  };
654}
655/// macro for an OTHER code token
656#[macro_export]
657macro_rules! T_OTHER {
658  ($text:literal) => {
659    Token {
660      text: $crate::pin!($text),
661      code: Catcode::OTHER,
662      prov: 0,
663      #[cfg(feature = "token-locators")]
664      loc: 0,
665    }
666  };
667  ($text:expr_2021) => {
668    Token {
669      text: $crate::common::arena::pin($text),
670      code: Catcode::OTHER,
671      prov: 0,
672      #[cfg(feature = "token-locators")]
673      loc: 0,
674    }
675  };
676}
677/// T_OTHER from a single character
678#[macro_export]
679macro_rules! T_OTHER_CHAR {
680  ($text:literal) => {
681    Token {
682      text: $crate::common::arena::pin_char($text),
683      code: Catcode::OTHER,
684      prov: 0,
685      #[cfg(feature = "token-locators")]
686      loc: 0,
687    }
688  };
689}
690/// macro for an ACTIVE char token
691#[macro_export]
692macro_rules! T_ACTIVE {
693  ($c:expr_2021) => {{
694    let mut tmp = [0u8; 4];
695    let s = $c.encode_utf8(&mut tmp);
696    Token {
697      text: $crate::common::arena::pin(s),
698      code: Catcode::ACTIVE,
699      prov: 0,
700      #[cfg(feature = "token-locators")]
701      loc: 0,
702    }
703  }};
704}
705/// macro for a COMMENT content token
706#[macro_export]
707macro_rules! T_COMMENT {
708  ($text:expr_2021) => {
709    Token {
710      text: $crate::common::arena::pin($text),
711      code: Catcode::COMMENT,
712      prov: 0,
713      #[cfg(feature = "token-locators")]
714      loc: 0,
715    }
716  };
717}
718/// macro for a command sequence token
719#[macro_export]
720macro_rules! T_CS {
721  ($text:literal) => {
722    $crate::token::Token {
723      text: $crate::pin!($text),
724      code: $crate::token::Catcode::CS,
725      prov: 0,
726      #[cfg(feature = "token-locators")]
727      loc: 0,
728    }
729  };
730  ($text:expr_2021) => {
731    $crate::token::Token {
732      text: $crate::common::arena::pin($text),
733      code: $crate::token::Catcode::CS,
734      prov: 0,
735      #[cfg(feature = "token-locators")]
736      loc: 0,
737    }
738  };
739}
740
741/// macro for T_CS("\\relax")
742#[macro_export]
743macro_rules! T_RELAX(() => { $crate::token::TOKEN_RELAX.clone() });
744
745/// macro for a tracing MARKER token
746#[macro_export]
747macro_rules! T_MARKER {
748  ($text:expr_2021) => {
749    Token {
750      text: $crate::common::arena::pin($text),
751      code: Catcode::MARKER,
752      prov: 0,
753      #[cfg(feature = "token-locators")]
754      loc: 0,
755    }
756  };
757}
758
759/// macro for a numbered ARG token
760#[macro_export]
761macro_rules! T_ARG {
762  ($text:expr_2021) => {
763    Token {
764      text: $crate::common::arena::pin($text.to_string()),
765      code: Catcode::ARG,
766      prov: 0,
767      #[cfg(feature = "token-locators")]
768      loc: 0,
769    }
770  };
771}
772
773/// Token constructor macro (defaults to OTHER code). `Token!(sym <SymStr>, <catcode>)` takes an
774/// already-interned symbol (a token's `text`, a `Stored::String`), without interning it again.
775#[macro_export]
776macro_rules! Token {
777  (sym $sym:expr_2021, $cc:expr_2021) => {
778    Token {
779      text: $sym,
780      code: $cc,
781      prov: 0,
782      #[cfg(feature = "token-locators")]
783      loc: 0,
784    }
785  };
786  ($text:expr_2021) => {
787    Token!($text, Catcode::OTHER)
788  };
789  ($text:literal, $cc:expr_2021) => {
790    Token {
791      text: $crate::pin!($text),
792      code: $cc,
793      prov: 0,
794      #[cfg(feature = "token-locators")]
795      loc: 0,
796    }
797  };
798  ($text:expr_2021, $cc:expr_2021) => {
799    Token {
800      text: $crate::common::arena::pin($text),
801      code: $cc,
802      prov: 0,
803      #[cfg(feature = "token-locators")]
804      loc: 0,
805    }
806  };
807}
808
809/// Special case: a character needs swift string conversion, so let's use a dedicated macro
810#[macro_export]
811macro_rules! CharToken {
812  ($c:expr_2021) => {
813    CharToken!($c, $crate::token::Catcode::OTHER)
814  };
815  ($c:expr_2021, $cc:expr_2021) => {
816    $crate::token::Token {
817      text: $crate::common::arena::pin_char($c),
818      code: $cc,
819      prov: 0,
820      #[cfg(feature = "token-locators")]
821      loc: 0,
822    }
823  };
824}
825
826/// Explode a string into a list of tokens, all w/catcode OTHER (except space).
827/// Note: newlines are converted to OTHER, NOT SPACE (Perl #2700 reverted #2646).
828/// ^^J in TeX decodes to CC_OTHER by default; let the tokenizer handle catcode
829/// reassignment if needed.
830#[macro_export]
831macro_rules! Explode(($text:expr_2021) => (
832  $text.to_string().chars().map(|c|
833    if c==' ' { T_SPACE!() }
834    else {
835      CharToken!(c)
836    }
837  ).collect::<Vec<Token>>()
838));
839
840#[macro_export]
841macro_rules! ExplodeChars(($text:expr_2021) => (
842  $text.as_str().chars().map(|c|
843    if c==' ' { T_SPACE!() }
844    else {
845      CharToken!(c)
846    }
847  ).collect::<Vec<Token>>()
848));
849
850/// Similar to Explode, but convert letters to catcode LETTER and others to OTHER
851/// Hopefully, this is essentially correct WITHOUT resorting to catcode lookup?
852/// Perl sync: newlines are OTHER, not SPACE (matches Perl #2700 revert of #2646).
853/// Letters are ASCII `[a-zA-Z]` only, as Perl Token.pm:111-116 and latex.ltx `\char@if@alph`; `é` is OTHER.
854#[macro_export]
855macro_rules! ExplodeText(
856  ($text:expr_2021) => ({
857  use $crate::token::{Catcode,Token};
858  $text.to_string().chars().map(|c|
859    if c==' ' { T_SPACE!() }
860    else {
861      let mut tmp = [0u8; 4];
862      let s = c.encode_utf8(&mut tmp);
863      if c.is_ascii_alphabetic() {
864      T_LETTER!(s) }
865    else { T_OTHER!(s) }}
866  ).collect::<Vec<Token>>()
867}));
868
869#[macro_export]
870macro_rules! SymExplodeText(
871  ($sym:expr_2021) => ({
872  use $crate::token::{Catcode,Token};
873  let chars : Vec<char> = arena::with($sym, |text| text.chars().collect());
874  chars.into_iter().map(|c|
875    if c==' ' { T_SPACE!() }
876    else {
877      let mut tmp = [0u8; 4];
878      let s = c.encode_utf8(&mut tmp);
879      if c.is_ascii_alphabetic() {
880      T_LETTER!(s) }
881    else { T_OTHER!(s) }}
882  ).collect::<Vec<Token>>()
883}));
884
885// static UNTEX_LINELENGTH: usize = 78; // [CONSTANT]
886
887impl Default for Token {
888  fn default() -> Self {
889    Token {
890      text: arena::pin_static("EXPECTED_TOKEN"),
891      code: Catcode::OTHER,
892      prov: 0,
893      #[cfg(feature = "token-locators")]
894      loc: 0,
895    }
896  }
897}
898
899///======================================================================
900/// Accessors.
901/// The bits of a [`Token::prov`] below the field: the token's position in the field's stored value (saturating).
902pub const FIELD_PROV_POS_BITS: u16 = 14;
903/// The largest position a field's stamps take, cumulative per document (`\lx@field@mark`, `\lx@field@stamp`).
904pub const FIELD_PROV_POS_MASK: u16 = (1 << FIELD_PROV_POS_BITS) - 1;
905/// The author field (`2`) is the top bit alone, the id `3` being none: its positions take 15 bits, so a call's own
906/// positions (the frontmatter observer's rehearsal of one author block, positions per call) reach 32,767 — a block of
907/// 559 names past the 16,383 the stamps take (2204.09614, 2404.06718). The stamps' tokens below 16,384 read as before.
908pub const AUTHOR_PROV_POS_MASK: u16 = (1 << (FIELD_PROV_POS_BITS + 1)) - 1;
909const AUTHOR_PROV: u16 = 1 << (FIELD_PROV_POS_BITS + 1);
910/// The field provenance of the token at `pos` of field `field`'s stored value (`field` 1 or 2; `0` is no field).
911pub fn field_prov(field: u16, pos: usize) -> u16 {
912  if field == 2 {
913    AUTHOR_PROV | (pos.min(AUTHOR_PROV_POS_MASK as usize) as u16)
914  } else {
915    (field << FIELD_PROV_POS_BITS) | (pos.min(FIELD_PROV_POS_MASK as usize) as u16)
916  }
917}
918/// The field of a [`Token::prov`] (`0` = none).
919#[inline]
920pub fn field_prov_field(prov: u16) -> u16 {
921  if prov & AUTHOR_PROV != 0 {
922    2
923  } else {
924    prov >> FIELD_PROV_POS_BITS
925  }
926}
927/// The position in its field's stored value of a [`Token::prov`].
928#[inline]
929pub fn field_prov_pos(prov: u16) -> u16 {
930  if prov & AUTHOR_PROV != 0 {
931    prov & AUTHOR_PROV_POS_MASK
932  } else {
933    prov & FIELD_PROV_POS_MASK
934  }
935}
936
937/// The expansion of a token with a field provenance (`prov`, [`Token::prov`]) is that field's too: each of its tokens
938/// without a provenance of its own takes `prov` (an `\and` in `\@author` expands to ink of the author field). A no-op
939/// for `prov` 0, the case of every token outside a frontmatter field's store.
940#[inline]
941pub fn inherit_field_prov(prov: u16, expansion: &mut Tokens) {
942  if prov != 0 {
943    for t in expansion.unlist_mut() {
944      if t.prov == 0 {
945        t.prov = prov;
946      }
947    }
948  }
949}
950
951/// A cover of a field's stored value: the positions `start..end` (end exclusive) of one field (`field`, `0` = none)
952/// that an invocation consumed, its own position and its arguments. See [`field_cover_pending_merge`].
953#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
954pub struct FieldCover {
955  /// the field (`1` title, `2` author; `0` = no cover)
956  pub field: u16,
957  /// the first position covered
958  pub start: u16,
959  /// one past the last position covered
960  pub end:   u16,
961}
962
963thread_local! {
964  /// The cover of a field token's invocation that produced no box (a font switch, `\relax`, a macro's expansion still
965  /// to be digested): the next box digested from that field's tokens within it takes it (a field's print covers its
966  /// font switches and the arguments a macro or primitive consumed, OXIDIZED_DESIGN #715).
967  static FIELD_COVER_PENDING: std::cell::Cell<FieldCover> =
968    const { std::cell::Cell::new(FieldCover { field: 0, start: 0, end: 0 }) };
969}
970
971/// Merge `cover` with the pending cover of a boxless invocation when they touch (the same field, `cover` starting
972/// inside or at the end of the pending one), clearing the pending cover either way: what a box digested from a field
973/// token covers of its stored value.
974pub fn field_cover_pending_merge(cover: FieldCover) -> FieldCover {
975  let pending = FIELD_COVER_PENDING.replace(FieldCover::default());
976  if pending.field == cover.field && pending.start <= cover.start && cover.start <= pending.end {
977    FieldCover {
978      field: cover.field,
979      start: pending.start,
980      end:   pending.end.max(cover.end),
981    }
982  } else {
983    cover
984  }
985}
986
987/// Leave `cover` pending for the next box of its field ([`field_cover_pending_merge`]), merged with the pending one
988/// it continues.
989pub fn field_cover_set_pending(cover: FieldCover) {
990  let merged = field_cover_pending_merge(cover);
991  FIELD_COVER_PENDING.set(merged);
992}
993
994/// One entry of the field ledger ([`field_ledger_push`]): the cover of a box digested from a field token, and whether
995/// the structure the print is set in took the box instead of the document absorbing it ([`field_ledger_take`]).
996#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
997pub struct FieldLedgerEntry {
998  /// what the box covers of its field's value
999  pub cover: FieldCover,
1000  /// taken by an alignment the document shows: a `tabular` row's end marker (a value's `\\`), digested and consumed by
1001  /// the alignment body, never absorbed, so no run of ink holds it (taken when the alignment's whatsit is absorbed,
1002  /// core `document::FIELD_TAKEN_PROPERTY`)
1003  pub taken: bool,
1004}
1005
1006thread_local! {
1007  /// The covers of the boxes digested from field tokens, in digestion order ([`field_ledger_push`]). What a run of ink
1008  /// covers is the entries of the boxes it absorbed (core `Document::absorb`'s field runs keep their serials), and of
1009  /// those an alignment took right after them ([`field_ledger_take`]); never an entry absorbed elsewhere (another run,
1010  /// a formula) or never absorbed (an unused `\setbox`, `\sbox`, `{lrbox}`), OXIDIZED_DESIGN #715.
1011  static FIELD_LEDGER: std::cell::RefCell<Vec<FieldLedgerEntry>> =
1012    const { std::cell::RefCell::new(Vec::new()) };
1013}
1014thread_local! {
1015  /// Set once the frontmatter placement settled the field ink (core `Document::settle_field_ink`): the ledger records
1016  /// nothing more, and nothing digested after it carries a field provenance property.
1017  static FIELD_LEDGER_SETTLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1018}
1019/// The most covers the ledger keeps (a full ledger records no more: a print digested past it is no whole print).
1020const FIELD_LEDGER_CAP: usize = 1 << 16;
1021
1022/// Is the field ledger recording ([`field_ledger_settle`])? The stomach records a field token's box only while it is.
1023#[inline]
1024pub fn field_ledger_live() -> bool { !FIELD_LEDGER_SETTLED.get() }
1025
1026/// Stop recording field covers: the frontmatter placement settled the field ink (no run is marked after it).
1027pub fn field_ledger_settle() { FIELD_LEDGER_SETTLED.set(true); }
1028
1029/// Record the cover of a box digested from a field token (the field ledger); its serial, the box's `fieldSerial`.
1030pub fn field_ledger_push(cover: FieldCover) -> Option<u32> {
1031  if FIELD_LEDGER_SETTLED.get() {
1032    return None;
1033  }
1034  FIELD_LEDGER.with(|ledger| {
1035    let mut ledger = ledger.borrow_mut();
1036    if ledger.len() >= FIELD_LEDGER_CAP {
1037      return None;
1038    }
1039    ledger.push(FieldLedgerEntry { cover, taken: false });
1040    u32::try_from(ledger.len() - 1).ok()
1041  })
1042}
1043
1044/// Note that the structure a print is set in took the box recorded with `serial` (an alignment's row-end marker, a
1045/// value's `\\`): no run absorbs it, and the run its row ends may cover it ([`FieldLedgerEntry::taken`]).
1046pub fn field_ledger_take(serial: u32) {
1047  FIELD_LEDGER.with(|ledger| {
1048    if let Some(entry) = ledger.borrow_mut().get_mut(serial as usize) {
1049      entry.taken = true;
1050    }
1051  });
1052}
1053
1054/// The positions of field `field`'s value covered by the ledger entries with the serials in `serials` (inclusive
1055/// `first..=last` intervals): sorted disjoint `start..end` intervals, merged where they touch.
1056pub fn field_ledger_cover(field: u16, serials: &[(u32, u32)]) -> Vec<(u16, u16)> {
1057  let mut cover: Vec<(u16, u16)> = FIELD_LEDGER.with(|ledger| {
1058    let ledger = ledger.borrow();
1059    let mut cover = Vec::new();
1060    for &(first, last) in serials {
1061      let (first, last) = (first as usize, last as usize);
1062      if first > last || first >= ledger.len() {
1063        continue;
1064      }
1065      cover.extend(
1066        ledger[first..=last.min(ledger.len() - 1)]
1067          .iter()
1068          .filter(|e| e.cover.field == field)
1069          .map(|e| (e.cover.start, e.cover.end.max(e.cover.start + 1))),
1070      );
1071    }
1072    cover
1073  });
1074  cover.sort_unstable();
1075  let mut merged: Vec<(u16, u16)> = Vec::with_capacity(cover.len());
1076  for (start, end) in cover {
1077    match merged.last_mut() {
1078      Some((_, e)) if start <= *e => *e = (*e).max(end),
1079      _ => merged.push((start, end)),
1080    }
1081  }
1082  merged
1083}
1084
1085/// The entry the field ledger recorded with `serial` ([`field_ledger_push`]).
1086pub fn field_ledger_entry(serial: u32) -> Option<FieldLedgerEntry> {
1087  FIELD_LEDGER.with(|ledger| ledger.borrow().get(serial as usize).copied())
1088}
1089
1090/// A stretch of digestion the document never keeps (a rehearsal of a frontmatter field's value, latexml_engine's
1091/// frontmatter observer), over which the field ledger records ([`field_ledger_live`], even once the placement settled
1092/// it) and after which it is as it was: the entries pushed meanwhile are dropped, the pending cover and the settled
1093/// flag put back, and the gate of field stamping (`document::field_prov_stamped`: a `\title` the rehearsal
1094/// stamps) as it was (on drop). Its serials are read while it is open ([`field_ledger_entry`]); a print the document
1095/// makes later is numbered as if it had never run.
1096///
1097/// The boxes the stomach stamped with a field provenance meanwhile (`fieldProv`/`fieldSerial`, `invoke_token`) are
1098/// unstamped on drop as well (`field_stamp_noted`): a box the run did not make — a register's, `\copy`/`\usebox`
1099/// handing back the stored box itself — would otherwise keep the run's serial, which the ledger no longer holds, and
1100/// the document's own print of it, finding it stamped, would not stamp it again (FM S2a.2 r9: `\usebox{\ORCIDicon}` in
1101/// an `\author`, wrapped in an `ltx:text` with an id under the observer's census switch, since deleted: 2405.14627, 2603.26792; repro
1102/// `sectioning-frontmatter/observer_rehearsal_leaves_a_used_box_unchanged`).
1103pub struct FieldLedgerScope {
1104  len:     usize,
1105  pending: FieldCover,
1106  settled: bool,
1107  stamped: bool,
1108  /// The enclosing scope's stamp journal (none outside every scope).
1109  outer:   Option<Vec<Digested>>,
1110}
1111
1112/// What runs on each field token's invocation while a rehearsal takes notes on what its boxes do not hold (the frontmatter
1113/// observer's `field_notes`, in the engine): `Token::prov`'s test in the stomach, then this. All the core knows of them, so
1114/// no line of theirs sits among the code the core's hot path is inlined from (Z01: the same lines here cost a text document
1115/// 0.17 % of `instructions:u` with no call made, a reshuffle of the crate's codegen units).
1116pub type FieldNotesHook = fn(&Token, FieldCover, FieldInvocation<'_>);
1117
1118/// What a field token's invocation did ([`FieldNotesHook`]), now that it read what it reads.
1119#[derive(Clone, Copy)]
1120pub enum FieldInvocation<'a> {
1121  /// the stomach digested it, to these boxes
1122  Digested(&'a [Digested]),
1123  /// the gullet expanded it, to these tokens, about to go on the input
1124  Expanded(&'a Tokens),
1125}
1126thread_local! {
1127  static FIELD_NOTES_HOOK: std::cell::Cell<Option<FieldNotesHook>> =
1128    const { std::cell::Cell::new(None) };
1129}
1130
1131/// Set (or, with `None`, clear) the hook [`FieldNotesHook`] names.
1132pub fn set_field_notes_hook(hook: Option<FieldNotesHook>) { FIELD_NOTES_HOOK.set(hook); }
1133
1134/// The hook [`FieldNotesHook`] names, while one is set.
1135#[inline]
1136pub fn field_notes_hook() -> Option<FieldNotesHook> { FIELD_NOTES_HOOK.get() }
1137
1138/// The pending cover of a boxless invocation ([`field_cover_pending_merge`]).
1139pub fn field_cover_pending() -> FieldCover { FIELD_COVER_PENDING.get() }
1140
1141thread_local! {
1142  /// The boxes stamped with a field provenance while a [`FieldLedgerScope`] is open (none outside one).
1143  static FIELD_STAMPED_BOXES: std::cell::RefCell<Option<Vec<Digested>>> =
1144    const { std::cell::RefCell::new(None) };
1145}
1146
1147/// Note that the stomach stamped `digested` with a field provenance (`fieldProv`/`fieldSerial`), which had none: a
1148/// [`FieldLedgerScope`] open now takes the stamp off again when it closes.
1149pub(crate) fn field_stamp_noted(digested: &Digested) {
1150  FIELD_STAMPED_BOXES.with(|boxes| {
1151    if let Some(boxes) = boxes.borrow_mut().as_mut() {
1152      boxes.push(digested.clone());
1153    }
1154  });
1155}
1156
1157impl FieldLedgerScope {
1158  /// Open the scope: the ledger records from here.
1159  pub fn begin() -> Self {
1160    let len = FIELD_LEDGER.with(|ledger| ledger.borrow().len());
1161    FieldLedgerScope {
1162      len,
1163      pending: FIELD_COVER_PENDING.replace(FieldCover::default()),
1164      settled: FIELD_LEDGER_SETTLED.replace(false),
1165      stamped: crate::document::field_prov_stamped(),
1166      outer: FIELD_STAMPED_BOXES.with(|boxes| boxes.replace(Some(Vec::new()))),
1167    }
1168  }
1169}
1170
1171impl Drop for FieldLedgerScope {
1172  fn drop(&mut self) {
1173    FIELD_LEDGER.with(|ledger| ledger.borrow_mut().truncate(self.len));
1174    FIELD_COVER_PENDING.set(self.pending);
1175    FIELD_LEDGER_SETTLED.set(self.settled);
1176    crate::document::restore_field_prov_stamped(self.stamped);
1177    let stamped = FIELD_STAMPED_BOXES.with(|boxes| boxes.replace(self.outer.take()));
1178    for digested in stamped.into_iter().flatten() {
1179      digested.try_remove_property(crate::document::FIELD_PROV_PROPERTY);
1180      digested.try_remove_property(crate::document::FIELD_SERIAL_PROPERTY);
1181    }
1182  }
1183}
1184
1185/// Clear the pending field cover and the ledger, and record again (conversion start).
1186pub fn reset_field_cover_pending() {
1187  FIELD_COVER_PENDING.set(FieldCover::default());
1188  FIELD_LEDGER.with(|ledger| ledger.borrow_mut().clear());
1189  FIELD_LEDGER_SETTLED.set(false);
1190}
1191
1192impl Token {
1193  /// simple Token constructor, wrapping over text and catcode
1194  pub fn new<T: AsRef<str>>(text: T, code: Catcode) -> Self {
1195    Self::from_sym(arena::pin(text), code)
1196  }
1197
1198  /// Construct a token directly from an already-interned [`SymStr`] without
1199  /// re-probing or interning into the arena.
1200  #[inline]
1201  pub fn from_sym(text: SymStr, code: Catcode) -> Self {
1202    Token {
1203      text,
1204      code,
1205      prov: 0,
1206      #[cfg(feature = "token-locators")]
1207      loc: 0,
1208    }
1209  }
1210
1211  /// Look up an already-interned control-sequence token without interning a
1212  /// new symbol if `text` has never been seen.
1213  #[inline]
1214  pub fn try_cs<T: AsRef<str>>(text: T) -> Option<Self> {
1215    arena::get(text).map(|text| Token { text, ..T_CS!("\\relax") })
1216  }
1217
1218  /// A cheap structural fingerprint for the cycle-detection guard
1219  /// ([`crate::cycle_guard`]). Matches [`PartialEq`] semantics: SPACE tokens
1220  /// fingerprint by catcode alone (their text is irrelevant to equality).
1221  /// NOT a stable hash across processes — for in-run loop detection only.
1222  #[inline]
1223  pub fn cycle_fingerprint(&self) -> u64 {
1224    use std::hash::{Hash, Hasher};
1225    let mut h = rustc_hash::FxHasher::default();
1226    self.code.hash(&mut h);
1227    if self.code != Catcode::SPACE {
1228      self.text.hash(&mut h);
1229    }
1230    h.finish()
1231  }
1232
1233  /// Get the CS Name of the token. This is the name that definitions will be
1234  /// stored under; It's the same for various `different' BEGIN tokens, eg.
1235  pub fn get_cs_name(&self) -> SymStr {
1236    if self.code.is_primitive() {
1237      self.code.name_sym()
1238    } else {
1239      self.get_sym()
1240    }
1241  }
1242
1243  /// Execute a closure using the CS Name of the token.
1244  /// This is the name that definitions will be stored under;
1245  /// It's the same for various `different' BEGIN tokens, eg.
1246  pub fn with_cs_name<R, FnR>(&self, caller: FnR) -> R
1247  where FnR: FnOnce(&str) -> R {
1248    if self.code.is_primitive() {
1249      caller(self.code.name())
1250    } else {
1251      self.with_str(caller)
1252    }
1253  }
1254
1255  /// artificial, but avoids the data race
1256  pub fn pin_cs_name(&self) -> SymStr {
1257    if self.code.is_primitive() {
1258      self.code.name_sym()
1259    } else {
1260      self.get_sym()
1261    }
1262  }
1263
1264  /// Get the fixed name of a primitive catcode, or empty string otherwise
1265  pub fn get_primitive_name(&self) -> Option<&'static str> {
1266    if self.code.is_primitive() {
1267      Some(self.code.name())
1268    } else {
1269      None
1270    }
1271  }
1272
1273  /// Get the CS name only if the catcode is executable!
1274  pub fn get_executable_name(&self) -> String {
1275    let cc = self.code;
1276    if cc.is_executable() {
1277      self
1278        .get_primitive_name()
1279        .map(ToString::to_string)
1280        .unwrap_or_else(|| self.with_str(|text| text.to_string()))
1281    } else {
1282      String::new()
1283    }
1284  }
1285
1286  /// Intersect executable and primitive
1287  pub fn get_executable_primitive_name(&self) -> Option<&'static str> {
1288    let cc = self.code;
1289    if cc.is_executable() && cc.is_primitive() {
1290      Some(self.code.name())
1291    } else {
1292      None
1293    }
1294  }
1295
1296  /// Use the ticket representing the interned "text" of the token
1297  pub fn get_sym(&self) -> SymStr { self.text }
1298  /// Use the interned &str "text" of the token
1299  /// use `to_string` instead for an owned String with simpler
1300  pub fn with_str<R, FnR>(&self, caller: FnR) -> R
1301  where FnR: FnOnce(&str) -> R {
1302    arena::with(self.text, caller)
1303  }
1304
1305  /// True for any member of the `\special_relax` no-expand family — the
1306  /// representation of a `\noexpand`'d (expandable or undefined) CS/active token.
1307  /// Such a token is a CS whose NAME is `\special_relax` `\x01` `<shadowed text>`,
1308  /// carrying the shadowed token's identity PER-TOKEN (faithful to TeX's
1309  /// `no_expand_flag`, which preserves `cur_cs`), while the whole family resolves
1310  /// to `\special_relax`'s `\relax` meaning ([`crate::state::lookup_meaning`]
1311  /// fallback). The bare `\special_relax` (no suffix) is the no-shadow case
1312  /// (`\dont_expand` at end-of-input). `\x01` is never valid in a CS name or as
1313  /// an active char, so the encoding is unambiguous.
1314  #[inline]
1315  pub fn is_noexpand_family(&self) -> bool {
1316    self.code == Catcode::CS && self.names_noexpand_family()
1317  }
1318
1319  /// [`Self::is_noexpand_family`] of a control sequence.
1320  fn names_noexpand_family(&self) -> bool {
1321    // Per-symbol memo: this runs ×2 per CS token via `state::meaning_key`
1322    // (read_x_token decides whether to expand, invoke_token how to invoke),
1323    // and the string-prefix probe was ~2% of digest self-time (2026-08-23
1324    // audit). A symbol's text never changes (append-only arena), so the
1325    // answer is memoized by symbol index: 0 = unknown, 1 = no, 2 = yes, for
1326    // the indices below `NOEXPAND_MEMO_SPAN`. Cleared with the arena in
1327    // `reset_thread_engine` (symbol indices are reused after `arena::reset`).
1328    use string_interner::Symbol;
1329    let idx = self.text.to_usize();
1330    if idx < NOEXPAND_MEMO_SPAN {
1331      let cached = NOEXPAND_FAMILY_MEMO.with(|memo| memo.borrow().get(idx).copied().unwrap_or(0));
1332      if cached != 0 {
1333        return cached == 2;
1334      }
1335    }
1336    self.read_noexpand_family(idx)
1337  }
1338
1339  /// The first look at a symbol: its text decides, and the answer goes in the memo. Kept out of line, as
1340  /// [`Self::noexpand_shadowed`] runs for every token of an argument and must stay small enough to inline its test.
1341  #[cold]
1342  #[inline(never)]
1343  fn read_noexpand_family(&self, idx: usize) -> bool {
1344    let is_family = self.with_str(|s| {
1345      s.starts_with(NOEXPAND_PREFIX)
1346        && (s.len() == NOEXPAND_PREFIX.len() || s.as_bytes()[NOEXPAND_PREFIX.len()] == NOEXPAND_SEP)
1347    });
1348    if idx < NOEXPAND_MEMO_SPAN {
1349      NOEXPAND_FAMILY_MEMO.with(|memo| {
1350        let mut memo = memo.borrow_mut();
1351        if memo.len() <= idx {
1352          memo.resize(idx + 1, 0);
1353        }
1354        memo[idx] = if is_family { 2 } else { 1 };
1355      });
1356    }
1357    is_family
1358  }
1359
1360  /// Recover the shadowed token from a `\special_relax`-family token, if it
1361  /// shadows one (i.e. not the bare `\special_relax`). The shadowed token is a
1362  /// CS (text begins `\`) or an active char.
1363  #[inline]
1364  pub fn noexpand_shadowed(&self) -> Option<Token> {
1365    if self.is_noexpand_family() {
1366      self.shadowed_by_noexpand()
1367    } else {
1368      None
1369    }
1370  }
1371
1372  /// [`Self::noexpand_shadowed`] of a member of the family.
1373  #[cold]
1374  #[inline(never)]
1375  fn shadowed_by_noexpand(&self) -> Option<Token> {
1376    // The owned shadowed name + its catcode, computed INSIDE the `with_str`
1377    // lend and pinned after it, so the name goes to the arena's buffer, not its
1378    // overflow page (clippy::unnecessary_to_owned cannot see that).
1379    let (name, code) = self.with_str(|s| {
1380      let rest = s.strip_prefix(NOEXPAND_PREFIX)?;
1381      let rest = rest.strip_prefix(NOEXPAND_SEP as char)?;
1382      let code = if rest.starts_with('\\') {
1383        Catcode::CS
1384      } else {
1385        Catcode::ACTIVE
1386      };
1387      Some((rest.to_string(), code))
1388    })?;
1389    Some(Token {
1390      text: arena::pin(name),
1391      code,
1392      prov: 0,
1393      #[cfg(feature = "token-locators")]
1394      loc: 0,
1395    })
1396  }
1397
1398  /// Return the character code of  character part of the token, or 256 if it is a control
1399  /// sequence. A SPACE token's code is always 32: tex.web §289 `space_token =
1400  /// 2^8·spacer + " "` and §349 (`mid_line + car_ret` → `cur_chr := " "`) — an
1401  /// end-of-line becomes a space with character code 32, whatever produced it.
1402  /// This token keeps its `"\n"` TEXT (Perl's data model, `PRESERVE_NEWLINES`,
1403  /// the `tex=` reversion) but Perl's `getCharcode` returned `ord("\n")` = 10
1404  /// for it (Token.pm:243), so `\if` compared an end-of-line space unequal to a
1405  /// typed one: stringstrings' `\if\BlankSpace#1` took the wrong branch on a
1406  /// `\@for` item that was a lone newline and desynchronised the conditional
1407  /// stack (`Extra \else`), then tikzviolinplots' KDE loop ran away
1408  /// (batch 56gc, OXIDIZED_DESIGN #260).
1409  pub fn get_charcode(&self) -> u32 {
1410    if self.code == Catcode::CS {
1411      256
1412    } else if self.code == Catcode::SPACE {
1413      32
1414    } else {
1415      self.with_str(|text| {
1416        if let Some(c) = text.chars().next() {
1417          c as u32
1418        } else {
1419          0
1420        }
1421      })
1422    }
1423  }
1424
1425  /// How far this token moves a brace count: 1 for a begin-group, -1 for an end-group, else 0. Brace balance is a property of
1426  /// a run of tokens, no reading of what they spell.
1427  pub fn group_step(&self) -> i32 {
1428    match self.get_catcode() {
1429      Catcode::BEGIN => 1,
1430      Catcode::END => -1,
1431      _ => 0,
1432    }
1433  }
1434
1435  /// Return the catcode of the token.
1436  pub fn get_catcode(&self) -> Catcode { self.code }
1437  /// is the current one
1438  pub fn is_executable(&self) -> bool { self.code.is_executable() }
1439  /// A control sequence or an active character ([`Catcode::is_active_or_cs`]).
1440  pub fn is_active_or_cs(&self) -> bool { self.code.is_active_or_cs() }
1441
1442  /// neutralize really should only retroactively imitate what Semiverbatim would have done.
1443  /// So, it needs to neutralize those in SPECIALS
1444  /// NOTE that although '%' gets it's catcode changed in Semiverbatim,
1445  /// I'm pretty sure we do NOT want to neutralize comments (turn them into Catcode::OTHER)
1446  /// here, since if comments do get into the Tokens, that will introduce weird crap into the
1447  /// stream.
1448  pub fn neutralize(self, extraspecials: &[char]) -> Token {
1449    let first_c: Option<char> = self.with_str(|text| text.chars().next());
1450    let ch = match first_c {
1451      Some(ch) => ch,
1452      None => return self,
1453    };
1454    let cc = self.code;
1455    if cc.is_neutralizable() {
1456      for extra in extraspecials {
1457        if extra == &ch {
1458          let mut tmp = [0u8; 4];
1459          let s = ch.encode_utf8(&mut tmp);
1460          return T_OTHER!(s);
1461        }
1462      }
1463      let maybe_return = state::with_value("SPECIALS", |specials_opt| {
1464        if let Some(Stored::Chars(specials_list)) = specials_opt {
1465          for special in specials_list.iter() {
1466            if *special == ch {
1467              let mut tmp = [0u8; 4];
1468              let s = ch.encode_utf8(&mut tmp);
1469              return Some(T_OTHER!(s));
1470            }
1471          }
1472        }
1473        None
1474      });
1475      if let Some(token) = maybe_return {
1476        return token;
1477      }
1478    }
1479    self
1480  }
1481
1482  pub fn as_other(&self) -> Token {
1483    Token {
1484      text: self.text,
1485      code: Catcode::OTHER,
1486      prov: 0,
1487      #[cfg(feature = "token-locators")]
1488      loc: 0,
1489    }
1490  }
1491  pub fn as_cs(&self) -> Token {
1492    Token {
1493      text: self.text,
1494      code: Catcode::CS,
1495      prov: 0,
1496      #[cfg(feature = "token-locators")]
1497      loc: 0,
1498    }
1499  }
1500
1501  pub fn substitute_parameters(self, args: &[&Token]) -> Self {
1502    if self.code == Catcode::ARG {
1503      self.with_str(|text| {
1504        let arg_idx = text
1505          .parse::<usize>()
1506          .expect("ARG catcode tokens should always contain numeric literals as text");
1507        *args[arg_idx - 1]
1508      })
1509    } else {
1510      self
1511    }
1512  }
1513
1514  /// A Token reverts to itself
1515  pub fn revert(self) -> Token { self }
1516
1517  /// A string form which is primarily used for error-reporting
1518  pub fn stringify(&self) -> String {
1519    self.with_str(|text| {
1520      // Make the token's char content more printable, since this is for a visual messages.
1521      let display_text = if text.len() == 1 {
1522        let c = text.chars().next().unwrap() as u16;
1523        if c < 0x020 {
1524          Cow::Owned(s!("U+{:04x}/{}", c, CONTROLNAME[c as usize]))
1525        } else {
1526          Cow::Borrowed(text)
1527        }
1528      } else {
1529        Cow::Borrowed(text)
1530      };
1531      s!("{}[{}]", self.code.short_name(), display_text)
1532    })
1533  }
1534
1535  pub fn to_register(&self) -> Option<Rc<Register>> { state::lookup_register_definition(self) }
1536
1537  pub fn to_number(&self) -> Number {
1538    Number::new(self.with_str(|text| text.parse::<i64>()).unwrap_or(0))
1539  }
1540
1541  pub fn to_dimension(&self) -> Dimension {
1542    Dimension::new_f64(self.with_str(|text| text.parse::<f64>().unwrap_or(0.0)))
1543  }
1544
1545  pub fn to_mu_dimension(&self) -> MuDimension {
1546    MuDimension::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1547  }
1548
1549  pub fn to_glue(&self) -> Glue {
1550    Glue::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1551  }
1552
1553  pub fn to_mu_glue(&self) -> MuGlue {
1554    MuGlue::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1555  }
1556
1557  pub fn to_float(&self) -> Float {
1558    Float::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1559  }
1560
1561  pub fn be_digested(self) -> Result<Digested> { crate::stomach::digest(Tokens::new(vec![self])) }
1562
1563  /// Check whether the current token is defined as `other`.
1564  /// That is, whether it is equal to `other`, or \let to `other`.
1565  /// `other` is is presumed to be some "constant", explicit token,
1566  /// such as  `T_SPACE` or `T_CS!("\\endcsname")`.
1567  pub fn defined_as(&self, other: &Token) -> bool {
1568    self.spelled_as(other)
1569      || self
1570        .meaning_name()
1571        .is_some_and(|letto| letto.spelled_as(other))
1572  }
1573
1574  /// Whether this token is `other` itself, as `defined_as` compares: the same catcode and, but for a space, the same
1575  /// text.
1576  #[inline]
1577  pub fn spelled_as(&self, other: &Token) -> bool {
1578    self.code == other.code && (other.code == Catcode::SPACE || self.text == other.text)
1579  }
1580
1581  /// The token this one's meaning names, as `defined_as` reads it: the control sequence of its definition, or the token
1582  /// a `\let` copied. One meaning lookup; a character token that is not active names none.
1583  #[inline]
1584  pub fn meaning_name(&self) -> Option<Token> { self.with_meaning_name(|named, _| named) }
1585
1586  /// Calls `f` with `meaning_name` and the meaning itself, from one meaning lookup: for a caller that tests a token
1587  /// against several primitives (`defined_as` looks the meaning up per call) or reads its definition too
1588  /// (`tex_fonts::read_font_ident`). A character token that is not active has neither.
1589  pub fn with_meaning_name<R>(&self, f: impl FnOnce(Option<Token>, Option<&Stored>) -> R) -> R {
1590    if !matches!(self.code, Catcode::CS | Catcode::ACTIVE) {
1591      return f(None, None);
1592    }
1593    // Use the closure-based `with_meaning` — Token is `Copy`, so
1594    // extracting a `Token` from the borrowed Stored is an implicit
1595    // copy, not a clone. Avoids a full `Stored::clone()` per call
1596    // (defined_as fires ~1% of total instructions on siunitx/
1597    // physics-heavy docs).
1598    state::with_meaning(self, |defn_opt| {
1599      let named = defn_opt.and_then(|defn| match defn {
1600        Stored::Token(t) => Some(*t),
1601        Stored::Expandable(inner) => Some(*inner.get_cs()),
1602        Stored::Primitive(inner) => Some(*inner.get_cs()),
1603        Stored::MathPrimitive(inner) => Some(*inner.get_cs()),
1604        Stored::Register(inner) => Some(*inner.get_cs()),
1605        Stored::Conditional(inner) => Some(*inner.get_cs()),
1606        Stored::Constructor(inner) => Some(*inner.get_cs()),
1607        _ => None,
1608      });
1609      f(named, defn_opt)
1610    })
1611  }
1612}
1613
1614// A simple (constant!) auto-cast for &str to Token. Beware this will not respect the current
1615// catcodes in state (and @ is OTHER).
1616impl From<&str> for Token {
1617  fn from(text: &str) -> Token {
1618    match text.chars().next() {
1619      Some('{') => T_BEGIN!(),
1620      Some('}') => T_END!(),
1621      Some('$') => T_MATH!(),
1622      Some('#') => T_PARAM!(),
1623      Some('&') => T_ALIGN!(),
1624      Some('^') => T_SUPER!(),
1625      Some('_') => T_SUB!(),
1626      Some('\\') => T_CS!(text),
1627      Some('%') => T_COMMENT!(text),
1628      _ => {
1629        // tex.web §464 `str_toks`: a string becomes tokens with catcode
1630        // OTHER, except the space character (catcode SPACE). No catcode is
1631        // ever inferred from the character class — U+00A0/U+0085 are Unicode
1632        // whitespace but under the pdfTeX byte mouth (K10) they are the bytes
1633        // 0xA0/0x85 of 素 or 銀紅, and letters are letters only through a
1634        // mouth's catcode table. The punctuation arms above are the callers'
1635        // alias contract (`{`, `}`, `\cs`…), not a catcode guess.
1636        if text.chars().all(|c| c.is_ascii_whitespace()) {
1637          T_SPACE!()
1638        } else {
1639          T_OTHER!(text)
1640        }
1641      },
1642    }
1643  }
1644}
1645
1646// ── Token-origin side arena (token-locators feature) ───────────────────────
1647// Per-conversion store mapping a Token's `loc` handle (1-based; 0 = none) to its
1648// captured source start. Tokens carry only the u32 handle (Token stays 12 bytes);
1649// this holds the (source, line, col). Appended in `read_token`, read by the
1650// digestion consumer to give a text run its true span. Cleared per conversion.
1651// See docs/performance/SOURCE_PROVENANCE.md §3.1.1.
1652#[cfg(feature = "token-locators")]
1653#[derive(Clone, Copy, Debug)]
1654pub struct TokenStart {
1655  pub source:    SymStr,
1656  pub line:      u32,
1657  pub col:       u32,
1658  /// `true` when this origin was *inherited* from a macro invocation rather
1659  /// than read directly from a mouth — i.e. the token is synthesized
1660  /// expansion output (`\today → "May 25, 2026"`) attributed to its `\today`
1661  /// call site. The content-range recovery in `constructor::child_span`
1662  /// prefers genuine (read-from-source) origins and only falls back to
1663  /// inherited ones, so a `\section{Intro}`'s structural body literals — now
1664  /// carrying an inherited origin — never widen the title's content-exact
1665  /// span. See docs/performance/SOURCE_PROVENANCE.md §3.1.3.
1666  pub inherited: bool,
1667}
1668
1669#[cfg(feature = "token-locators")]
1670thread_local! {
1671  static TOKEN_ORIGINS: std::cell::RefCell<Vec<TokenStart>> =
1672    const { std::cell::RefCell::new(Vec::new()) };
1673}
1674
1675/// Append a token's source start, returning its 1-based handle (`0` is reserved
1676/// for "no origin"). Only called on the source-map precision path.
1677#[cfg(feature = "token-locators")]
1678pub fn push_token_origin(source: SymStr, line: u32, col: u32) -> u32 {
1679  TOKEN_ORIGINS.with(|o| {
1680    let mut v = o.borrow_mut();
1681    v.push(TokenStart {
1682      source,
1683      line,
1684      col,
1685      inherited: false,
1686    });
1687    v.len() as u32 // index + 1
1688  })
1689}
1690
1691/// Derive an *inherited* origin from an existing handle: look up the
1692/// invocation token's start, push a copy flagged `inherited`, and return its
1693/// new handle (`0` if `handle` is the no-origin sentinel or out of range). One
1694/// call per macro expansion; the returned handle is shared by every synthesized
1695/// result token. See `push_token_origin` and docs/performance/SOURCE_PROVENANCE.md §3.1.3.
1696#[cfg(feature = "token-locators")]
1697pub fn push_inherited_origin(handle: u32) -> u32 {
1698  if handle == 0 {
1699    return 0;
1700  }
1701  TOKEN_ORIGINS.with(|o| {
1702    let mut v = o.borrow_mut();
1703    let Some(mut start) = v.get((handle - 1) as usize).copied() else {
1704      return 0;
1705    };
1706    start.inherited = true;
1707    v.push(start);
1708    v.len() as u32
1709  })
1710}
1711
1712/// Resolve a token `loc` handle to its origin (`None` for the `0` sentinel or an
1713/// out-of-range handle).
1714#[cfg(feature = "token-locators")]
1715pub fn get_token_origin(handle: u32) -> Option<TokenStart> {
1716  if handle == 0 {
1717    return None;
1718  }
1719  TOKEN_ORIGINS.with(|o| o.borrow().get((handle - 1) as usize).copied())
1720}
1721
1722/// Reset the arena at the start of a conversion (handles are per-conversion).
1723#[cfg(feature = "token-locators")]
1724pub fn clear_token_origins() { TOKEN_ORIGINS.with(|o| o.borrow_mut().clear()); }
1725
1726#[cfg(test)]
1727mod tests {
1728  use super::*;
1729
1730  /// The `is_noexpand_family` memo is indexed by arena byte offset, so it covers
1731  /// only the first `NOEXPAND_MEMO_SPAN` bytes: a control sequence interned after
1732  /// more text than that is checked directly and the memo stays within the span
1733  /// (unbounded, it grew to the arena's size, 1.5 GB after tkz-grapheur's long
1734  /// pgf path). The answers are the same on both sides of the span, and on a
1735  /// memo hit.
1736  #[test]
1737  fn noexpand_memo_stays_within_its_span() {
1738    std::thread::spawn(|| {
1739      let early = T_CS!(NOEXPAND_PREFIX);
1740      assert!(early.is_noexpand_family());
1741      let _bulk = arena::pin("x".repeat(NOEXPAND_MEMO_SPAN + (1 << 20)));
1742      let late_family = T_CS!(format!("{NOEXPAND_PREFIX}{}\\foo", NOEXPAND_SEP as char));
1743      let late_other = T_CS!("\\noexpandmemoprobe");
1744      assert!(early.is_noexpand_family());
1745      assert!(late_family.is_noexpand_family());
1746      assert!(!late_other.is_noexpand_family());
1747      let len = NOEXPAND_FAMILY_MEMO.with(|memo| memo.borrow().len());
1748      assert!(len <= NOEXPAND_MEMO_SPAN, "memo grew to {len} bytes");
1749      reset_noexpand_family_memo();
1750      arena::reset();
1751    })
1752    .join()
1753    .unwrap();
1754  }
1755
1756  /// `Token` size invariant (docs/performance/SOURCE_PROVENANCE.md §3.1.1): 8 bytes by
1757  /// default (`SymStr` + `Catcode`), 12 only under the `token-locators`
1758  /// precision build (+ the `u32` origin handle). Guards the corpus/parity/
1759  /// distribution builds against an accidental widening.
1760  #[test]
1761  fn token_size_invariant() {
1762    #[cfg(not(feature = "token-locators"))]
1763    assert_eq!(
1764      size_of::<Token>(),
1765      8,
1766      "default Token must stay 8 bytes (SymStr + Catcode + prov)"
1767    );
1768    #[cfg(feature = "token-locators")]
1769    assert_eq!(
1770      std::mem::size_of::<Token>(),
1771      12,
1772      "token-locators Token is 8 + a u32 origin handle"
1773    );
1774  }
1775
1776  /// The field ledger (OXIDIZED_DESIGN #715): an entry an alignment took is marked so, a run's cover is the entries of
1777  /// the serials it holds (never an entry between them it does not), and once the frontmatter placement settled the
1778  /// field ink nothing more is recorded (fms1 round-3 review finding 5).
1779  #[test]
1780  fn field_ledger_take_cover_and_settle() {
1781    reset_field_cover_pending();
1782    let cover = |start, end| FieldCover { field: 1, start, end };
1783    let a = field_ledger_push(cover(0, 5)).unwrap();
1784    let unused = field_ledger_push(cover(5, 9)).unwrap();
1785    let marker = field_ledger_push(cover(9, 10)).unwrap();
1786    field_ledger_take(marker);
1787    assert!(field_ledger_entry(marker).is_some_and(|e| e.taken));
1788    assert!(field_ledger_entry(unused).is_some_and(|e| !e.taken));
1789    assert_eq!(field_ledger_cover(1, &[(a, a)]), vec![(0, 5)]);
1790    assert_eq!(field_ledger_cover(1, &[(a, a), (marker, marker)]), vec![
1791      (0, 5),
1792      (9, 10)
1793    ]);
1794    assert!(field_ledger_live());
1795    field_ledger_settle();
1796    assert!(!field_ledger_live());
1797    assert_eq!(field_ledger_push(cover(10, 11)), None);
1798    reset_field_cover_pending();
1799    assert!(field_ledger_live());
1800    assert_eq!(field_ledger_entry(a), None);
1801  }
1802
1803  /// `#[repr(C)]` and a two-byte `Catcode` keep `Token` gap-free with `code` at byte 4 (`text` u32 at 0, `code` u16
1804  /// at 4, `prov` u16 at 6, `loc` at 8 under token-locators). Why: under Rust's default layout `prov` took byte 4 and
1805  /// `code` moved to byte 6, and a pad byte stayed, so every token move on the gullet's read path became a field-wise
1806  /// copy (+1.29 % instructions on an empty article, +3.27 % on 2311.18489; gap-free +0.65 % / +1.66 %, fms1 round 3).
1807  /// OXIDIZED_DESIGN #715.
1808  #[test]
1809  fn token_layout_code_at_byte_4() {
1810    assert_eq!(std::mem::offset_of!(Token, text), 0);
1811    assert_eq!(
1812      std::mem::offset_of!(Token, code),
1813      4,
1814      "Token.code must sit at byte 4 (read-path codegen)"
1815    );
1816    assert_eq!(
1817      size_of::<Catcode>(),
1818      2,
1819      "Catcode fills bytes 4-5: no pad byte before prov"
1820    );
1821    assert_eq!(std::mem::offset_of!(Token, prov), 6);
1822    #[cfg(feature = "token-locators")]
1823    assert_eq!(std::mem::offset_of!(Token, loc), 8);
1824    assert_eq!(
1825      size_of::<Option<Token>>(),
1826      size_of::<Token>(),
1827      "Option<Token> keeps its niche"
1828    );
1829  }
1830
1831  /// Per-token origin capture (token-locators): each char token read from a
1832  /// mouth carries a handle resolving to its exact (line, col). This is the leaf
1833  /// accuracy that mouth-snapshot (Experiments 1–2) and digested-child assembly
1834  /// (Experiment 3) could not provide — the position now travels *with the
1835  /// token*. See docs/performance/SOURCE_PROVENANCE.md §3.1.1.
1836  #[cfg(feature = "token-locators")]
1837  #[test]
1838  fn token_origin_capture() {
1839    super::clear_token_origins();
1840    // "Hello" — five letters at 1-indexed columns 1..=5 on line 1.
1841    let toks = crate::mouth::tokenize("Hello");
1842    let got: Vec<(u32, u32)> = toks
1843      .unlist_ref()
1844      .iter()
1845      .map(|t| {
1846        let o = super::get_token_origin(t.loc).expect("token carries an origin handle");
1847        (o.line, o.col)
1848      })
1849      .collect();
1850    assert_eq!(
1851      got,
1852      vec![(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)],
1853      "each letter's captured (line, col) must be exact"
1854    );
1855  }
1856
1857  #[test]
1858  fn catcode_name_covers_all_variants() {
1859    // Ensure every Catcode variant produces a non-empty name.
1860    use Catcode::*;
1861    for cc in [
1862      ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE, IGNORE, LETTER, OTHER,
1863      ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1864    ] {
1865      assert!(!cc.name().is_empty(), "{cc:?}.name() is empty");
1866    }
1867  }
1868
1869  #[test]
1870  fn catcode_name_specific_values() {
1871    assert_eq!(Catcode::ESCAPE.name(), "Escape");
1872    assert_eq!(Catcode::BEGIN.name(), "Begin");
1873    assert_eq!(Catcode::CS.name(), "ControlSequence");
1874    assert_eq!(Catcode::LETTER.name(), "Letter");
1875  }
1876
1877  #[test]
1878  fn catcode_short_name_starts_with_t_prefix() {
1879    use Catcode::*;
1880    for cc in [
1881      ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE, IGNORE, LETTER, OTHER,
1882      ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1883    ] {
1884      assert!(
1885        cc.short_name().starts_with("T_"),
1886        "{cc:?}.short_name() = {} lacks T_ prefix",
1887        cc.short_name()
1888      );
1889    }
1890  }
1891
1892  #[test]
1893  fn catcode_meaning_mostly_nonempty() {
1894    // Most variants have a TeX-meaning description.
1895    assert!(!Catcode::ESCAPE.meaning().is_empty());
1896    assert!(!Catcode::LETTER.meaning().is_empty());
1897    assert!(!Catcode::OTHER.meaning().is_empty());
1898    // A few (e.g. CS/MARKER/ARG) fall through to "".
1899    assert_eq!(Catcode::CS.meaning(), "");
1900  }
1901
1902  #[test]
1903  fn is_primitive_checks() {
1904    use Catcode::*;
1905    // TeX primitives:
1906    for cc in [
1907      ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE,
1908    ] {
1909      assert!(cc.is_primitive(), "{cc:?} should be primitive");
1910    }
1911    // Non-primitives:
1912    for cc in [
1913      IGNORE, LETTER, OTHER, ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1914    ] {
1915      assert!(!cc.is_primitive(), "{cc:?} should not be primitive");
1916    }
1917  }
1918
1919  #[test]
1920  fn is_executable_checks() {
1921    use Catcode::*;
1922    for cc in [BEGIN, END, MATH, ALIGN, SUPER, SUB, ACTIVE, CS] {
1923      assert!(cc.is_executable(), "{cc:?} should be executable");
1924    }
1925    for cc in [
1926      EOL, ESCAPE, PARAM, SPACE, IGNORE, LETTER, OTHER, COMMENT, INVALID, MARKER, ARG,
1927    ] {
1928      assert!(!cc.is_executable(), "{cc:?} should not be executable");
1929    }
1930  }
1931
1932  #[test]
1933  fn is_neutralizable_set() {
1934    use Catcode::*;
1935    for cc in [MATH, ALIGN, PARAM, SUPER, SUB, ACTIVE] {
1936      assert!(cc.is_neutralizable(), "{cc:?}");
1937    }
1938    assert!(!CS.is_neutralizable());
1939    assert!(!LETTER.is_neutralizable());
1940  }
1941
1942  #[test]
1943  fn is_active_or_cs_narrow_set() {
1944    assert!(Catcode::ACTIVE.is_active_or_cs());
1945    assert!(Catcode::CS.is_active_or_cs());
1946    assert!(!Catcode::LETTER.is_active_or_cs());
1947    assert!(!Catcode::ESCAPE.is_active_or_cs());
1948  }
1949
1950  #[test]
1951  fn is_absorbable_space_letter_other_comment() {
1952    use Catcode::*;
1953    assert!(SPACE.is_absorbable());
1954    assert!(LETTER.is_absorbable());
1955    assert!(OTHER.is_absorbable());
1956    assert!(COMMENT.is_absorbable());
1957    // All else not absorbable.
1958    assert!(!CS.is_absorbable());
1959    assert!(!BEGIN.is_absorbable());
1960  }
1961
1962  #[test]
1963  fn is_gullet_holdable_comment_marker_only() {
1964    assert!(Catcode::COMMENT.is_gullet_holdable());
1965    assert!(Catcode::MARKER.is_gullet_holdable());
1966    assert!(!Catcode::SPACE.is_gullet_holdable());
1967    assert!(!Catcode::LETTER.is_gullet_holdable());
1968  }
1969
1970  #[test]
1971  fn is_balanced_interesting_begin_end_marker() {
1972    assert!(Catcode::BEGIN.is_balanced_interesting());
1973    assert!(Catcode::END.is_balanced_interesting());
1974    assert!(Catcode::MARKER.is_balanced_interesting());
1975    assert!(!Catcode::LETTER.is_balanced_interesting());
1976    assert!(!Catcode::MATH.is_balanced_interesting());
1977  }
1978
1979  #[test]
1980  fn catcode_u8_roundtrip() {
1981    // From<Catcode> for u8 + From<u8> for Catcode should round-trip
1982    // (at least for the documented range 0..=18).
1983    use Catcode::*;
1984    for cc in [
1985      ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE, IGNORE, LETTER, OTHER,
1986      ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1987    ] {
1988      let b: u8 = cc.into();
1989      let cc2: Catcode = b.into();
1990      assert_eq!(cc, cc2, "roundtrip broke for {cc:?} (u8={b})");
1991    }
1992  }
1993
1994  #[test]
1995  fn token_new_and_display() {
1996    let t = Token::new("foo", Catcode::LETTER);
1997    assert_eq!(format!("{t}"), "foo");
1998    assert_eq!(t.code, Catcode::LETTER);
1999  }
2000
2001  #[test]
2002  fn token_arg_display_prepends_hash() {
2003    // ARG catcode prepends # in Display.
2004    let t = Token::new("1", Catcode::ARG);
2005    assert_eq!(format!("{t}"), "#1");
2006  }
2007}
2008
2009#[cfg(test)]
2010mod charcode_tests {
2011  use super::{Catcode, Token};
2012
2013  /// tex.web §289/§349: every space token has character code 32, an
2014  /// end-of-line space included (its text stays "\n").
2015  #[test]
2016  fn end_of_line_space_has_character_code_32() {
2017    assert_eq!(Token::new("\n", Catcode::SPACE).get_charcode(), 32);
2018    assert_eq!(Token::new(" ", Catcode::SPACE).get_charcode(), 32);
2019    assert_eq!(Token::new("A", Catcode::LETTER).get_charcode(), 65);
2020  }
2021}