latexml_core/tokens.rs
1//! Token List constructors.
2use std::{
3 borrow::Cow,
4 collections::VecDeque,
5 fmt::{Display, Write as _},
6 rc::Rc,
7};
8
9#[cfg(feature = "codegen")]
10use proc_macro2::{Ident, Punct, Spacing, Span, TokenStream};
11#[cfg(feature = "codegen")]
12use quote::{ToTokens, TokenStreamExt, quote};
13
14use crate::{
15 Digested,
16 common::{
17 dimension::Dimension,
18 error::{emit_warn, *},
19 float::Float,
20 glue::Glue,
21 mudimension::MuDimension,
22 muglue::MuGlue,
23 number::Number,
24 numeric_ops::NumericOps,
25 },
26 definition::argument::ArgWrap,
27 fmt,
28 keyvals::KeyVals,
29 stomach,
30 token::*,
31};
32
33/// One piece of a macro body's [`Tokens::substitution_plan`].
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum BodyPiece {
36 /// The body's own tokens `[start, end)`.
37 Run(u32, u32),
38 /// Parameter `#n` (1-based, as written; `0` or any `n` above the arguments read substitutes nothing, as
39 /// [`Tokens::substitute_parameters`] does).
40 Parameter(usize),
41}
42
43/// If untex is requested to add line-breaks, this is the line length it will allow
44pub const UNTEX_LINELENGTH: usize = 78;
45/// Use this to avoid reallocating a new empty Vec each time you need a placeholder Tokens return
46/// value
47pub const NO_TOKENS: Tokens = Tokens(Vec::new());
48pub const NO_BORROWED_TOKENS: &Tokens = &NO_TOKENS;
49/// Tokens are a thin wrapper over a vector of Token objects
50///
51/// They are usually read from a `Mouth` and treated as an immutable interface.
52/// For access to the inner Token contents, use one of the `unlist` methods.
53#[derive(Debug, Clone, Default)]
54pub struct Tokens(Vec<Token>);
55
56impl PartialEq for Tokens {
57 fn eq(&self, other: &Tokens) -> bool {
58 self.0.len() == other.0.len() && self.0.iter().zip(other.0.iter()).all(|(a, b)| a == b)
59 }
60}
61
62/// convenience macro for assembling a Tokens object from different pieces (`Token`, `Vec<Token>`,
63/// `Tokens`)
64#[macro_export]
65macro_rules! Tokens(
66 () => ( $crate::tokens::NO_TOKENS );
67 ($tokens:expr_2021) => ({
68 let t_vec : Vec<$crate::token::Token> = $tokens.into();
69 $crate::tokens::Tokens::new(t_vec)
70 });
71 ($( $tokens:expr_2021 ),+) => ({
72 let mut collected : Vec<$crate::token::Token> = Vec::new();
73 $(
74 $crate::tokens::TokensPiece::append_to($tokens, &mut collected);
75 )*
76 $crate::tokens::Tokens::new(collected)
77 }));
78
79/// A piece of [`Tokens!`]: appended in place, without the `Vec` its `Into<Vec<Token>>` would make per piece.
80#[doc(hidden)]
81pub trait TokensPiece {
82 fn append_to(self, collected: &mut Vec<Token>);
83}
84impl TokensPiece for Token {
85 fn append_to(self, collected: &mut Vec<Token>) { collected.push(self) }
86}
87impl TokensPiece for Tokens {
88 fn append_to(self, collected: &mut Vec<Token>) {
89 if collected.is_empty() {
90 *collected = self.0;
91 } else {
92 collected.extend(self.0);
93 }
94 }
95}
96impl TokensPiece for Vec<Token> {
97 fn append_to(self, collected: &mut Vec<Token>) {
98 if collected.is_empty() {
99 *collected = self;
100 } else {
101 collected.extend(self);
102 }
103 }
104}
105// We also need convenient auxiliaries, including auto-casting
106impl From<Vec<Token>> for Tokens {
107 fn from(ts: Vec<Token>) -> Tokens { Tokens::new(ts) }
108}
109impl From<Tokens> for Vec<Token> {
110 fn from(ts: Tokens) -> Vec<Token> { ts.unlist() }
111}
112
113impl From<Token> for Tokens {
114 fn from(t: Token) -> Tokens { Tokens::new(vec![t]) }
115}
116impl From<&Token> for Tokens {
117 fn from(t: &Token) -> Tokens { Tokens::new(vec![*t]) }
118}
119
120// Good news: Cloning `Token` should now be cheap (due to string interning),
121// so cloning `Tokens` should be fine.
122impl From<Rc<Tokens>> for Tokens {
123 fn from(t: Rc<Tokens>) -> Tokens { (*t).clone() }
124}
125impl From<&Rc<Tokens>> for Tokens {
126 fn from(t: &Rc<Tokens>) -> Tokens { (**t).clone() }
127}
128
129impl From<Tokens> for Result<Tokens> {
130 fn from(t: Tokens) -> Result<Tokens> { Ok(t) }
131}
132impl From<Token> for Result<Tokens> {
133 fn from(t: Token) -> Result<Tokens> { Ok(t.into()) }
134}
135impl From<Token> for Vec<Token> {
136 fn from(t: Token) -> Vec<Token> { vec![t] }
137}
138
139impl From<Tokens> for Token {
140 fn from(mut ts: Tokens) -> Token {
141 if ts.0.is_empty() {
142 // Match the &Tokens impl below: empty → \relax fallback rather
143 // than panic. Callers that must see the empty case are rare and
144 // should inspect Tokens directly.
145 T_CS!("\\relax")
146 } else if ts.0.len() == 1 {
147 ts.0.remove(0)
148 } else {
149 // Prefer the first token and warn; cascading a panic here usually
150 // means a stringly-typed binding slot received a multi-token value
151 // (e.g. a macro argument coerced into a single-token slot). The
152 // first token preserves TEx's "grab a single token" semantics.
153 emit_warn(
154 "internal",
155 "tokens",
156 &format!("multi-token Tokens cast into single Token: {ts:?}"),
157 );
158 ts.0.remove(0)
159 }
160 }
161}
162
163impl<'a> From<&'a Tokens> for Token {
164 fn from(ts: &'a Tokens) -> Token {
165 if ts.0.is_empty() {
166 T_CS!("\\relax") // empty Tokens → relax fallback
167 } else if ts.0.len() == 1 {
168 ts.0[0]
169 } else {
170 emit_warn(
171 "internal",
172 "tokens",
173 &format!("multi-token Tokens cast into single Token: {ts:?}"),
174 );
175 ts.0[0]
176 }
177 }
178}
179
180impl From<Option<Tokens>> for Token {
181 fn from(ts_opt: Option<Tokens>) -> Token {
182 match ts_opt {
183 Some(ts) => ts.into(),
184 None => T_CS!("\\relax"), // None → relax, matching the empty-Tokens path
185 }
186 }
187}
188
189impl From<Token> for Option<Tokens> {
190 fn from(t: Token) -> Option<Tokens> { Some(Tokens::new(vec![t])) }
191}
192impl From<Token> for Option<Cow<'static, Tokens>> {
193 fn from(t: Token) -> Option<Cow<'static, Tokens>> { Some(Cow::Owned(Tokens::new(vec![t]))) }
194}
195
196impl Display for Tokens {
197 /// to_string is used often, and for more keyword-like reasons,
198 /// NOT for creating valid TeX (use revert or UnTeX for that!)
199 ///
200 /// This is THE token-list → Rust-string boundary (Perl `ToString`). Under
201 /// the pdfTeX byte mouth (KERNEL_CAPABILITIES K10) a non-ASCII name has two
202 /// token spellings — the bytes and the character the octet readers emit —
203 /// that pdfTeX never distinguishes; every Rust-side key derived here (colour
204 /// names, key-value keys, labels) gets the one decoded spelling
205 /// (`mouth::decode_byte_mouth_runs`), so the bindings need no per-site
206 /// normalization. Text runs reach the document as single-character boxes
207 /// and are reassembled there (`Document::open_text_internal`); `\csname`
208 /// builds its name in the gullet (`read_cs_name_inner`).
209 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
210 if crate::state::lookup_bool_sym(crate::pin!("PDFTEX_BYTE_MOUTH")) {
211 let mut s = String::new();
212 for t in &self.0 {
213 if t.code != Catcode::COMMENT {
214 write!(s, "{t}")?;
215 }
216 }
217 return f.write_str(&crate::mouth::decode_byte_mouth_runs(&s));
218 }
219 for t in &self.0 {
220 if t.code != Catcode::COMMENT {
221 write!(f, "{t}")?;
222 }
223 }
224 Ok(())
225 }
226}
227
228impl AsRef<Tokens> for Tokens {
229 fn as_ref(&self) -> &Tokens { self }
230}
231
232/// A string of **TeX markup** — text that is safe to hand back to the tokenizer.
233///
234/// It is *not* a path and *not* an input `.tex` file (`source_directory`,
235/// `--source-map` and `docs/performance/SOURCE_PROVENANCE.md` own that sense of
236/// "source"); it is the character content a [`crate::mouth::Mouth`] will read.
237///
238/// # Why the type exists
239///
240/// Flattening [`struct@Tokens`] with [`Display`] **welds control words**. TeX consumes
241/// the space that terminates a control word, so `\v S` tokenizes to `[\v][S]`;
242/// re-emitting that with `Display` gives `\vS`, a control sequence that exists in
243/// no LaTeX. [`Tokens::untex`] re-emits the space, `Display` deliberately does
244/// not — this is faithful to Perl (`Core/Tokens.pm:61 toString` joins the token
245/// strings, and `Core/Token.pm:306` returns a CS name with no trailing space),
246/// whose own comment says the result is "NOT for creating valid TeX (use revert
247/// or UnTeX for that!)".
248///
249/// Perl relies on author discipline there. It has failed three times in this
250/// port — `\bib@@names` (PR #399), `dcolumn`/`overpic` (PR #400), and the
251/// MathSciNet review path (issue 410: `MRREVIEWER = {Fran\c cois\ Digne}` became
252/// `undefined:\ccois`) — each found by a user-visible failure years after the
253/// code was written. `TeXString` makes the mistake unrepresentable instead: the
254/// tokenizing sinks take `impl Into<TeXString>`, and a bare `String` has no way
255/// in.
256///
257/// # The three ways in
258///
259/// * `From<&'static str>` — a string *literal* in a binding is TeX its author
260/// typed by hand, so it converts implicitly and the ~125 literal call sites
261/// stay untouched. There is deliberately **no** `From<String>` and **no**
262/// `From<&str>`: those are exactly the shapes a welded `Tokens::to_string()`
263/// arrives in, and `s!(…)`/`format!(…)` returns the former.
264/// * [`Tokens::untex_string`] — the blessed path from `Tokens`.
265/// * [`TeXString::assembled`] — the explicit escape hatch, for a `format!` of
266/// literal TeX around already-safe pieces. It names the obligation it imposes.
267///
268/// ```
269/// # use latexml_core::tokens::TeXString;
270/// let s: TeXString = r"\relax".into(); // literal: implicit
271/// assert_eq!(s.as_str(), r"\relax");
272/// ```
273///
274/// A `String` cannot get in on its own — this is the guard, and it bites:
275///
276/// ```compile_fail
277/// # use latexml_core::tokens::TeXString;
278/// let welded: String = String::from(r"\vS");
279/// let _: TeXString = welded.into(); // no `From<String>`: does not compile
280/// ```
281#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
282pub struct TeXString(Cow<'static, str>);
283
284impl TeXString {
285 /// Assert that an owned `String` is valid TeX markup.
286 ///
287 /// **The caller's obligation**: every interpolated fragment must be either
288 /// literal TeX written at the call site, or a fragment that came from
289 /// [`Tokens::untex_string`] / another `TeXString`. It must **not** be a bare
290 /// `Tokens::to_string()` — that is the welding bug this type exists to
291 /// prevent (`\v S` → `\vS`); use [`Tokens::untex_string`] for those.
292 ///
293 /// The typical honest use is a `format!` whose *shape* is literal TeX:
294 ///
295 /// ```
296 /// # use latexml_core::tokens::TeXString;
297 /// let counter = "section";
298 /// let tex = TeXString::assembled(format!(r"\the{counter}"));
299 /// assert_eq!(tex.as_str(), r"\thesection");
300 /// ```
301 pub fn assembled(tex: String) -> Self { TeXString(Cow::Owned(tex)) }
302
303 /// The TeX markup, borrowed.
304 pub fn as_str(&self) -> &str { &self.0 }
305
306 /// The TeX markup, owned (allocates only when this was built from a literal).
307 pub fn into_string(self) -> String { self.0.into_owned() }
308
309 /// Is there any markup at all?
310 pub fn is_empty(&self) -> bool { self.0.is_empty() }
311}
312
313impl From<&'static str> for TeXString {
314 /// A `&'static str` in a binding is a TeX literal its author typed by hand.
315 ///
316 /// Deliberately the *only* blanket string conversion — see the type docs.
317 fn from(tex: &'static str) -> Self { TeXString(Cow::Borrowed(tex)) }
318}
319
320impl Display for TeXString {
321 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0) }
322}
323
324impl AsRef<str> for TeXString {
325 fn as_ref(&self) -> &str { &self.0 }
326}
327
328impl Tokens {
329 /// Create a Tokens object from a `Vec` of individual `Token`
330 pub fn new(tokens: Vec<Token>) -> Self { Tokens(tokens) }
331
332 /// Return a list of the tokens making up this Tokens
333 pub fn unlist(self) -> Vec<Token> { self.0 }
334
335 /// Return a reference to the tokens making up this Tokens
336 pub fn unlist_ref(&self) -> &Vec<Token> { &self.0 }
337
338 /// Return a mutable reference to the tokens making up this Tokens
339 pub fn unlist_mut(&mut self) -> &mut Vec<Token> { &mut self.0 }
340
341 /// Are there any tokens at all contained in this Tokens object
342 pub fn is_empty(&self) -> bool { self.0.is_empty() }
343
344 /// Number of contained Token entries
345 pub fn len(&self) -> usize { self.0.len() }
346
347 /// Zero-alloc equivalent of `self.to_string().starts_with(prefix)`.
348 /// Walks tokens byte-by-byte into `prefix` using the same Display
349 /// semantics as `eq_text` (COMMENT skipped, ARG prefixed with `#`).
350 /// Returns `true` once the full prefix has been consumed, even if
351 /// more token text follows.
352 pub fn starts_with_text(&self, prefix: &str) -> bool {
353 let mut remaining = prefix;
354 for t in &self.0 {
355 if remaining.is_empty() {
356 return true;
357 }
358 if t.code == Catcode::COMMENT {
359 continue;
360 }
361 if t.code == Catcode::ARG {
362 if !remaining.starts_with('#') {
363 return false;
364 }
365 remaining = &remaining[1..];
366 if remaining.is_empty() {
367 return true;
368 }
369 }
370 let keep_going = t.with_str(|text| {
371 if text.is_empty() {
372 return true;
373 }
374 if remaining.starts_with(text) {
375 remaining = &remaining[text.len()..];
376 true
377 } else if text.starts_with(remaining) {
378 // This token's text extends past `prefix` — prefix matches
379 // and we're done.
380 remaining = "";
381 true
382 } else {
383 false
384 }
385 });
386 if !keep_going {
387 return false;
388 }
389 if remaining.is_empty() {
390 return true;
391 }
392 }
393 remaining.is_empty()
394 }
395
396 /// Zero-alloc equivalent of `self.to_string() == target`. Walks the
397 /// contained tokens byte-by-byte, skipping COMMENT tokens (matching
398 /// `Display for Tokens`) and prefixing ARG tokens with `#` (matching
399 /// `Display for Token`). Returns `true` iff the rendered text exactly
400 /// equals `target`. Used by DefMacro bodies that check keyword
401 /// values like `true` / `false` / `swapnumber` without wanting to
402 /// allocate a fresh `String` per invocation.
403 pub fn eq_text(&self, target: &str) -> bool {
404 let mut remaining = target;
405 for t in &self.0 {
406 if t.code == Catcode::COMMENT {
407 continue;
408 }
409 if t.code == Catcode::ARG {
410 if !remaining.starts_with('#') {
411 return false;
412 }
413 remaining = &remaining[1..];
414 }
415 let ok = t.with_str(|text| {
416 if remaining.starts_with(text) {
417 remaining = &remaining[text.len()..];
418 true
419 } else {
420 false
421 }
422 });
423 if !ok {
424 return false;
425 }
426 }
427 remaining.is_empty()
428 }
429
430 // Just a synonym for unlist in this reversion case
431 pub fn revert(self) -> Vec<Token> { self.0 }
432
433 /// to_number casts back to a parsed Number (usually via gullet::read_number)
434 /// which had to be re-converted to a Tokens for reentering the expansion flow
435 pub fn to_number(&self) -> Number {
436 if self.is_empty() {
437 log::debug!("to_number called on empty Tokens — returning 0 (TeX-compatible default)");
438 Number::default()
439 } else {
440 Number::new(self.to_string().parse::<i64>().unwrap_or(0))
441 }
442 }
443
444 /// to_dimension casts back to a parsed Dimension (usually via gullet::read_dimension)
445 /// which had to be re-converted to a Tokens for reentering the expansion flow
446 pub fn to_dimension(&self) -> Dimension {
447 // TODO: How do we enhance here to be able to use the current font information from state::
448 // Using the state::ful variations makes it impossible to work with the From/Into standard Rust
449 // traits. Should we do stateful From/Into ?
450 Dimension::new_f64(Dimension::spec_to_f64(&self.to_string()).unwrap_or_default())
451 }
452
453 /// to_glue casts back to a parsed Glue (usually via gullet::read_glue)
454 /// which had to be re-converted to a Tokens for reentering the expansion flow
455 pub fn to_glue(&self) -> Glue {
456 let token: Token = self.into();
457 token.to_glue()
458 }
459
460 /// to_mu_glue casts back to a parsed MuGlue (usually via gullet::read_mu_glue)
461 /// which had to be re-converted to a Tokens for reentering the expansion flow
462 pub fn to_mu_glue(&self) -> MuGlue {
463 let token: Token = self.into();
464 token.to_mu_glue()
465 }
466
467 /// to_mu_dimension casts back to a parsed MuGlue (usually via gullet::read_mu_glue)
468 /// which had to be re-converted to a Tokens for reentering the expansion flow
469 pub fn to_mu_dimension(&self) -> MuDimension {
470 let token: Token = self.into();
471 token.to_mu_dimension()
472 }
473
474 /// to_float casts back to a parsed Float (usually via gullet::read_float)
475 /// which had to be re-converted to a Tokens for reentering the expansion flow
476 pub fn to_float(&self) -> Float {
477 if self.is_empty() {
478 log::debug!("to_float called on empty Tokens — returning 0.0 (TeX-compatible default)");
479 Float::default()
480 } else {
481 Float::new_f64(self.to_string().parse::<f64>().unwrap_or(0.0))
482 }
483 }
484
485 /// to_keyvals casts back to a parsed KeyVals (usually via a KeyVals parameter type)
486 /// which had to be re-converted to a Tokens for reentering the expansion flow
487 pub fn to_keyvals(&self) -> Result<KeyVals> {
488 let mut toks_iter = self.unlist_ref().iter();
489 let mut kvs = KeyVals::default();
490 while let Some(key) = toks_iter.next() {
491 key.with_str(|key_str| {
492 if let Some(value) = toks_iter.next() {
493 kvs.add_value(key_str, ArgWrap::Token(*value), false, false)
494 } else {
495 kvs.add_value(key_str, ArgWrap::Tokens(Tokens!()), false, false)
496 }
497 })?;
498 }
499 Ok(kvs)
500 }
501
502 /// Methods for overloaded ops.
503 pub fn equals(&self, other: Tokens) -> bool {
504 let self_tokens: Vec<&Token> = self
505 .0
506 .iter()
507 .filter(|t| t.code != Catcode::COMMENT && t.code != Catcode::MARKER)
508 .collect();
509 let other_tokens: Vec<&Token> = other
510 .0
511 .iter()
512 .filter(|t| t.code != Catcode::COMMENT && t.code != Catcode::MARKER)
513 .collect();
514 if self_tokens.len() != other_tokens.len() {
515 false
516 } else {
517 self_tokens
518 .into_iter()
519 .zip(other_tokens)
520 .all(|(t_self, t_other)| *t_self == *t_other)
521 }
522 }
523
524 /// returns self, for compatibility convenience with `Option`
525 pub fn unwrap_or_default(self) -> Tokens { self }
526 /// returns self, for compatibility convenience with `Option`
527 pub fn unwrap(&self) -> &Tokens { self }
528
529 /// A string form which is primarily used for error-reporting
530 pub fn stringify(&self) -> String {
531 s!(
532 "Tokens[{}]",
533 &self
534 .0
535 .iter()
536 .map(ToString::to_string)
537 .collect::<Vec<_>>()
538 .join(",")
539 )
540 }
541 /// digest the current `Tokens`
542 pub fn be_digested(self) -> Result<Digested> { stomach::digest(self) }
543
544 /// neutralize each token
545 pub fn neutralize(self, extraspecials: &[char]) -> Tokens {
546 Tokens(
547 self
548 .0
549 .into_iter()
550 .map(|t| t.neutralize(extraspecials))
551 .collect::<Vec<_>>(),
552 )
553 }
554 /// Checks if any BEGIN/END code groups are correctly nested and closed
555 pub fn is_balanced(&self) -> bool { Tokens::slice_is_balanced(&self.0) }
556
557 /// [`Tokens::is_balanced`] of a token slice.
558 pub fn slice_is_balanced(tokens: &[Token]) -> bool {
559 let mut level = 0;
560 for t in tokens {
561 level += match t.get_catcode() {
562 Catcode::BEGIN => 1,
563 Catcode::END => -1,
564 _ => 0,
565 };
566 if level < 0 {
567 // a negative level encountered at any point is ill-formed,
568 // return early
569 return false;
570 }
571 }
572 level == 0
573 }
574
575 /// The body as `macro_call` substitutes it (tex.web §390: a macro's body is stored with each `#n` as an
576 /// `out_param` token carrying `n`): runs of the body's own tokens and the parameters between them, in order.
577 /// Computed once per definition ([`crate::definition::expandable::Expandable`]), so a call copies runs
578 /// instead of testing every token and parsing every parameter's number.
579 pub fn substitution_plan(&self) -> Box<[BodyPiece]> {
580 let mut plan = Vec::new();
581 let mut start = 0;
582 for (at, token) in self.0.iter().enumerate() {
583 if token.get_catcode() == Catcode::ARG {
584 if start < at {
585 plan.push(BodyPiece::Run(start as u32, at as u32));
586 }
587 let index = token.with_str(|ts| ts.parse::<usize>().unwrap_or(0));
588 plan.push(BodyPiece::Parameter(index));
589 start = at + 1;
590 }
591 }
592 if start < self.0.len() {
593 plan.push(BodyPiece::Run(start as u32, self.0.len() as u32));
594 }
595 plan.into_boxed_slice()
596 }
597
598 // NOTE: Assumes each arg either undef or also Tokens
599 // Using inline accessors on those assumptions
600 /// substitutes the parameters (ARG catcode) in a Tokens list for concrete arguments
601 pub fn substitute_parameters(&self, args: &[Option<Cow<Tokens>>]) -> Self {
602 // Pre-size to the template plus every present argument once: for the
603 // common single-use body that is the result's length plus the parameter
604 // tokens it replaces, so the push/extend loop below never regrows (a
605 // template-only size regrew on every argument-bearing expansion;
606 // expansion bodies can be thousands of tokens in the expl3 kernel). An
607 // empty body (`\@gobble`, `\use_none:n`) returns before any allocation; a
608 // non-empty one reserves for every present argument without scanning the
609 // body for parameters, so one that names none over-reserves, harmlessly:
610 // the hot caller (`Expandable::invoke`) only gets here for a body that has one.
611 if self.0.is_empty() {
612 return Tokens::new(Vec::new());
613 }
614 let args_len: usize = args
615 .iter()
616 .flatten()
617 .map(|arg| arg.as_ref().unlist_ref().len())
618 .sum();
619 let mut result = Vec::with_capacity(self.0.len() + args_len);
620 for token in self.0.iter() {
621 if token.get_catcode() != Catcode::ARG {
622 // Non-match; copy it
623 result.push(*token);
624 } else {
625 let idx = token.with_str(|ts| ts.parse::<usize>().unwrap_or(0));
626 if idx > 0
627 && idx <= args.len()
628 && let Some(ref arg) = args[idx - 1]
629 {
630 // `arg` is `Cow<Tokens>`; iterate via `unlist_ref` + copy
631 // (Tokens is a Vec<Token> of `Copy` tokens). Avoids the
632 // previous `clone().into_owned().unlist()` chain which
633 // double-cloned the Vec when `arg` was `Cow::Borrowed`.
634 result.extend(arg.as_ref().unlist_ref().iter().copied());
635 }
636 }
637 }
638 Tokens::new(result)
639 }
640
641 /// Consumes a Tokens to a string containing TeX that created it (or could have).
642 /// Note that this is not necessarily the original TeX code; expansions or other substitutions may
643 /// have taken place.
644 ///
645 /// **Design decision:** The Perl `UnTeX` inserts `%\n` line-breaks (TeX comment + newline) when
646 /// a token string would exceed 78 characters. The Rust port deliberately omits this feature.
647 /// Line-break insertion is purely cosmetic and makes test expectations fragile — the `%\n`
648 /// appears verbatim in `tex=` attributes of `ltx:Math` elements, causing test XML files to
649 /// contain `% ` escape sequences that depend on exact token lengths. We instead always
650 /// produce compact, single-line output. Test `.xml` files should not contain `% `.
651 pub fn untex(self) -> String {
652 // `VecDeque::from(Vec)` reuses the Vec's heap buffer directly
653 // (no second allocation), unlike `.into_iter().collect()`.
654 let mut tokens: VecDeque<Token> = VecDeque::from(self.revert());
655 let mut tex_string = String::new();
656 let mut length = 0;
657 let mut level = 0;
658 let mut prevs = String::new();
659 // the token's text (its `Display`), spelled in a buffer reused across tokens
660 let mut token_string = String::new();
661 let mut prevcc = Catcode::COMMENT;
662 while let Some(token) = tokens.pop_front() {
663 let cc = token.get_catcode();
664 if cc == Catcode::COMMENT {
665 continue;
666 }
667 token_string.clear();
668 let _ = write!(token_string, "{token}");
669 // Note: \n only-used to fail alphanumeric test
670 let first_char = token_string.chars().next().unwrap_or('\n');
671 if cc == Catcode::LETTER {
672 // keep "words" together, just for aesthetics
673 while !tokens.is_empty() && tokens[0].get_catcode() == Catcode::LETTER {
674 tokens
675 .pop_front()
676 .unwrap()
677 .with_str(|front_str| token_string.push_str(front_str));
678 }
679 }
680
681 let l = token_string.len();
682 if cc == Catcode::BEGIN {
683 level += 1;
684 }
685 // Seems a reasonable & safe time to line break, for readability, etc.
686 if cc == Catcode::SPACE && token_string == "\n" {
687 // preserve newlines already present
688 if length > 0 {
689 tex_string.push_str(&token_string);
690 length = 0;
691 }
692 // If this token is a letter (or otherwise starts with a letter or digit): space or linebreak
693 } else {
694 let last_prevs = prevs.chars().last().unwrap_or('_');
695 // Perl: $STATE->lookupCatcode($1) == CC_LETTER
696 // Must use actual catcode lookup, not just is_alphabetic(), because
697 // characters like @ may have catcode LETTER in some contexts.
698 let prev_is_letter = crate::state::lookup_catcode(last_prevs)
699 .map(|cc| cc == Catcode::LETTER)
700 .unwrap_or_else(|| last_prevs.is_alphabetic());
701
702 if (cc == Catcode::LETTER || (cc == Catcode::OTHER && first_char.is_alphanumeric()))
703 && prevcc == Catcode::CS
704 && prev_is_letter
705 {
706 // Insert a (virtual) space before a letter if previous token was a CS w/letters
707 // This is required for letters, but just aesthetic for digits (to me?)
708 let space = ' ';
709 tex_string.push(space);
710 tex_string.push_str(&token_string);
711 length += 1 + l;
712 } else {
713 tex_string.push_str(&token_string);
714 length += l;
715 }
716 if cc == Catcode::END {
717 level -= 1;
718 }
719 std::mem::swap(&mut prevs, &mut token_string);
720 prevcc = cc;
721 }
722 }
723 // Patch up nesting for valid TeX !!!
724 match level {
725 1..=i32::MAX => {
726 for _ in 0..level {
727 tex_string.push('}');
728 }
729 },
730 i32::MIN..=-1 => {
731 // Prepend `-level` opening braces in one alloc (was O(n²) with
732 // String::from("{") + &tex_string per iteration).
733 let n = (-level) as usize;
734 let mut prefixed = String::with_capacity(n + tex_string.len());
735 for _ in 0..n {
736 prefixed.push('{');
737 }
738 prefixed.push_str(&tex_string);
739 tex_string = prefixed;
740 },
741 0 => {},
742 }
743 tex_string
744 }
745
746 /// [`untex`](Tokens::untex), typed — the blessed way to get TeX markup out of
747 /// a `Tokens` and back into a tokenizing sink.
748 ///
749 /// Prefer this over `untex()` whenever the string is destined for
750 /// `Tokenize!` / `mouth::tokenize` / `mouth::tokenize_internal`: it is the
751 /// only [`struct@Tokens`]→[`TeXString`] conversion, so the sink's signature proves
752 /// the round trip cannot weld a control word (`\v S` stays `\v S`, not
753 /// `\vS`). `untex()` itself is unchanged for the callers that want a plain
754 /// `String` (a `tex=` attribute, a log message, a comparison).
755 pub fn untex_string(self) -> TeXString { TeXString::assembled(self.untex()) }
756
757 /// Packs repeated CC_PARAM tokens into CC_ARG tokens for use as a macro body (and other token
758 /// lists) Also unwraps \noexpand tokens, since that is also needed for macro bodies
759 /// (but not strictly part of packing parameters)
760 pub fn pack_parameters(self) -> Result<Self> {
761 // Result is at most the same size as input (param-digit pairs
762 // collapse 2→1; other tokens copy 1→1). Pre-sizing avoids the
763 // initial Vec doublings on 1k+ token expansions (common for
764 // expl3 macros).
765 let mut rescanned = Vec::with_capacity(self.0.len());
766 // `VecDeque::from(Vec)` reuses the Vec's heap buffer directly (no
767 // second allocation), unlike `into_iter().collect()` which copies.
768 let mut toks: VecDeque<Token> = VecDeque::from(self.unlist());
769 // tex.web resolves tokens by MEANING during macro-definition scanning
770 // (get_next assigns cur_cmd=mac_param for a CS `\let` to a catcode-6
771 // `#`), so an IMPLICIT parameter token participates in `#1`/`##`
772 // pairing exactly like a literal `#`. Generated code relies on it:
773 // ctexart.cls L1194 `\cs_new_protected:Npn \__ctex_patch_toc_width:n
774 // \c_parameter_token 1 { … \c_parameter_token 1 … }` (docstrip writes
775 // the CS spelling to survive catcode changes) — without this, the CS
776 // leaks literally into hook names → `\csname __hook package/#…` errors
777 // across the 50-doc ctex family.
778 let is_param_tok = |t: &Token| {
779 t.get_catcode() == Catcode::PARAM
780 || (t.get_catcode().is_active_or_cs()
781 && crate::state::with_meaning(t, |m| {
782 matches!(m, Some(crate::common::store::Stored::Token(l))
783 if l.get_catcode() == Catcode::PARAM)
784 }))
785 };
786 while let Some(mut t) = toks.pop_front() {
787 if t.get_catcode() != Catcode::PARAM && is_param_tok(&t) {
788 t = T_PARAM!();
789 }
790 if t.get_catcode() == Catcode::PARAM && !toks.is_empty() {
791 let next_t = toks.pop_front();
792 let next_cc = next_t.as_ref().map(|t| t.get_catcode());
793 if next_cc == Some(Catcode::OTHER) {
794 // only group clear match token cases
795 rescanned.push(Token!(sym next_t.unwrap().get_sym(), Catcode::ARG));
796 } else if next_cc == Some(Catcode::PARAM) || next_t.as_ref().map(is_param_tok) == Some(true)
797 {
798 rescanned.push(t);
799 } else {
800 // A PARAM (`#`) followed by neither a digit nor another `#` is, in
801 // real documents, almost always a `\halign`/`\valign` alignment-cell
802 // marker embedded in a macro body (e.g. `\def\foo{\halign{#\hfil&...}}`)
803 // or the `#{` end-of-parameter-text delimiter — both VALID TeX where
804 // the catcode-6 `#` must survive losslessly into the template/preamble.
805 // Real TeX resolves the parameter-vs-cell ambiguity during alignment
806 // processing, a lower level than LaTeXML operates at, so we cannot
807 // reliably tell this apart from a genuine typo.
808 //
809 // Perl's packParameters (Tokens.pm L139) emits a *counted* Error here
810 // AND drops both tokens, corrupting the template — but Perl rarely
811 // reaches it (it often can't find the offending package and skips the
812 // raw load). We DO raw-load such packages, so erroring+dropping broke
813 // the error-free target for the common halign-in-macro idiom. Preserve
814 // both tokens and log at Info (non-counted) instead. Documented as a
815 // beneficial divergence in docs/parity/KNOWN_PERL_ERRORS.md item 1. Witness
816 // 2006.02269 (easyeqn.sty `{MATRIX}` env → `$\mathstrut##$` template;
817 // 2 errors → 0).
818 Info!(
819 "misdefined",
820 "expansion",
821 &s!(
822 "Lone # (catcode PARAM) preserved as alignment/template marker. In expansion {}",
823 Tokens::new(toks.clone().into_iter().collect()).to_string()
824 )
825 );
826 rescanned.push(t);
827 if let Some(nt) = next_t {
828 rescanned.push(nt);
829 }
830 }
831 } else {
832 rescanned.push(t);
833 }
834 }
835 Ok(Tokens::new(rescanned))
836 }
837
838 /// Trims outer braces (if they balance each other).
839 /// Strips exactly 1 layer of matching outer braces by default.
840 /// Should this also trim whitespace? or only if there are braces?
841 pub fn strip_braces(self) -> Self { self.strip_braces_n(1) }
842
843 /// Trims `layers` outer brace pairs (if they balance each other).
844 /// Also trims whitespace *outer to* the removed braces.
845 /// Follows the Perl Tokens.pm algorithm: first collects all balanced
846 /// brace pairs, then strips from outside-in, only removing pairs that
847 /// span the full remaining width.
848 pub fn strip_braces_n(self, mut layers: usize) -> Self {
849 let tokens = self.0;
850 let n = tokens.len();
851 if n <= 1 {
852 return Tokens::new(tokens);
853 }
854
855 let mut i0: usize = 0;
856 let mut i1: usize = n;
857
858 // skip past spaces at ends
859 while i0 < i1 && tokens[i0].get_catcode() == Catcode::SPACE {
860 i0 += 1;
861 }
862 while i1 > i0 && tokens[i1 - 1].get_catcode() == Catcode::SPACE {
863 i1 -= 1;
864 }
865
866 // Collect balanced pairs (innermost first due to stack order)
867 let mut opens: Vec<usize> = Vec::new();
868 let mut pairs: Vec<(usize, usize)> = Vec::new();
869 for i in i0..i1 {
870 match tokens[i].get_catcode() {
871 Catcode::BEGIN => opens.push(i),
872 Catcode::END => {
873 if let Some(j) = opens.pop() {
874 pairs.push((j, i));
875 } else {
876 return Tokens::new(tokens); // Unbalanced: Too many }
877 }
878 },
879 _ => {},
880 }
881 }
882 if !opens.is_empty() {
883 return Tokens::new(tokens); // Unbalanced: Too many {
884 }
885
886 // Strip layers from outside-in.
887 // pairs is ordered innermost-first, so pop() gives outermost pair first.
888 while layers > 0 {
889 layers -= 1;
890 if let Some((j0, j1)) = pairs.pop()
891 && j0 == i0
892 && j1 == i1 - 1
893 {
894 i0 += 1;
895 i1 -= 1;
896 }
897 }
898
899 // Empty after stripping
900 if i0 >= i1 {
901 return Tokens::new(Vec::new());
902 }
903
904 if i0 > 0 || i1 < n {
905 Tokens::new(tokens[i0..i1].to_vec())
906 } else {
907 Tokens::new(tokens)
908 }
909 }
910}
911
912// `impl ToTokens` blocks below are gated on the `codegen` feature
913// (audit DEP-14, 2026-05-18). They are called only at compile time by
914// `latexml_codegen` proc-macros via `quote!{ ... #tokens_value ... }`
915// splices. Resolver v2 keeps proc-macro feature unification isolated,
916// so the runtime `latexml_core` linked into `latexml_oxide` does NOT
917// compile these impls — dropping `proc-macro2` (~93 KiB) and `quote`
918// from the runtime binary's dependency graph.
919#[cfg(feature = "codegen")]
920impl ToTokens for Tokens {
921 fn to_tokens(&self, stream: &mut TokenStream) {
922 let d = &self.0;
923 stream.extend(quote! {
924 Tokens::new(<[Token]>::into_vec(Box::new([ #(#d),* ])))
925 });
926 }
927}
928
929#[cfg(feature = "codegen")]
930impl ToTokens for Catcode {
931 fn to_tokens(&self, stream: &mut TokenStream) {
932 use crate::token::Catcode::*;
933 let kind = match *self {
934 ESCAPE => "ESCAPE",
935 BEGIN => "BEGIN",
936 END => "END",
937 MATH => "MATH",
938 ALIGN => "ALIGN",
939 EOL => "EOL",
940 PARAM => "PARAM",
941 SUPER => "SUPER",
942 SUB => "SUB",
943 SPACE => "SPACE",
944 // Non-primitive
945 IGNORE => "IGNORE",
946 LETTER => "LETTER",
947 OTHER => "OTHER",
948 ACTIVE => "ACTIVE",
949 COMMENT => "COMMENT",
950 INVALID => "INVALID",
951 CS => "CS",
952 MARKER => "MARKER",
953 ARG => "ARG",
954 };
955 stream.append(Ident::new("Catcode", Span::call_site()));
956 stream.append(Punct::new(':', Spacing::Joint));
957 stream.append(Punct::new(':', Spacing::Alone));
958 stream.append(Ident::new(kind, Span::call_site()));
959 }
960}
961
962#[cfg(feature = "codegen")]
963impl ToTokens for Token {
964 fn to_tokens(&self, stream: &mut TokenStream) {
965 let code = self.get_catcode();
966 self.with_str(|text| {
967 stream.extend(quote! {
968 Token {
969 text: latexml_core::common::arena::pin_static(#text),
970 code: #code,
971 prov: 0,
972 // Emitted into the consumer crate; the cfg resolves there (the feature
973 // propagates from latexml_oxide). See docs/performance/SOURCE_PROVENANCE.md §3.1.1.
974 #[cfg(feature = "token-locators")]
975 loc: 0u32
976 }
977 })
978 });
979 }
980}
981
982#[cfg(test)]
983mod tests {
984 use super::*;
985 use crate::common::arena;
986
987 /// A body's substitution plan is its runs and parameters in order (a repeated parameter twice, an out-of-range
988 /// one kept as written), and substituting through it gives `substitute_parameters`' list.
989 #[test]
990 fn substitution_plan_reproduces_substitute_parameters() {
991 let body = Tokens::new(vec![
992 T_LETTER!("a"),
993 T_ARG!(1),
994 T_LETTER!("b"),
995 T_ARG!(2),
996 T_ARG!(1),
997 T_ARG!(3),
998 T_LETTER!("c"),
999 ]);
1000 let plan = body.substitution_plan();
1001 assert_eq!(&*plan, &[
1002 BodyPiece::Run(0, 1),
1003 BodyPiece::Parameter(1),
1004 BodyPiece::Run(2, 3),
1005 BodyPiece::Parameter(2),
1006 BodyPiece::Parameter(1),
1007 BodyPiece::Parameter(3),
1008 BodyPiece::Run(6, 7),
1009 ]);
1010 let one = Tokens::new(vec![T_LETTER!("x"), T_LETTER!("y")]);
1011 let two = Tokens::new(vec![T_LETTER!("z")]);
1012 let args = [&one, &two];
1013 let mut via_plan = Vec::new();
1014 for piece in plan.iter() {
1015 match *piece {
1016 BodyPiece::Run(start, end) => {
1017 via_plan.extend_from_slice(&body.unlist_ref()[start as usize..end as usize])
1018 },
1019 BodyPiece::Parameter(n) => {
1020 if let Some(arg) = n.checked_sub(1).and_then(|i| args.get(i)) {
1021 via_plan.extend_from_slice(arg.unlist_ref());
1022 }
1023 },
1024 }
1025 }
1026 let substituted = body.substitute_parameters(
1027 &args
1028 .iter()
1029 .map(|a| Some(Cow::Borrowed(*a)))
1030 .collect::<Vec<_>>(),
1031 );
1032 assert_eq!(&via_plan, substituted.unlist_ref());
1033 }
1034
1035 #[test]
1036 fn empty_tokens_len_zero() {
1037 let t = Tokens::new(vec![]);
1038 assert_eq!(t.len(), 0);
1039 assert!(t.is_empty());
1040 }
1041
1042 #[test]
1043 fn tokens_new_preserves_order() {
1044 let t = Tokens::new(vec![T_LETTER!("a"), T_LETTER!("b"), T_LETTER!("c")]);
1045 assert_eq!(t.len(), 3);
1046 let list = t.unlist();
1047 let texts: Vec<String> = list.iter().map(|t| arena::to_string(t.text)).collect();
1048 assert_eq!(texts, vec!["a", "b", "c"]);
1049 }
1050
1051 #[test]
1052 fn tokens_unlist_ref_does_not_consume() {
1053 let t = Tokens::new(vec![T_LETTER!("a")]);
1054 let r = t.unlist_ref();
1055 assert_eq!(r.len(), 1);
1056 // t is still usable after unlist_ref.
1057 assert_eq!(t.len(), 1);
1058 }
1059
1060 #[test]
1061 fn tokens_stringify_format() {
1062 let t = Tokens::new(vec![T_LETTER!("a"), T_LETTER!("b")]);
1063 let s = t.stringify();
1064 assert!(s.starts_with("Tokens["), "got {s:?}");
1065 assert!(s.ends_with(']'));
1066 assert!(s.contains("a"));
1067 assert!(s.contains("b"));
1068 }
1069
1070 #[test]
1071 fn tokens_equals_ignores_comments_and_markers() {
1072 // equals() filters out COMMENT and MARKER tokens before comparing.
1073 let a = Tokens::new(vec![T_LETTER!("x"), T_COMMENT!("%"), T_LETTER!("y")]);
1074 let b = Tokens::new(vec![T_LETTER!("x"), T_LETTER!("y")]);
1075 assert!(a.equals(b), "comments should be ignored in equals()");
1076 }
1077
1078 #[test]
1079 fn tokens_equals_different_content() {
1080 let a = Tokens::new(vec![T_LETTER!("x")]);
1081 let b = Tokens::new(vec![T_LETTER!("y")]);
1082 assert!(!a.equals(b));
1083 }
1084
1085 #[test]
1086 fn tokens_equals_different_lengths() {
1087 let a = Tokens::new(vec![T_LETTER!("x")]);
1088 let b = Tokens::new(vec![T_LETTER!("x"), T_LETTER!("y")]);
1089 assert!(!a.equals(b));
1090 }
1091
1092 #[test]
1093 fn tokens_equals_both_empty() {
1094 let a = Tokens::new(vec![]);
1095 let b = Tokens::new(vec![]);
1096 assert!(a.equals(b));
1097 }
1098
1099 #[test]
1100 fn tokens_unwrap_self_identity() {
1101 let t = Tokens::new(vec![T_LETTER!("x")]);
1102 assert_eq!(t.unwrap().len(), 1);
1103 }
1104
1105 #[test]
1106 fn tokens_revert_returns_vec() {
1107 let t = Tokens::new(vec![T_LETTER!("x"), T_LETTER!("y")]);
1108 let v = t.revert();
1109 assert_eq!(v.len(), 2);
1110 }
1111
1112 #[test]
1113 fn tokens_display_joins_content() {
1114 // Display on Tokens concatenates each token's Display.
1115 let t = Tokens::new(vec![T_LETTER!("a"), T_LETTER!("b"), T_LETTER!("c")]);
1116 let s = format!("{t}");
1117 assert_eq!(s, "abc");
1118 }
1119}
1120
1121#[cfg(test)]
1122mod untex_control_word_space_tests {
1123 use super::*;
1124
1125 /// `untex()` must re-emit the space that terminates a control word;
1126 /// `to_string()` documents that it does not, and the two must not be
1127 /// confused at a call site that needs valid TeX back.
1128 ///
1129 /// TeX CONSUMES the space after a control word, so by token-time it is gone
1130 /// as data — `\v S` and `\vS` tokenize to different things but a naive
1131 /// concatenation of the first yields the second. `\vS` exists in no LaTeX.
1132 ///
1133 /// This is not academic: `\bib@@names` used `to_string()` where Perl uses
1134 /// `UnTeX` (BibTeX.pool.ltxml L277), which mangled every space-form accent in
1135 /// a bibliography author name — `{\v S}`, `{\c c}`, `{\" a}`, i.e. most
1136 /// non-English names — into an undefined macro. ~+2800 error documents per
1137 /// corpus on the 2026-07-26 sandbox sweep.
1138 #[test]
1139 fn untex_reemits_the_space_that_terminates_a_control_word() {
1140 for (src, expect_untex) in [
1141 (r"\v Spakov", r"\v Spakov"), // control word + space + LETTER: space needed
1142 (r"\c calves", r"\c calves"), // likewise
1143 (r"\v{S}pakov", r"\v{S}pakov"), // braced argument: no space needed, none added
1144 ] {
1145 let toks = crate::mouth::tokenize(src);
1146 assert_eq!(
1147 toks.clone().untex(),
1148 expect_untex,
1149 "untex({src:?}) must round-trip to valid TeX"
1150 );
1151 // Re-tokenizing the untex output must yield the SAME control sequence —
1152 // the property that actually matters, and the one that broke.
1153 let first = |t: Tokens| {
1154 t.unlist()
1155 .first()
1156 .map(|t| t.to_string())
1157 .unwrap_or_default()
1158 };
1159 assert_eq!(
1160 first(crate::mouth::tokenize(toks.clone().untex_string())),
1161 first(crate::mouth::tokenize(src)),
1162 "untex({src:?}) changed the leading control sequence on re-tokenization"
1163 );
1164 }
1165 }
1166
1167 /// The documented contract of the other direction, pinned so nobody
1168 /// "helpfully" makes `Display` TeX-correct and silently changes every
1169 /// keyword-ish `to_string()` caller in the tree.
1170 #[test]
1171 fn to_string_deliberately_does_not_reemit_the_space() {
1172 let toks = crate::mouth::tokenize(r"\v Spakov");
1173 assert_eq!(
1174 toks.to_string(),
1175 r"\vSpakov",
1176 "Display for Tokens is documented as NOT producing valid TeX; if this \
1177 changes, audit every to_string() caller before updating the expectation"
1178 );
1179 }
1180}
1181
1182/// The guard itself: proof, at COMPILE time, that a welded `String` cannot reach
1183/// a tokenizing sink.
1184///
1185/// This module contains no runtime assertions worth the name — its whole value is
1186/// that it stops compiling if the property is lost. It is `#[cfg(test)]`, so it is
1187/// checked whenever the test target is built (`cargo test --tests`, and so CI).
1188#[cfg(test)]
1189mod texstring_guard_tests {
1190 use super::*;
1191
1192 /// Neither `String: Into<TeXString>` nor `&String: Into<TeXString>` may hold.
1193 ///
1194 /// Those are the shapes a control-word-welding `Tokens::to_string()` arrives in
1195 /// (`s!(…)`/`format!(…)` gives the first, `&some_local` the second), so an
1196 /// implicit conversion would silently reopen the bug this type exists to close
1197 /// (`\bib@@names` PR #399, `dcolumn`/`overpic` PR #400, MathSciNet review path
1198 /// issue 410).
1199 ///
1200 /// Mechanism (the `static_assertions::assert_not_impl_any!` trick, hand-rolled
1201 /// to avoid the dependency): a helper trait with a blanket impl for everything
1202 /// plus a second impl gated on `Into<TeXString>`. If BOTH apply the item path is
1203 /// ambiguous and this fails to compile; if only the blanket one applies it
1204 /// resolves. So "still compiles" == "the conversion does not exist".
1205 ///
1206 /// A `&str` whose lifetime is shorter than `'static` is rejected too, but not
1207 /// by this assertion — an unconstrained `&'_ str` here infers to `&'static str`,
1208 /// which is exactly the case that MUST convert. The compiler enforces that half
1209 /// at the call site instead, as an E0521 "borrowed data escapes … `'1` must
1210 /// outlive `'static`".
1211 const _NO_IMPLICIT_STRING_CONVERSION: fn() = || {
1212 trait AmbiguousIfConvertible<A> {
1213 fn some_item() {}
1214 }
1215 impl<T> AmbiguousIfConvertible<()> for T {}
1216 impl<T: Into<TeXString>> AmbiguousIfConvertible<u8> for T {}
1217
1218 let _ = <String as AmbiguousIfConvertible<_>>::some_item;
1219 let _ = <&String as AmbiguousIfConvertible<_>>::some_item;
1220 };
1221
1222 /// The other half: a `&'static str` — i.e. every TeX literal a binding types
1223 /// out — must keep converting implicitly, or ~125 call sites would need
1224 /// ceremony for nothing.
1225 const _LITERALS_STILL_CONVERT: fn() = || {
1226 fn sink(_: impl Into<TeXString>) {}
1227 sink(r"\relax");
1228 sink(TeXString::assembled(String::new()));
1229 };
1230
1231 /// …while the three blessed ways in must all still work. Kept beside the
1232 /// negative assertion so a "fix" that deletes the conversions to satisfy it is
1233 /// caught here.
1234 #[test]
1235 fn the_three_blessed_constructors_reach_the_sink() {
1236 // 1. a literal
1237 assert_eq!(crate::mouth::tokenize(r"\relax").to_string(), r"\relax");
1238 // 2. untex_string — the space that terminates `\v` survives the round trip
1239 let welded = crate::mouth::tokenize(r"\v Spakov");
1240 assert_eq!(
1241 crate::mouth::tokenize(welded.clone().untex_string()).to_string(),
1242 r"\vSpakov",
1243 "re-tokenizing untex_string() output must give back the SAME tokens \
1244 (whose Display is again the welded form) — i.e. \\v stayed \\v"
1245 );
1246 // …which is precisely what the welded string does NOT do:
1247 let welded_again = crate::mouth::tokenize(TeXString::assembled(welded.to_string()));
1248 assert_eq!(
1249 welded_again.unlist().first().map(|t| t.to_string()),
1250 Some(r"\vSpakov".to_string()),
1251 "the welded path collapses \\v + Spakov into the single undefined CS \
1252 \\vSpakov — the bug TeXString exists to make hard to write"
1253 );
1254 // 3. assembled
1255 assert_eq!(
1256 crate::mouth::tokenize(TeXString::assembled(format!(r"\the{}", "section"))).to_string(),
1257 r"\thesection"
1258 );
1259 }
1260}