latexml_core/mouth.rs
1use core::ops::{Range, RangeBounds};
2// TODO:
3// use encoding::all::ISO_8859_1;
4// use encoding::{EncoderTrap, Encoding};
5use std::{
6 collections::VecDeque,
7 fmt,
8 fs::File,
9 io,
10 io::{BufReader, prelude::*},
11 rc::Rc,
12 str,
13 sync::LazyLock,
14};
15
16use regex::Regex;
17
18use crate::{
19 common::{
20 arena::SymStr,
21 error::{emit_warn, *},
22 locator::Locator,
23 numeric_ops::NumericOps,
24 object::Object,
25 },
26 state::*,
27 token::*,
28 tokens::{NO_TOKENS, TeXString, Tokens},
29 util::pathname,
30};
31
32static TRAILING_SPACE_CHARS: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?s) +$").unwrap());
33
34const READLINE_PROGRESS_QUANTUM: usize = 25;
35
36#[derive(PartialEq, Eq, Debug, Copy, Clone)]
37pub enum FoodType {
38 File,
39 // Binding,
40 HTTP,
41 HTTPS,
42 Literal,
43}
44
45impl FoodType {
46 /// TODO: Should be a From trait implementation, but am not allowed due to both &str and Option
47 /// being external. Argh.
48 pub fn opt_from_str(text: &str) -> Option<FoodType> {
49 use self::FoodType::*;
50 match text.to_lowercase().as_str() {
51 "file" => Some(File),
52 // "binding" => Some(Binding),
53 "http" => Some(HTTP),
54 "https" => Some(HTTPS),
55 "literal" => Some(Literal),
56 _ => None,
57 }
58 }
59}
60
61static LINEBREAK_REGEX: LazyLock<Regex> =
62 LazyLock::new(|| Regex::new(r"(?s:\r\n?)|(?s:\n)").unwrap());
63// LOWERHEX_REGEX removed — replaced with direct matches!() check in tex_hex_caret path.
64static _SANITIZE_LINE_REGEX: LazyLock<Regex> =
65 LazyLock::new(|| Regex::new(r"((\\ )*)\s*$").unwrap());
66
67#[derive(Debug, Default)]
68pub struct MouthOptions {
69 pub fordefinitions: bool,
70 pub at_letter: bool,
71 pub notes: bool,
72 pub content: Option<String>,
73 /// The string IS a document source (a file handed over as content: the
74 /// cortex/in-process API, filecontents, an `\openin` overlay): keep its
75 /// bytes and decode each line lazily under the encoding current when the
76 /// line is read, exactly like a file mouth — so the pdfTeX byte mouth (K10)
77 /// switched on by a package mid-document reaches the document's own text.
78 /// Internal strings (`Tokenize!` bodies, `\scantokens`) stay pre-decoded.
79 pub lazy_decode: bool,
80 /// The mouth reads a FILE — on disk or held in memory (filecontents, an
81 /// `\openout` file): tex.web's `name>17` input level. Its end is an end of
82 /// file for a balanced read (runaway, §338-339), whatever `foodtype` says
83 /// about how it is read. Set by [`Mouth::create`]'s file paths.
84 pub file_level: bool,
85 pub foodtype: Option<FoodType>,
86 pub source: Option<String>,
87 pub shortsource: Option<String>,
88}
89
90#[derive(Debug)]
91pub struct Mouth {
92 fordefinitions: bool,
93 at_letter: bool,
94 notes: bool,
95 at_eof: bool,
96 nchars: usize,
97 colno: usize,
98 lineno: usize,
99 /// Source start `(lineno, colno)` of the most recently *begun* token,
100 /// captured in `read_token` after inter-token skips and before the token's
101 /// first char is consumed. Foundation for §1 accurate construct-start ranges
102 /// (docs/performance/SOURCE_PROVENANCE.md). Semantically inert until consumed by a ranged
103 /// locator; written unconditionally — two writes, below the hot-path noise
104 /// floor and cheaper than a per-read flag check.
105 last_token_start: (usize, usize),
106 foodtype: FoodType,
107 /// Read [`BIB_DATA_LITERALS`] (`% & # @`) as ordinary characters — not comment, alignment tab,
108 /// parameter, active — for this mouth only. Set by `with_bib_data_literals()`; see
109 /// that method for the BibTeX rationale, and for why `_` is NOT here.
110 /// Deliberately a per-Mouth field rather than a State catcode assignment: a
111 /// nested mouth (a `.sty` raw-load triggered from inside the text) is a
112 /// separate object and keeps TeX's meanings, which a State-level assignment
113 /// could not guarantee.
114 bib_data_literals: bool,
115 /// See [`MouthOptions::lazy_decode`].
116 lazy_decode: bool,
117 /// See [`MouthOptions::file_level`].
118 file_level: bool,
119 saved_at_cc: Option<Catcode>,
120 saved_include_comments: Option<bool>,
121 note_message: Option<String>,
122 source: String,
123 /// `source` pre-interned at construction, so per-token / per-conditional
124 /// locator building ([`Object::get_locator`], [`Mouth::get_locator_from_start`])
125 /// is pure field copies instead of an interner probe over the path string.
126 /// `source` is never mutated after construction, so the two cannot drift.
127 source_sym: SymStr,
128 shortsource: String,
129 skipping_spaces: bool,
130 // pub handle : Option<File>,
131 chars: VecDeque<char>,
132 buffer: VecDeque<String>,
133 /// The lines of `raw_bytes` not yet decoded, as ranges into it: a file is held once, not as a `Vec` per line.
134 raw_buffer: VecDeque<Range<usize>>,
135 raw_bytes: Rc<[u8]>,
136 /// The name of the control sequence being read ([`Self::handle_escape`]), spelled in a buffer reused across tokens.
137 cs_name: String,
138 reader: Option<BufReader<File>>,
139 /// This mouth reads input BYTES (a file, or a document handed over as content),
140 /// not an engine string: see [`eight_bit_input_char`].
141 reads_input_bytes: bool,
142 /// The line in `buffer` was decoded as the Latin-1 image of its bytes (it is
143 /// not UTF-8, or the input encoding is a byte encoding) — see `line_is_bytes`.
144 buffered_line_is_bytes: bool,
145 /// The current line's characters in U+0080..U+00FF ARE its input bytes, not
146 /// UTF-8-decoded characters: only those reach [`eight_bit_input_char`].
147 line_is_bytes: bool,
148 /// Positions in `chars` of the current line where a `^^xx` / `^^X` code was
149 /// reduced to its byte (tex.web §355) — bytes even on a UTF-8 line, and still
150 /// bytes when the reduced character is read again after a peek.
151 caret_bytes: Vec<usize>,
152}
153
154impl PartialEq for Mouth {
155 fn eq(&self, other: &Mouth) -> bool { self.source == other.source }
156}
157
158impl Mouth {
159 /// A copy of this mouth, to read on while this one stays where it is (`state::input_stream_to_change`): a file it reads from
160 /// disk is opened again at the same offset; one that cannot be ends where the lines it holds end, enough for a run about to
161 /// be undone.
162 pub fn copy_for_a_rollback(&mut self) -> Mouth {
163 use std::io::{Seek, SeekFrom};
164 let source = self.source.clone();
165 let reader = self.reader.as_mut().and_then(|reader| {
166 let at = reader.stream_position().ok()?;
167 // (the name `open_file` judged, judged again as it is opened again)
168 let mut file = pathname::read_allowed(&source)
169 .then(|| File::open(&source).ok())
170 .flatten()?;
171 file.seek(SeekFrom::Start(at)).ok()?;
172 Some(BufReader::new(file))
173 });
174 Mouth {
175 fordefinitions: self.fordefinitions,
176 at_letter: self.at_letter,
177 notes: self.notes,
178 at_eof: self.at_eof,
179 nchars: self.nchars,
180 colno: self.colno,
181 lineno: self.lineno,
182 last_token_start: self.last_token_start,
183 foodtype: self.foodtype,
184 bib_data_literals: self.bib_data_literals,
185 lazy_decode: self.lazy_decode,
186 file_level: self.file_level,
187 saved_at_cc: self.saved_at_cc,
188 saved_include_comments: self.saved_include_comments,
189 note_message: self.note_message.clone(),
190 source,
191 source_sym: self.source_sym,
192 shortsource: self.shortsource.clone(),
193 skipping_spaces: self.skipping_spaces,
194 chars: self.chars.clone(),
195 buffer: self.buffer.clone(),
196 raw_buffer: self.raw_buffer.clone(),
197 raw_bytes: Rc::clone(&self.raw_bytes),
198 cs_name: String::new(),
199 reader,
200 reads_input_bytes: self.reads_input_bytes,
201 buffered_line_is_bytes: self.buffered_line_is_bytes,
202 line_is_bytes: self.line_is_bytes,
203 caret_bytes: self.caret_bytes.clone(),
204 }
205 }
206}
207
208impl Default for Mouth {
209 fn default() -> Self {
210 // Historically the source was `"Anonymous String {gid}"` with a
211 // per-instance gid, which Locator::source then pinned into the arena.
212 // The gid served no functional purpose and made every anonymous mouth
213 // unique at the SymStr layer — fine for a handful of mouths, but
214 // catastrophic when a runaway error-recovery path creates millions
215 // (arxiv 1210.4211 under parallel load: 50M anonymous mouths saturated
216 // the u32 interner offset). Collapsing onto a shared static label makes
217 // the per-mouth cost arena-free, and the pin-count sentinel remains as
218 // a symptom detector for the *actual* bug (something is still creating
219 // 50M anonymous mouths — that's a runaway loop to track down, now with
220 // the arena side-effect removed).
221 Mouth {
222 notes: false,
223 note_message: None,
224 fordefinitions: false,
225 at_letter: false,
226 at_eof: false,
227 skipping_spaces: false,
228 lineno: 0,
229 colno: 0,
230 last_token_start: (0, 0),
231 chars: VecDeque::new(),
232 nchars: 0,
233 source: String::from("Anonymous String"),
234 source_sym: crate::pin!("Anonymous String"),
235 shortsource: s!("String"),
236 // handle : None,
237 foodtype: FoodType::File,
238 bib_data_literals: false,
239 lazy_decode: false,
240 file_level: false,
241 saved_at_cc: None,
242 saved_include_comments: None,
243 buffer: VecDeque::new(),
244 raw_buffer: VecDeque::new(),
245 raw_bytes: Rc::from([]),
246 cs_name: String::new(),
247 reader: None,
248 reads_input_bytes: false,
249 buffered_line_is_bytes: false,
250 line_is_bytes: false,
251 caret_bytes: Vec::new(),
252 }
253 }
254}
255
256impl fmt::Display for Mouth {
257 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Mouth[{}]", self.source) }
258}
259impl Object for Mouth {
260 fn stringify(&self) -> String { s!("Mouth[<string>{}x{}]", self.lineno, self.colno) }
261 fn get_locator(&self) -> Option<Locator> {
262 let (to_line, to_column) = (self.lineno, self.colno);
263 let max_col = if self.nchars > 0 {
264 self.nchars - 1
265 } else {
266 self.nchars
267 }; // There is always a trailing EOL char, if any
268 let (from_line, from_column) = if to_column > 0 && to_column >= max_col {
269 (to_line, 0)
270 } else {
271 (to_line, to_column)
272 };
273 // Perl Mouth.pm L199 (#2671): columns in Locator are 1-indexed; the Mouth's
274 // internal colno counter is 0-indexed (character array index), so we add 1
275 // when producing the Locator for error-message display.
276 // A Mouth always has a position, so this is always `Some`.
277 Some(Locator::from_sym(
278 self.source_sym,
279 from_line as u32,
280 (from_column + 1) as u32,
281 to_line as u32,
282 (to_column + 1) as u32,
283 ))
284 }
285}
286
287/// Decode raw input bytes as text when no encoding has been declared:
288/// valid UTF-8 is taken as-is, anything else is a Latin-1 passthrough
289/// (byte → char).
290///
291/// Mirrors Perl `Mouth.pm` L75-80: when `PERL_INPUT_ENCODING` is undef Perl
292/// never decodes, so the bytes pass through untouched and the read cannot
293/// fail. The point is that a non-UTF-8 file is **never lost** — only decoded
294/// conservatively. `std::fs::read_to_string` gives the opposite behaviour
295/// (hard error on the first stray byte), which silently cost witness
296/// 2605.00490 its entire bibliography: a JabRef-written `.bib` self-declaring
297/// `% Encoding: Cp1252`. Real `bibtex` 0.99d is 8-bit clean and reads it fine.
298///
299/// Latin-1 (rather than `from_utf8_lossy`) is the better fallback here
300/// because it is lossless byte → char: legacy `.bib` files are overwhelmingly
301/// Latin-1/Cp1252, whose accented names survive intact instead of collapsing
302/// to U+FFFD.
303///
304/// The fallback is applied **per line**, not per buffer. `raw` is a single
305/// line when the Mouth calls this, but a whole file when a `.bib` reader does,
306/// and decoding a whole file as Latin-1 because of one stray byte would
307/// mojibake every correctly-UTF-8-encoded name in it (`é` → `é`). Per-line
308/// keeps the damage to the offending line and matches the Mouth's own
309/// granularity. The all-valid-UTF-8 case (the overwhelming majority) still
310/// costs exactly one `from_utf8` SIMD validation of the whole buffer.
311/// KERNEL_CAPABILITIES K10: under the pdfTeX byte mouth a non-ASCII string
312/// has two spellings — the bytes (a run of chars in U+0080..U+00FF, from
313/// `\string`/`\detokenize`/`\csname` of the active bytes, or a stringified
314/// token list) and the character the octet readers emit. pdfTeX knows only
315/// the bytes, so the two never meet there; here they meet at every string
316/// boundary (a color name defined from a detokenized list and used from the
317/// text — cncolours.sty:21 vs pgfornament-han-doc; hyperref's `pdftitle`;
318/// a theorem tag). Decode every maximal byte run that is valid UTF-8 back
319/// into its characters; anything else stays as it is. A no-op unless the
320/// byte mouth is on.
321pub fn decode_byte_mouth_runs(s: &str) -> std::borrow::Cow<'_, str> {
322 if !s.chars().any(is_byte_spelling) || !lookup_bool_sym(crate::pin!("PDFTEX_BYTE_MOUTH")) {
323 return std::borrow::Cow::Borrowed(s);
324 }
325 let mut out = String::with_capacity(s.len());
326 let mut run: Vec<u8> = Vec::new();
327 for c in s.chars() {
328 if is_byte_spelling(c) {
329 run.push(c as u32 as u8);
330 } else {
331 decode_byte_run(&mut run, &mut out);
332 out.push(c);
333 }
334 }
335 decode_byte_run(&mut run, &mut out);
336 std::borrow::Cow::Owned(out)
337}
338
339/// The value holding utf8.def's undeclared-character error installed for `ch` (utf8_def.rs), which only that
340/// definition matches.
341pub fn utf8_undeclared_error_key(ch: char) -> String { s!("utf8_def:undeclared:{:X}", ch as u32) }
342
343/// The value marking a C1 character (U+0080-U+009F) whose catcode TeX code assigned under `[utf8]` (`\catcode`'s
344/// setter, tex_character.rs), so a byte of a byte-decoded line stays that active character (OD #481's addendum).
345pub fn utf8_c1_catcode_key(ch: char) -> String { s!("lx@utf8@c1@catcode:{:X}", ch as u32) }
346
347/// Whether the document owns the active C1 character `ch` under `[utf8]`: it assigned its catcode, or gave it a
348/// meaning other than utf8.def's (a `\lowercase{\def~}` names it with no `\catcode`).
349fn utf8_c1_byte_is_owned(ch: char) -> bool {
350 lookup_bool(&utf8_c1_catcode_key(ch))
351 || lookup_value(&utf8_undeclared_error_key(ch))
352 .is_some_and(|installed| lookup_meaning(&T_ACTIVE!(ch)) != Some(installed))
353}
354
355/// A char that spells a byte under the byte mouth: the Latin-1 image of
356/// 0x80..0xFF (`decode_bytes` "bytes" branch).
357fn is_byte_spelling(c: char) -> bool { ('\u{80}'..='\u{FF}').contains(&c) }
358
359/// Decode one maximal byte run SEQUENCE by sequence: every valid UTF-8
360/// sequence becomes its character, an invalid byte stays its Latin-1 image,
361/// and a trailing INCOMPLETE sequence stays as bytes — it is still being
362/// assembled when the run is a text node the bytes reach one token at a time
363/// (`byte_mouth_pending_tail`). An all-or-nothing `from_utf8` of the run
364/// mis-read a decoded Latin-1 character (é = U+00E9, a 3-byte lead's image)
365/// next to a fresh CJK sequence as one invalid run and left both undecoded.
366fn decode_byte_run(run: &mut Vec<u8>, out: &mut String) {
367 let mut rest: &[u8] = run;
368 while !rest.is_empty() {
369 match str::from_utf8(rest) {
370 Ok(text) => {
371 out.push_str(text);
372 break;
373 },
374 Err(e) => {
375 let (valid, bad) = rest.split_at(e.valid_up_to());
376 out.push_str(str::from_utf8(valid).unwrap_or_default());
377 let n = e.error_len().unwrap_or(bad.len());
378 out.extend(bad[..n].iter().map(|&b| b as char));
379 rest = &bad[n..];
380 },
381 }
382 }
383 run.clear();
384}
385
386/// Byte offset in `s` where a trailing INCOMPLETE UTF-8 sequence in the byte
387/// spelling begins (`s.len()` when there is none). The text-run merge in
388/// `Document::open_text_internal` re-decodes only from there: the bytes of
389/// one character arrive one token at a time (tex.web §1034: one char node per
390/// byte), so a run is complete only once its last continuation byte is on,
391/// and everything before the pending lead byte is already decoded (or
392/// invalid and final). Invariant relied on: a decoded character in
393/// U+00C2..U+00F4 (é, Ã) is never followed by raw continuation bytes without
394/// their own lead — well-formed input never produces that shape, so the one
395/// preceding character this looks back at is only ever re-merged when it IS
396/// the pending lead byte.
397pub fn byte_mouth_pending_tail(s: &str) -> usize {
398 let mut continuations = 0usize;
399 for (i, c) in s.char_indices().rev() {
400 let u = c as u32;
401 if (0x80..=0xBF).contains(&u) {
402 continuations += 1;
403 if continuations > 3 {
404 return s.len();
405 }
406 continue;
407 }
408 let needed = match u {
409 0xC2..=0xDF => 1,
410 0xE0..=0xEF => 2,
411 0xF0..=0xF4 => 3,
412 _ => return s.len(),
413 };
414 return if continuations < needed { i } else { s.len() };
415 }
416 s.len()
417}
418
419pub fn decode_input_bytes(raw: &[u8]) -> String {
420 match str::from_utf8(raw) {
421 Ok(s) => s.to_string(),
422 Err(_) => {
423 let mut out = String::with_capacity(raw.len());
424 for (i, line) in raw.split(|&b| b == b'\n').enumerate() {
425 if i > 0 {
426 out.push('\n');
427 }
428 match str::from_utf8(line) {
429 Ok(s) => out.push_str(s),
430 Err(_) => out.extend(line.iter().map(|&b| b as char)),
431 }
432 }
433 out
434 },
435 }
436}
437
438/// The character an 8-bit input byte stands for, when it reaches the tokenizer as a
439/// plain letter or other character instead of through its active inputenc
440/// definition.
441///
442/// inputenc makes every upper byte active (`\DeclareInputText{199}{\CYRZ}`,
443/// cp1251.def:54), and the active definition yields the character. A package that
444/// hands the bytes back to the letter class (russ.sty:58-63 `\catcode…=11`, so
445/// Cyrillic words can form control-sequence names) bypasses that definition: in TeX
446/// the byte then goes straight to the font as a slot, and T2A's letter block is laid
447/// out like cp1251, so the glyph is still the letter the author typed. LaTeXML is
448/// Unicode-native — a byte is decoded where it enters, as utf8 input already is — so
449/// the byte becomes the character its own inputenc declaration produces: the active
450/// definition followed through single-token macros (`\IeC{…}` unwrapped) to one
451/// character (`\CYRZ` → `З`, fontenc_sty.rs). Only for a genuine input byte — a
452/// character of a file line that is not UTF-8 (decoded as its bytes), or a `^^xx`
453/// code — under a declared 8-bit input encoding, outside the pdfTeX byte mouth (K10);
454/// a valid UTF-8 line keeps its characters (é stays é in an `\input` UTF-8 file). The
455/// catcode stays the byte's. Everything downstream is then Unicode, so the font map
456/// never has to guess whether a code in 128–255 is a slot or a character.
457/// `None` keeps the byte (no declaration, or one that is not a single character).
458/// OXIDIZED_DESIGN #266.
459fn eight_bit_input_char(byte: char) -> Option<char> {
460 use crate::definition::Definition;
461 if lookup_bool_sym(crate::pin!("PDFTEX_BYTE_MOUTH")) {
462 return None;
463 }
464 let encoding = lookup_string_from_sym(crate::pin!("INPUT_ENCODING"));
465 if encoding.is_empty() || encoding == "utf8" {
466 return None;
467 }
468 let mut meaning = lookup_meaning(&T_ACTIVE!(byte))?;
469 for _ in 0..6 {
470 let Stored::Expandable(ref defn) = meaning else {
471 return None;
472 };
473 let Some(crate::definition::ExpansionBody::Tokens(body)) = defn.get_expansion() else {
474 return None;
475 };
476 let toks: Vec<Token> = body
477 .unlist_ref()
478 .iter()
479 .copied()
480 .filter(|t| {
481 !matches!(t.get_catcode(), Catcode::BEGIN | Catcode::END) && !t.with_str(|s| s == "\\IeC")
482 })
483 .collect();
484 let [t] = toks.as_slice() else {
485 return None;
486 };
487 match t.get_catcode() {
488 Catcode::LETTER | Catcode::OTHER => {
489 let mut it = t.with_str(|s| s.chars().collect::<Vec<char>>()).into_iter();
490 return match (it.next(), it.next()) {
491 (Some(c), None) if c != byte => Some(c),
492 _ => None,
493 };
494 },
495 Catcode::CS => {
496 // A LaTeX text command (`\CYRZ` = the `\cf@encoding` dispatch,
497 // latex.ltx `\DeclareTextSymbol`): its glyph is `\<encoding>\CYRZ` for
498 // the font encoding current when the byte is READ (TeX resolves it when
499 // the letter is typeset), a one-character primitive decoded from that
500 // encoding's font map (sect08.rs) — T2A slot 199 → `З`.
501 if let Some(c) = text_symbol_char(t) {
502 return Some(c);
503 }
504 meaning = lookup_meaning(t)?;
505 },
506 Catcode::ACTIVE => meaning = lookup_meaning(t)?,
507 _ => return None,
508 }
509 }
510 None
511}
512
513/// The single character `\<current encoding><cs>` typesets, if it is a
514/// `\DeclareTextSymbol` glyph (a primitive with a one-character string body).
515pub fn text_symbol_char(cs: &Token) -> Option<char> {
516 use crate::definition::PrimitiveBody;
517 // `\cf@encoding` is the current font's encoding (a computed macro here).
518 let encoding = lookup_font()?.get_encoding()?.to_string();
519 let glyph_cs = T_CS!(format!("\\{}{}", encoding.trim(), cs.to_string()));
520 let Some(Stored::Primitive(prim)) = lookup_meaning(&glyph_cs) else {
521 return None;
522 };
523 let Some(PrimitiveBody::String(sym)) = prim.replacement else {
524 return None;
525 };
526 let mut it = crate::common::arena::with(sym, |s| s.chars().collect::<Vec<char>>()).into_iter();
527 match (it.next(), it.next()) {
528 (Some(c), None) => Some(c),
529 _ => None,
530 }
531}
532
533impl Mouth {
534 // Factory method;
535 // Create an appropriate Mouth
536 // options are
537 // quiet,
538 // atletter,
539 // content
540 //
541 // DG: For now we are using a `foodtype` field instead of subclassing mouth, as it feels more
542 // compact in this particular application we're really looking at a unified Mouth
543 // application logic, with a capacity of reading different kinds of sources
544 pub fn create(source: &str, mut options: MouthOptions) -> Result<Self> {
545 if let Some(content) = options.content.take() {
546 // we've cached the content of this source
547 let (_dir, name, ext) = pathname::split(source);
548 options.source = Some(source.to_string());
549 options.shortsource = Some(s!("{}.{}", name, ext));
550 options.lazy_decode = true;
551 options.file_level = true;
552 // Read-log: a named cached-content open (filecontents / LSP overlay).
553 record_opened_source(crate::common::arena::pin(source));
554 Mouth::new(&content, Some(options))
555 } else if source.starts_with("literal:") {
556 let source = source.replacen("literal:", "", 1);
557 // we've supplied literal data
558 options.source = None; // the source does not have a corresponding file name
559 options.foodtype = FoodType::opt_from_str("literal");
560 Mouth::new(&source, Some(options))
561 } else if source.is_empty() {
562 Mouth::new("", Some(options))
563 } else {
564 let (_dir, name, ext) = pathname::split(source);
565 options.foodtype = FoodType::opt_from_str(&pathname::protocol(source));
566 options.file_level = true;
567 options.source = Some(source.to_string());
568 if options.shortsource.is_none() {
569 options.shortsource = Some(if ext.is_empty() {
570 name
571 } else {
572 s!("{}.{}", name, ext)
573 });
574 }
575 // Read-log: a named file open (recorded even when the open then
576 // fails — a pinned-but-missing path that later APPEARS must read
577 // as a dependency change).
578 record_opened_source(crate::common::arena::pin(source));
579 Mouth::new(source, Some(options))
580 }
581 }
582
583 /// What kind of source feeds this mouth (file vs literal/string injection).
584 pub fn foodtype(&self) -> FoodType { self.foodtype }
585
586 /// Whether this mouth reads a file (see [`MouthOptions::file_level`]).
587 pub fn is_file_level(&self) -> bool { self.file_level }
588
589 /// Whether this mouth reads the document's own text: a content file (`binding::content::load_tex_content`, the
590 /// converter's in-memory source), its notes on and not read for definitions — no package's, class's or binding's.
591 pub fn is_document_text(&self) -> bool { self.notes && !self.fordefinitions }
592
593 pub fn new(text: &str, options: Option<MouthOptions>) -> Result<Self> {
594 let mut mouth = match options {
595 None => Mouth {
596 foodtype: FoodType::Literal,
597 ..Mouth::default()
598 },
599 Some(opts) => {
600 let shortsource = opts.shortsource.unwrap_or_else(|| s!("String"));
601 let source = opts.source.unwrap_or_default();
602 Mouth {
603 foodtype: opts.foodtype.unwrap_or(FoodType::Literal),
604 fordefinitions: opts.fordefinitions,
605 at_letter: opts.at_letter,
606 notes: opts.notes,
607 lazy_decode: opts.lazy_decode,
608 file_level: opts.file_level,
609 source_sym: crate::common::arena::pin(&source),
610 source,
611 shortsource,
612 ..Mouth::default()
613 }
614 },
615 };
616 mouth.open(text)?;
617 Ok(mouth)
618 }
619
620 /// Read `% & #` as ordinary characters (catcode 12) instead of comment,
621 /// alignment tab and parameter, for the whole life of this mouth.
622 ///
623 /// **Treatment 1 of two** (see `OXIDIZED_DESIGN #74`): this is "be `bibtex`".
624 /// BibTeX's lexer interprets only braces and the entry/field delimiters — it
625 /// has no comment syntax inside an entry (`%` is significant only in the junk
626 /// BETWEEN entries, `Pre::BibTeX::skipJunk`), no alignment and no parameters.
627 /// So a field value it hands back is a string in which all three are ordinary
628 /// characters: a percent-encoded URL, a publisher's name ("Taylor &
629 /// Francis"), an issue number.
630 ///
631 /// Re-injected as TeX source (BibTeX.pool's `\bibentry@create`) under the
632 /// default catcodes, each misfires: `%` (14) comments out the rest of its
633 /// line — the field's own closing brace included — so the entry's group never
634 /// closes; `&` (4) is a stray alignment tab and is dropped; `#` (6) reaches
635 /// the Stomach as a parameter token. Reading the injected text with all three
636 /// neutralized preserves the value BibTeX actually parsed, **without altering
637 /// a byte of it**.
638 ///
639 /// **`_` is deliberately NOT in this set**, and the reason is the boundary
640 /// between the two treatments. A catcode is decided at tokenization, before
641 /// anything knows whether it is inside `$…$` — and a subscript in a `.bib`
642 /// title's math (`title = {Bounds on $x_1+x_2$}`) is *legitimate TeX* that
643 /// must keep working. `_` therefore belongs to treatment 2
644 /// (`bibtex.rs::escape_bib_data_specials`), which walks the value and skips
645 /// math spans. Measured: putting `_` here silently flattened every
646 /// subscript in a bibliography title. The other three have no legitimate
647 /// meaning inside a `.bib` field, in math or out.
648 ///
649 /// A `\catcode` in the injected text cannot do this job either: the catcode
650 /// would still be a State assignment, so a raw `.sty` opened from inside a
651 /// field handler would inherit it — and so would the document. Scoping to the
652 /// Mouth keeps the rule attached to the *text that BibTeX lexed*, which is
653 /// exactly where it belongs.
654 ///
655 /// Only the TeX-special meaning is removed: a character that has been given
656 /// some other catcode (LETTER, say) keeps it. And `\%`, `\&`, `\#` still
657 /// work, because the backslash is untouched.
658 pub fn with_bib_data_literals(mut self) -> Self {
659 self.bib_data_literals = true;
660 self
661 }
662
663 pub fn get_source(&self) -> &str { &self.source }
664
665 pub fn open(&mut self, content: &str) -> Result<()> {
666 match self.foodtype {
667 FoodType::File => self.open_file(content)?,
668 FoodType::Literal => self.open_literal(content),
669 FoodType::HTTP => self.open_http(content),
670 FoodType::HTTPS => self.open_https(content),
671 };
672 self.initialize();
673 Ok(())
674 }
675
676 fn open_file(&mut self, pathname: &str) -> Result<()> {
677 if self.foodtype == FoodType::File {
678 // Every TeX text a confined conversion reads opens here, whoever built the name (a package's internal command,
679 // a macro body): judged as opened, refused an Error and read as empty
680 // (OXIDIZED_DESIGN_DIVERGENCES #1183).
681 if !pathname::read_allowed(pathname) {
682 if pathname::refused_exists(pathname) {
683 pathname::refuse(pathname);
684 } else {
685 Error!(
686 "I/O",
687 pathname,
688 s!("Can't find file {}", pathname),
689 "Reading it as empty"
690 );
691 }
692 return Ok(());
693 }
694 // Perl: check readable, then check binary (non-empty), then open
695 let metadata = std::fs::metadata(pathname);
696 match &metadata {
697 Err(e) if e.kind() == io::ErrorKind::NotFound => {
698 // Perl Mouth/file.pm:32-41 `openFile`: an unreadable/unopenable file
699 // is a recoverable `Error('I/O', …)` and the mouth stays empty —
700 // callers pre-check with FindFile, so this is a race or a stale
701 // path, not a reason to abort the document. (It was a `fatal!`
702 // here, which since 56fc logs at the raise: a probing `\openin`
703 // then surfaced `Fatal:Mouth:MissingFile` — s108, four docs.)
704 Error!(
705 "I/O",
706 pathname,
707 s!("Can't find file {}", pathname),
708 "Reading it as empty"
709 );
710 return Ok(());
711 },
712 Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
713 Error!(
714 "I/O",
715 "unreadable",
716 s!("File {} is not readable. Ignoring.", pathname),
717 "",
718 "",
719 self.get_location()
720 );
721 return Ok(());
722 },
723 Err(e) => {
724 return Err(io::Error::new(e.kind(), e.to_string()).into());
725 },
726 Ok(meta) => {
727 // Every opened source file raises the runaway-token backstop in
728 // proportion (see `gullet::scale_token_limit_to_source`).
729 crate::gullet::scale_token_limit_to_source(meta.len() as usize);
730 // Check for binary file (non-empty and appears binary)
731 // Perl's -B heuristic: check first block for high proportion of non-text bytes
732 if meta.len() > 0
733 && let Ok(mut f) = File::open(pathname)
734 {
735 let mut buf = [0u8; 512];
736 if let Ok(n) = f.read(&mut buf)
737 && n > 0
738 {
739 let non_text = buf[..n]
740 .iter()
741 .filter(|&&b| {
742 b == 0 || (b < 0x20 && b != b'\n' && b != b'\r' && b != b'\t' && b != 0x1b)
743 })
744 .count();
745 if non_text * 3 > n {
746 // High ratio of non-text bytes — likely binary
747 Error!(
748 "invalid",
749 "binary",
750 s!("Input file {} appears to be binary. Ignoring.", pathname),
751 "",
752 "",
753 self.get_location()
754 );
755 return Ok(());
756 }
757 }
758 }
759 },
760 }
761 let f = match File::open(pathname) {
762 Ok(f) => f,
763 Err(e) => {
764 Error!(
765 "I/O",
766 "open",
767 s!("Can't open {} for reading: {}", pathname, e),
768 "",
769 "",
770 self.get_location()
771 );
772 return Err(e.into());
773 },
774 };
775 let reader = BufReader::new(f);
776 self.reader = Some(reader);
777 self.reads_input_bytes = true;
778 self.buffer = VecDeque::new();
779 self.raw_buffer = VecDeque::new();
780 self.raw_bytes = Rc::from([]);
781 }
782 Ok(())
783 }
784 fn open_literal(&mut self, content: &str) {
785 if self.lazy_decode {
786 // A document handed over as content: bytes, decoded per line on read
787 // (`get_next_line`), like a file.
788 self.raw_buffer = Mouth::split_raw_lines(content.as_bytes());
789 self.raw_bytes = Rc::from(content.as_bytes());
790 self.reads_input_bytes = true;
791 } else {
792 self.buffer = Mouth::split_lines(content);
793 }
794 }
795 fn open_http(&mut self, url: &str) {
796 emit_warn(
797 "unsupported",
798 "http_input",
799 &format!("HTTP input not supported: {url}"),
800 );
801 }
802 fn open_https(&mut self, url: &str) {
803 emit_warn(
804 "unsupported",
805 "http_input",
806 &format!("HTTPS input not supported: {url}"),
807 );
808 }
809 // fn open_binding(&mut self, _content: &str) {}
810
811 fn initialize(&mut self) {
812 // `@`'s catcode as the read starts: the note's ` w/@ other`, and the at_letter save below.
813 let at_cc = lookup_catcode('@');
814 self.note_message = if self.notes {
815 let source = if !self.source.is_empty() {
816 &self.source
817 } else {
818 "Anonymous String"
819 };
820 let kind = if self.fordefinitions {
821 "definitions"
822 } else {
823 "content"
824 };
825 // Perl Mouth.pm:94-96 says `w/@ other` for a reader that does not force `@`; a package's `\input` keeps the
826 // catcodes (content.rs), so it also needs `@` not a letter as the read starts (other, or an escape; #1024).
827 let at_note =
828 if self.fordefinitions && !self.at_letter && !matches!(at_cc, Some(Catcode::LETTER)) {
829 " w/@ other"
830 } else {
831 ""
832 };
833 Some(s!("Processing {}{} {}", kind, at_note, source))
834 } else {
835 None
836 };
837 // Perl Mouth.pm L97: ProgressSpinup($$self{note_message}) — emit
838 // `(Processing definitions <source>...` when this mouth begins reading.
839 // The matching ProgressSpindown (Mouth.pm L121) is in `finish()` below.
840 if let Some(ref msg) = self.note_message {
841 note_begin(msg);
842 }
843 // Perl Mouth.pm:98-100: at_letter saves/restores `@`'s catcode with a
844 // LOCAL assignment (no scope argument), independently of fordefinitions.
845 // It was global here (2121a02d09, "persist across scope frame pops"),
846 // which erased the enclosing group's undo entry for `@`: a package that
847 // `\input`s a file inside `\bgroup\catcode`\@0 … \egroup` (CoverPage.sty:
848 // 60-70 reading a BibTeX-keyword file) then kept `@` as an escape after
849 // the group, and every later `\CP@…`/`\define@key` split (coverpage
850 // SimpleSample, ~20 errors; RUST-ONLY, Perl 0).
851 // Guard: `perfect_kernel_batch56::at_letter_mouth_keeps_group_catcode_undo`.
852 if self.at_letter {
853 self.saved_at_cc = at_cc;
854 assign_catcode('@', Catcode::LETTER, None);
855 }
856 // Perl: fordefinitions saves/restores INCLUDE_COMMENTS
857 if self.fordefinitions {
858 self.saved_include_comments = match lookup_value("INCLUDE_COMMENTS") {
859 Some(Stored::Bool(x)) => Some(x),
860 _ => None,
861 };
862 assign_value("INCLUDE_COMMENTS", false, Some(Scope::Local));
863 }
864 }
865 /// Stop reading from this mouth: clear buffers and close file handle.
866 /// Called by flush_mouth (\endinput) to prevent further reading.
867 /// Does NOT restore catcodes — that's done by finish().
868 pub fn stop_reading(&mut self) {
869 self.buffer = VecDeque::new();
870 self.raw_buffer = VecDeque::new();
871 self.raw_bytes = Rc::from([]);
872 self.chars = VecDeque::new();
873 self.line_is_bytes = false;
874 self.caret_bytes.clear();
875 self.lineno = 0;
876 self.colno = 0;
877 self.nchars = 0;
878 self.reader.take(); // close file handle
879 }
880
881 /// Fully finish this mouth: stop reading AND restore catcodes/state.
882 /// Called by close_mouth when the mouth is popped from the stack.
883 pub fn finish(&mut self) {
884 self.stop_reading();
885 // Perl Mouth.pm:117: at_letter restores `@`'s catcode locally (see
886 // `initialize`).
887 if self.at_letter {
888 let cc = self.saved_at_cc.take().unwrap_or(Catcode::OTHER);
889 assign_catcode('@', cc, None);
890 }
891 // Perl: fordefinitions restores INCLUDE_COMMENTS
892 if let Some(sic) = self.saved_include_comments.take() {
893 assign_value("INCLUDE_COMMENTS", sic, Some(Scope::Local))
894 }
895 if self.notes
896 && let Some(ref msg) = self.note_message
897 {
898 note_end(msg);
899 }
900 }
901 // Auxiliaries
902
903 /// This is (hopefully) a platform independent way of splitting a string
904 /// into "lines" ending with CRLF, CR or LF (DOS, Mac or Unix).
905 /// Note that TeX considers newlines to be \r, ie CR, ie ^^M
906 fn split_lines(lines: &str) -> VecDeque<String> {
907 let mut lines: VecDeque<String> = LINEBREAK_REGEX.split(lines).map(str::to_owned).collect();
908 if let Some(last_line) = lines.back()
909 && last_line.is_empty()
910 {
911 lines.pop_back();
912 }
913 lines
914 }
915
916 /// Split raw bytes into lines without decoding, splitting on \r\n, \r, or \n: the lines' ranges in `bytes`.
917 fn split_raw_lines(bytes: &[u8]) -> VecDeque<Range<usize>> {
918 let mut lines = VecDeque::new();
919 let mut start = 0;
920 let mut i = 0;
921 while i < bytes.len() {
922 if bytes[i] == b'\r' {
923 lines.push_back(start..i);
924 if i + 1 < bytes.len() && bytes[i + 1] == b'\n' {
925 i += 1; // skip \n after \r
926 }
927 start = i + 1;
928 } else if bytes[i] == b'\n' {
929 lines.push_back(start..i);
930 start = i + 1;
931 }
932 i += 1;
933 }
934 // Add remaining bytes (last line without trailing newline)
935 if start < bytes.len() {
936 lines.push_back(start..bytes.len());
937 }
938 lines
939 }
940
941 /// Decode a raw byte line using the current encoding setting.
942 /// Matches Perl's per-line decode behavior. The flag says whether the line's
943 /// characters are the Latin-1 image of its bytes (a byte encoding, or a line
944 /// that is not UTF-8) rather than UTF-8-decoded characters.
945 fn decode_bytes(raw_line: &[u8], location: impl FnOnce() -> String) -> (String, bool) {
946 if let Some(ref encoding_sym) = get_input_encoding() {
947 // Probe the encoding without allocating — this fires per input
948 // line, so even a small heap alloc per call adds up on large
949 // documents. Only resolve the symbol to an owned String when we
950 // actually need it for the misdefined-encoding Info! message.
951 // `bytes` is the pdfTeX byte mouth (KERNEL_CAPABILITIES K10): pdfTeX
952 // reads a file byte by byte (tex.web §30-31 `buffer: array of
953 // ASCII_code`, §341 `cur_chr:=buffer[loc]`) against a 256-entry
954 // `\catcode` table, so a UTF-8 syllable is three char tokens whose codes
955 // are its bytes — the model cjkutf8-josa.sty:176 (`\DeclareRobustCommand*
956 // \^^ea[2]`, a control symbol over the lead byte) and dhucs.sty:44
957 // (`\ifx 가가`, two different bytes) are built on. Byte→char over
958 // U+0000..U+00FF is exactly the Latin-1 decode, and the catcode table's
959 // U+0000..U+00FF entries ARE that 256-entry table (`\catcode"EA` and a
960 // `^^ea` both address U+00EA). Enabled package-scoped by
961 // `inputenc_sty::enable_pdftex_byte_mouth`, never globally.
962 let is_latin1 = crate::common::arena::with(*encoding_sym, |s| {
963 s.eq_ignore_ascii_case("iso-8859-1")
964 || s.eq_ignore_ascii_case("latin1")
965 || s.eq_ignore_ascii_case("latin-1")
966 || s.eq_ignore_ascii_case("bytes")
967 });
968 let file_str = if is_latin1 {
969 raw_line.iter().map(|&b| b as char).collect::<String>()
970 } else {
971 // Fast path for valid UTF-8 (overwhelming majority of TeX
972 // source under `inputenc[utf8]`). `str::from_utf8` validates
973 // the whole slice in a tight SIMD loop and returns a
974 // borrow on success — no `Utf8Chunks::next` iteration
975 // looking for invalid bytes. Fall back to `from_utf8_lossy`
976 // only when validation fails.
977 match str::from_utf8(raw_line) {
978 Ok(s) => s.to_string(),
979 Err(_) => String::from_utf8_lossy(raw_line).into_owned(),
980 }
981 };
982 // Replace the U+FFFD inserted by lossy decode with space. For
983 // valid-UTF-8 inputs (no FFFD), skip the replace+log scan
984 // entirely. The original logic compared `replaced.len()` to
985 // `file_str.len()` to detect FFFD presence indirectly; the
986 // explicit `contains` is cheaper and lets us avoid the
987 // unconditional `replace` walk on every input line.
988 let has_fffd = file_str.contains('\u{FFFD}');
989 let file_str = if has_fffd {
990 let encoding_name = crate::common::arena::to_string(*encoding_sym);
991 Info!(
992 "misdefined",
993 &encoding_name,
994 s!("input isn't valid under encoding {}", &encoding_name),
995 "",
996 "",
997 location()
998 );
999 file_str.replace('\u{FFFD}', " ")
1000 } else {
1001 file_str
1002 };
1003 (file_str, is_latin1)
1004 } else {
1005 // No encoding set — interpret as UTF-8, falling back to a Latin-1
1006 // passthrough for non-UTF-8 bytes. This happens after inputenc
1007 // disables PERL_INPUT_ENCODING and the remaining file lines contain
1008 // high bytes. (`decode_input_bytes` for one line.)
1009 //
1010 // The decode stays the Latin-1 passthrough (OXIDIZED_DESIGN_DIVERGENCES
1011 // #481: the bytes are kept as text, where Perl blanks them), but the
1012 // report is Perl's: with no `inputenc` declaring a non-UTF-8 encoding,
1013 // the file is read as UTF-8 and an undecodable line raises
1014 // `Info:misdefined` "input isn't valid under encoding utf-8"
1015 // (Core/Mouth/file.pm:72-77). An Info, as in Perl; pdflatex's own
1016 // "Invalid UTF-8 byte" Error (utf8.def:113) is not raised here.
1017 match str::from_utf8(raw_line) {
1018 Ok(s) => (s.to_string(), false),
1019 Err(_) => {
1020 let declared = lookup_string("lx@inputenc@encoding");
1021 if declared.is_empty() || declared.starts_with("utf8") {
1022 let encoding_name = lookup_string("PERL_INPUT_ENCODING");
1023 let encoding_name = if encoding_name.is_empty() {
1024 s!("utf-8")
1025 } else {
1026 encoding_name
1027 };
1028 Info!(
1029 "misdefined",
1030 &encoding_name,
1031 s!("input isn't valid under encoding {}", &encoding_name),
1032 "",
1033 "",
1034 location()
1035 );
1036 }
1037 (raw_line.iter().map(|&b| b as char).collect(), true)
1038 },
1039 }
1040 }
1041 }
1042
1043 /// Original LaTeXML:
1044 /// This is (hopefully) a correct way to split a line into "chars",
1045 /// or what is probably more desired is "Grapheme clusters" (even "extended")
1046 /// These are unicode characters that include any following combining chars, accents & such.
1047 /// I am thinking that when we deal with unicode this may be the most correct way?
1048 /// If it's not the way XeTeX does it, perhaps, it must be that ALL combining chars
1049 /// have to be converted to the proper accent control sequences!
1050 fn get_next_line(&mut self) -> Option<String> {
1051 if self.buffer.is_empty() && !self.raw_buffer.is_empty() {
1052 // Decode the next raw byte line lazily using the current encoding.
1053 // This matches Perl's approach: each line is decoded with the encoding
1054 // that is active at the time the line is read, allowing inputenc to
1055 // change encoding mid-file.
1056 if let Some(raw_line) = self.raw_buffer.pop_front() {
1057 let (decoded, is_bytes) =
1058 Mouth::decode_bytes(&self.raw_bytes[raw_line], || self.get_location());
1059 self.buffered_line_is_bytes = is_bytes;
1060 self.buffer.push_back(decoded);
1061 }
1062 }
1063 if self.buffer.is_empty()
1064 && let Some(ref mut reader) = self.reader
1065 {
1066 // file mouth case — read all bytes, split into raw lines, decode lazily
1067 let mut file_bytes = Vec::new();
1068 let _num_bytes = match reader.read_to_end(&mut file_bytes) {
1069 Ok(count) => count,
1070 Err(e) => {
1071 let message = s!("BufReader::read_to_end returned an error: {:?}", e);
1072 Warn!("mouth", "io", message, "", "", self.get_location());
1073 0
1074 },
1075 };
1076 // remove the now exhausted reader
1077 self.reader.take();
1078 // Split raw bytes into lines without decoding (preserving raw bytes).
1079 // Each line is decoded lazily via decode_bytes() using the CURRENT encoding.
1080 self.raw_buffer = Mouth::split_raw_lines(&file_bytes);
1081 self.raw_bytes = Rc::from(file_bytes);
1082 // Decode the first line now
1083 if let Some(raw_line) = self.raw_buffer.pop_front() {
1084 let (decoded, is_bytes) =
1085 Mouth::decode_bytes(&self.raw_bytes[raw_line], || self.get_location());
1086 self.buffered_line_is_bytes = is_bytes;
1087 self.buffer.push_back(decoded);
1088 }
1089 }
1090 // A raw line is decoded into an empty `buffer` and popped here at once, so
1091 // the flag set by the decode belongs to this line.
1092 self.line_is_bytes = std::mem::take(&mut self.buffered_line_is_bytes);
1093 self.caret_bytes.clear();
1094 self.buffer.pop_front()
1095 }
1096
1097 /// Get the next character & it's catcode from the current line of input, even ignored chars,
1098 /// handling TeX's "^^" encoding.
1099 /// Note that this is the only place where catcode lookup is done (well almost),
1100 /// and that it is somewhat `inlined'.
1101 fn get_next_char(&mut self) -> Option<(char, Catcode)> {
1102 if self.colno >= self.nchars {
1103 return None;
1104 };
1105 let ch_opt = self.chars.get(self.colno);
1106 self.colno += 1;
1107 if let Some(ch) = ch_opt {
1108 let mut ch = *ch;
1109 let mut cc = self.catcode_of(ch);
1110 // Possible convert ^^x
1111 // Perl: (cc == CC_SUPER) && (colno + 1 < nchars) && (ch == chars[colno])
1112 if cc == Catcode::SUPER
1113 && self.colno + 1 < self.nchars
1114 && Some(&ch) == self.chars.get(self.colno)
1115 {
1116 // XeTeX/LuaTeX extended caret notation, longest-match-first:
1117 // ^^^^^^hhhhhh (6 hex) and ^^^^hhhh (4 hex) produce one Unicode
1118 // scalar. This engine is Unicode-native (same precedent as
1119 // providing \Ucharcat despite pdfTeX lacking it), and packages
1120 // PROBE for a Unicode engine with exactly this notation —
1121 // newunicodechar.sty L52-56 `\edef\next{\@gobble^^^^0021}` takes
1122 // its broken 8-bit branch without it (9-doc corpus cluster,
1123 // witnesses eigo, verifica, tikz-trackschematic, uspace).
1124 let is_lowerhex_c = |c: char| -> bool { matches!(c, '0'..='9' | 'a'..='f') };
1125 for (extra_carets, ndigits) in [(4usize, 6usize), (2, 4)] {
1126 // self.colno-1 is the first ^; require extra ^s then ndigits hex.
1127 let carets_ok =
1128 (0..extra_carets).all(|k| self.chars.get(self.colno + 1 + k) == Some(&ch));
1129 let dig_start = self.colno + 1 + extra_carets;
1130 if carets_ok
1131 && dig_start + ndigits <= self.nchars
1132 && (0..ndigits).all(|k| {
1133 self
1134 .chars
1135 .get(dig_start + k)
1136 .is_some_and(|c| is_lowerhex_c(*c))
1137 })
1138 {
1139 let hex: String = (0..ndigits)
1140 .filter_map(|k| self.chars.get(dig_start + k))
1141 .collect();
1142 if let Some(newch) = u32::from_str_radix(&hex, 16).ok().and_then(char::from_u32) {
1143 let removed = 2 + extra_carets + ndigits;
1144 self.splice(self.colno - 1..self.colno - 1 + removed, &[newch]);
1145 self.nchars -= removed - 1;
1146 let cc2 = self.catcode_of(newch);
1147 return Some((newch, cc2));
1148 }
1149 }
1150 }
1151 let c1_opt = self.chars.get(self.colno + 1);
1152 let c2_opt = self.chars.get(self.colno + 2);
1153 let mut two_hex = false;
1154 // ^^ followed by TWO LOWERCASE Hex digits???
1155 if let Some(c1) = c1_opt
1156 && let Some(c2) = c2_opt
1157 {
1158 // Perf: avoid per-char String alloc + regex match by using
1159 // direct ASCII class check. LOWERHEX_REGEX = ^[0-9a-f]$, i.e.
1160 // lowercase hex digits only.
1161 let is_lowerhex = |c: char| -> bool { matches!(c, '0'..='9' | 'a'..='f') };
1162 if (self.colno + 2 < self.nchars) && is_lowerhex(*c1) && is_lowerhex(*c2) {
1163 // TODO: Maybe Result type warranted here?
1164 let hex = u8::from_str_radix(&s!("{}{}", c1, c2), 16).unwrap();
1165 if let Some((decoded, removed)) = self.caret_utf8_sequence(ch, hex) {
1166 self.splice(self.colno - 1..self.colno - 1 + removed, &[decoded]);
1167 self.nchars -= removed - 1;
1168 return Some((decoded, self.catcode_of(decoded)));
1169 }
1170 ch = hex as char;
1171 self.splice(self.colno - 1..self.colno + 3, &[ch]);
1172 self.nchars -= 3;
1173 two_hex = true;
1174 }
1175 }
1176 if !two_hex {
1177 // OR ^^ followed by a SINGLE Control char type code???
1178 let c = self.chars[self.colno + 1];
1179 let cn = c as i16;
1180
1181 ch = (cn + if cn >= 64 { -64 } else { 64 }) as u8 as char;
1182 self.splice(self.colno - 1..self.colno + 2, &[ch]);
1183 self.nchars -= 2;
1184 }
1185 cc = self.catcode_of(ch);
1186 self.caret_bytes.push(self.colno - 1);
1187 }
1188 // Only an input byte: a character of a byte-decoded line, or a `^^xx` /
1189 // `^^X` code (tex.web §355 — a byte even on a UTF-8 line).
1190 if self.reads_input_bytes
1191 && ('\u{80}'..='\u{FF}').contains(&ch)
1192 && (self.line_is_bytes || self.caret_bytes.contains(&(self.colno - 1)))
1193 && matches!(cc, Catcode::LETTER | Catcode::OTHER)
1194 && let Some(decoded) = eight_bit_input_char(ch)
1195 {
1196 return Some((decoded, cc));
1197 }
1198 // A C1 byte of a byte-decoded line under [utf8] is an invalid UTF-8 byte, its Latin-1 character as text (OD #481),
1199 // not the code point U+0080-U+009F that utf8.def makes an error (utf8_def.rs); one the document owns stays
1200 // active, as utf8.def:174-190 leaves the byte (2205.07691's `\catcode`…=13 \def…{\'e}`).
1201 if ('\u{80}'..='\u{9F}').contains(&ch)
1202 && self.line_is_bytes
1203 && cc == Catcode::ACTIVE
1204 && !lookup_bool("PDFTEX_BYTE_MOUTH")
1205 && lookup_string("lx@inputenc@encoding").starts_with("utf8")
1206 && !utf8_c1_byte_is_owned(ch)
1207 {
1208 return Some((ch, Catcode::OTHER));
1209 }
1210 Some((ch, cc))
1211 } else {
1212 None
1213 }
1214 }
1215
1216 /// A UTF-8 character written as caret bytes (`^^e2^^80^^93`, bibtex's en dash), read at the first `^^`: its
1217 /// character and the length of the run. pdfTeX reads bytes and utf8.def's lead byte gathers its continuation bytes
1218 /// (utf8.def:93-108); this mouth reads characters, so under utf8 input the run is gathered here. Under an 8-bit
1219 /// `inputenc` encoding, or the pdfTeX byte mouth (whose utf8.def does it), every `^^xx` stays its byte; so does an
1220 /// incomplete or invalid sequence (not quite pdfTeX's reading: OXIDIZED_DESIGN_DIVERGENCES #1176's residuals). Perl
1221 /// reads one character per byte (Core/Mouth.pm:164-175). Witness: 2605.14761 (bibtex's caret en dash).
1222 fn caret_utf8_sequence(&self, caret: char, lead: u8) -> Option<(char, usize)> {
1223 let continuations = match lead {
1224 0xC2..=0xDF => 1,
1225 0xE0..=0xEF => 2,
1226 0xF0..=0xF4 => 3,
1227 _ => return None,
1228 };
1229 let start = self.colno - 1;
1230 let removed = 4 * (continuations + 1);
1231 if start + removed > self.nchars {
1232 return None;
1233 }
1234 let mut bytes = vec![lead];
1235 for k in 1..=continuations {
1236 let at = start + 4 * k;
1237 let [c0, c1, h1, h2] = [0, 1, 2, 3].map(|i| self.chars[at + i]);
1238 let is_lowerhex = |c: char| matches!(c, '0'..='9' | 'a'..='f');
1239 if c0 != caret || c1 != caret || !is_lowerhex(h1) || !is_lowerhex(h2) {
1240 return None;
1241 }
1242 bytes.push(u8::from_str_radix(&s!("{}{}", h1, h2), 16).ok()?);
1243 }
1244 // utf8.def's octet readers (the format's, latex.ltx:22224, or inputenc's) are what a byte means; not plain TeX's.
1245 if lookup_bool("PDFTEX_BYTE_MOUTH") || lookup_meaning(&T_CS!("\\UTFviii@two@octets")).is_none()
1246 {
1247 return None;
1248 }
1249 // `INPUT_ENCODING` is the `inputenc` encoding in force; utf8.def leaves it unset (None), as without inputenc.
1250 if let Some(Stored::String(encoding)) = lookup_value("INPUT_ENCODING")
1251 && !crate::common::arena::with(encoding, |e| e.starts_with("utf8"))
1252 {
1253 return None;
1254 }
1255 let mut chars = str::from_utf8(&bytes).ok()?.chars();
1256 Some((chars.next()?, removed))
1257 }
1258
1259 /// The catcode this mouth reads `ch` with: the State's, except that a
1260 /// [`Self::with_bib_data_literals`] mouth reads each of [`BIB_DATA_LITERALS`]
1261 /// as OTHER when — and only when — it carries a TeX meaning (any catcode but
1262 /// LETTER or OTHER).
1263 fn catcode_of(&self, ch: char) -> Catcode {
1264 let cc = lookup_catcode(ch).unwrap_or(Catcode::OTHER);
1265 if self.bib_data_literals
1266 && BIB_DATA_LITERALS.contains(&ch)
1267 && !matches!(cc, Catcode::LETTER | Catcode::OTHER)
1268 {
1269 Catcode::OTHER
1270 } else {
1271 cc
1272 }
1273 }
1274
1275 /// How far this mouth has read: its line, its column, the characters of the line still to read, and the lines still
1276 /// buffered. Only compared with an earlier reading of the same mouth (`gullet::input_unread_since`): it changes
1277 /// whenever a character or a line is read.
1278 pub fn read_position(&self) -> (usize, usize, usize, usize) {
1279 (
1280 self.lineno,
1281 self.colno,
1282 self.chars.len(),
1283 self.buffer.len() + self.raw_buffer.len(),
1284 )
1285 }
1286
1287 /// Checks if there is more input to process.
1288 ///
1289 /// Note: we need mutability, as we may refill the internal BufReader
1290 /// when performing the check.
1291 pub fn has_more_input(&mut self) -> bool {
1292 if !self.is_eol() || !self.buffer.is_empty() || !self.raw_buffer.is_empty() {
1293 return true;
1294 }
1295 // Peek the underlying reader if present. A fill_buf I/O error is treated
1296 // as end-of-input (return false) rather than panicking — the caller will
1297 // naturally stop requesting tokens and the Mouth will be closed out.
1298 match self.reader.as_mut() {
1299 Some(r) => r.fill_buf().map(|buf| !buf.is_empty()).unwrap_or(false),
1300 None => false,
1301 }
1302 }
1303
1304 /// Read the next token, or undef if exhausted.
1305 /// Note that this also returns COMMENT tokens containing source comments,
1306 /// and also locator comments (file, line# info).
1307 /// LaTeXML::Core::Gullet intercepts them and passes them on at appropriate times.
1308 pub fn read_token(&mut self) -> Option<Token> {
1309 loop {
1310 // Iterate till we find a token, or run out. (use return)
1311 // ===== Get next line, if we need to.
1312 if self.colno >= self.nchars {
1313 self.lineno += 1;
1314 self.colno = 0;
1315 let line_opt = self.get_next_line();
1316 // For \read, we have to return something for EOL, and handle implicit final newline
1317 let read_mode = lookup_int("PRESERVE_NEWLINES") > 1;
1318 let eolch = endline_char();
1319 if line_opt.is_none() {
1320 // Exhausted the input.
1321 let eolcc = if let Some(ch) = eolch {
1322 lookup_catcode(ch).unwrap_or(Catcode::OTHER)
1323 } else {
1324 Catcode::OTHER
1325 };
1326 let eoftoken = if let Some(eolch_content) = eolch {
1327 if read_mode && !self.at_eof && !self.source.is_empty() {
1328 // The synthetic final line is empty + `\endlinechar`, read in
1329 // state N like any other line (tex.web §345-349): an EOL char
1330 // is `\par`, a SPACE or IGNORE char is dropped (§349 "goto
1331 // switch" — it can never become a token), anything else is a
1332 // char token. Perl Mouth.pm:303-307 emits the IGNORE char and
1333 // it reaches the Stomach as `misdefined` (KNOWN_PERL_ERRORS
1334 // #125); witness liftarm (pgfmanual `codeexample` sets
1335 // `\catcode`\^^M=9` around `\scantokens`, and animate.sty's
1336 // `\@anim@buildtmln` `\read`s the timeline to EOF inside it —
1337 // 501 errors capped).
1338 match eolcc {
1339 Catcode::EOL => Some(T_CS!("\\par")),
1340 Catcode::SPACE | Catcode::IGNORE => None,
1341 _ => Some(CharToken!(eolch_content, eolcc)),
1342 }
1343 } else {
1344 None
1345 }
1346 } else {
1347 None
1348 };
1349 self.at_eof = true;
1350 self.chars = VecDeque::new();
1351 self.nchars = 0;
1352 return eoftoken;
1353 }
1354 // Remove trailing spaces from external sources
1355 let mut line = line_opt.unwrap();
1356 if !self.source.is_empty() && line.ends_with(' ') {
1357 line = TRAILING_SPACE_CHARS.replace(&line, "").to_string();
1358 }
1359 // Then append the appropriate \endlinechar, or "\r";
1360 if let Some(ch) = eolch {
1361 line.push(ch);
1362 }
1363
1364 self.chars.clear();
1365 self.chars.extend(line.chars());
1366 self.nchars = self.chars.len();
1367 // In state N, skip leading spaces & ignored, possibly decoding (trailing space removed
1368 // above)
1369 let mut peeked = false;
1370 while let Some((_ch, cc)) = self.get_next_char() {
1371 match cc {
1372 Catcode::SPACE | Catcode::IGNORE => {},
1373 Catcode::EOL => {
1374 // Eolch already? empty line!
1375 self.colno = self.nchars; // ignore rest of line.
1376 return Some(T_CS!("\\par"));
1377 },
1378 _ => {
1379 peeked = true;
1380 break;
1381 },
1382 }
1383 }
1384 // A line of only blanks and no catcode-5 `\endlinechar` yields no token (tex.web §347):
1385 // Perl Mouth.pm:320-331 backs up over its last tab or space-catcode `\endlinechar` and
1386 // reads a space (KNOWN_PERL_ERRORS #1387; pgfplots tables, 2012.13078).
1387 if peeked {
1388 // Back up over peeked char
1389 self.colno -= 1;
1390 } else if read_mode {
1391 // `\read` still ends this line.
1392 return Some(T_MARKER!("EOL"));
1393 }
1394 // Sneak a comment out, every so often.
1395 if self.lineno.is_multiple_of(READLINE_PROGRESS_QUANTUM) && lookup_bool("INCLUDE_COMMENTS")
1396 {
1397 // Perl T_COMMENT prepends '%' (Token.pm L81)
1398 return Some(T_COMMENT!(s!(
1399 "%**** {} Line {} ****",
1400 &self.shortsource,
1401 &self.lineno.to_string()
1402 )));
1403 }
1404 }
1405 // In state::S, skip spaces — and ignored characters, which leave the state as it is (tex.web §344
1406 // `any_state_plus(ignore)`): under `\ExplSyntaxOn` the (ignored) space of `\foo ~` kept TeX skipping, so the
1407 // `~` (a spacer) is skipped too, where stopping at the ignored character made it a space token
1408 // (`\str_if_eq:nnTF { \foo ~ } { \foo }` false). Perl Mouth.pm skips CC_SPACE only (KNOWN_PERL_ERRORS #1177).
1409 if self.skipping_spaces {
1410 let mut cc = None;
1411 // This is very awkward as a loop,
1412 // but I had to port the Perl logic without going crazy...
1413 // tokenizer/verb.tex depends on it.
1414 while let Some((_, ncc)) = self.get_next_char() {
1415 cc = Some(ncc);
1416 if !matches!(ncc, Catcode::SPACE | Catcode::IGNORE) {
1417 break;
1418 }
1419 }
1420 if self.colno <= self.nchars
1421 && cc.is_some()
1422 && !matches!(cc, Some(Catcode::SPACE | Catcode::IGNORE))
1423 {
1424 self.colno -= 1;
1425 }
1426 if cc == Some(Catcode::EOL) {
1427 // If we've got an EOL
1428 self.get_next_char();
1429 if self.colno < self.nchars {
1430 self.colno -= 1;
1431 }
1432 }
1433 self.skipping_spaces = false;
1434 }
1435 // ==== Extract next token from line.
1436 // §1 (docs/performance/SOURCE_PROVENANCE.md): record the token's source start now —
1437 // after all inter-token skips (line fetch, leading / skipping spaces) and
1438 // before `get_next_char` advances past its first char. `colno` is 0-indexed
1439 // here; the +1 to 1-indexed columns happens in `get_locator`.
1440 self.last_token_start = (self.lineno, self.colno);
1441 if let Some((ch, cc)) = self.get_next_char() {
1442 #[cfg(not(feature = "token-locators"))]
1443 if let Some(token) = Mouth::dispatch_char(self, ch, cc) {
1444 return Some(token);
1445 } // Else, repeat till we get something or run out.
1446 // token-locators: stamp the token with an origin handle into the side
1447 // arena, using `last_token_start` (the token's first char — captured
1448 // above, before `dispatch_char` reads the rest, e.g. a CS name). This is
1449 // what survives expansion to digestion (Experiments 1–3 showed the mouth
1450 // position at digest time cannot recover it). See SOURCE_PROVENANCE §3.1.1.
1451 #[cfg(feature = "token-locators")]
1452 if let Some(mut token) = Mouth::dispatch_char(self, ch, cc) {
1453 let (line, col0) = self.last_token_start;
1454 token.loc =
1455 crate::token::push_token_origin(self.source_sym, line as u32, (col0 + 1) as u32);
1456 return Some(token);
1457 } // Else, repeat till we get something or run out.
1458 }
1459 }
1460 }
1461
1462 //**********************************************************************
1463 /// Read all tokens until a token equal to $until (if given), or until exhausted.
1464 /// Returns an empty Tokens list, if there is no input
1465 pub fn read_tokens(&mut self) -> Tokens {
1466 // Pre-size to skip the early doubling reallocations of the per-token push
1467 // loop below (a `grow_one` site in the allocation profile); 16 covers a
1468 // typical line/group in one allocation.
1469 let mut tokens = Vec::with_capacity(16);
1470 while let Some(token) = self.read_token() {
1471 tokens.push(token);
1472 }
1473 while let Some(Token { code: Catcode::SPACE, .. }) = tokens.last() {
1474 // Remove trailing space
1475 tokens.pop();
1476 }
1477 Tokens::new(tokens)
1478 }
1479
1480 //**********************************************************************
1481 // Read a raw lines; there are so many variants of how it should end,
1482 // that the Mouth API is left as simple as possible.
1483 // Alas: $noread true means NOT to read a new line, but only return
1484 // the remainder of the current line, if any. This is useful when combining
1485 // with previously peeked tokens from the Gullet.
1486 /// The WHOLE current line as raw text, from column 0 — including the part
1487 /// already tokenized — and consume the rest of it. `None` when no line is
1488 /// loaded. Used by the listings raw-line reader when an optional-argument
1489 /// probe has already tokenized the body's first token (OXIDIZED_DESIGN #162).
1490 pub fn read_raw_line_from_start(&mut self) -> Option<String> {
1491 if self.nchars == 0 && self.colno == 0 {
1492 return None;
1493 }
1494 let mut line: String = self.chars.iter().collect();
1495 if line.ends_with('\r') {
1496 line.pop();
1497 }
1498 self.colno = self.nchars;
1499 Some(line)
1500 }
1501
1502 /// [`read_raw_line`](Self::read_raw_line) with the line's input bytes turned
1503 /// into the characters the declared input encoding makes of them
1504 /// (`eight_bit_input_char`, as the tokenizer does for a byte line). For a
1505 /// consumer that parses raw lines itself: a `.bib`, whose bytes real `bibtex`
1506 /// copies into the `.bbl` for the document's inputenc to decode. A cp1251
1507 /// `.bib` under `\usepackage[cp1251]{inputenc}` read `Ò. Ñ. Ãåéäåìàí` for
1508 /// "Т. С. Гейдеман" (shipunov/rusnat-ex1-ru, sweep #121).
1509 pub fn read_raw_line_decoded(&mut self, noread: bool) -> Option<String> {
1510 let line = self.read_raw_line(noread)?;
1511 Some(self.decode_eight_bit(line))
1512 }
1513
1514 /// `text` with its upper-half bytes (read as U+0080..U+00FF) turned into
1515 /// the characters the declared input encoding makes of them, when this
1516 /// mouth reads a byte line; unchanged otherwise.
1517 pub fn decode_eight_bit(&self, text: String) -> String {
1518 if !self.line_is_bytes {
1519 return text;
1520 }
1521 text
1522 .chars()
1523 .map(|c| {
1524 if ('\u{80}'..='\u{ff}').contains(&c) {
1525 eight_bit_input_char(c).unwrap_or(c)
1526 } else {
1527 c
1528 }
1529 })
1530 .collect()
1531 }
1532
1533 /// Make `rest` — the end of the line a raw read just took — the current line again, with the `\endlinechar` a
1534 /// line is read with ([`Self::read_token`]), so tokens and raw lines are read from it before the next line. Its
1535 /// columns count from the start of `rest` (the line number is the line's).
1536 pub fn restore_line_rest(&mut self, rest: &str) {
1537 let mut line = rest.to_string();
1538 if let Some(ch) = endline_char() {
1539 line.push(ch);
1540 }
1541 self.chars.clear();
1542 self.chars.extend(line.chars());
1543 self.nchars = self.chars.len();
1544 self.colno = 0;
1545 self.caret_bytes.clear();
1546 }
1547
1548 /// The source text this mouth will read next — the rest of the current line, then up to `max_lines` lines after it,
1549 /// joined by `\n`, at most `max_chars` characters in all — without reading it: nothing is consumed, tokenized or
1550 /// decoded in place. A look-ahead for a decision about what follows (stomach.rs `formula_continues_past_par`,
1551 /// OXIDIZED_DESIGN #553); `max_chars` keeps its cost bounded on a source whose current line is the whole document.
1552 /// Lines not yet decoded are read as UTF-8, lossily; their structure (`$`, `\int`, `_`) is all a look-ahead needs.
1553 /// A current line read to its end contributes nothing: its end-of-line character is read already, and an empty line
1554 /// in its place would tokenize as one more (a `\par`, or under `\obeylines` an active `^^M`; hep-ph9809328).
1555 pub fn peek_text(&self, max_lines: usize, max_chars: usize) -> String {
1556 // Whether a line is begun in `text` that the next must be joined to.
1557 let mut joined = self.colno < self.nchars;
1558 let mut text = String::new();
1559 let mut room = max_chars;
1560 for ch in self.chars.iter().skip(self.colno).take(max_chars) {
1561 text.push(*ch);
1562 room -= 1;
1563 }
1564 if room == 0 {
1565 return text;
1566 }
1567 if let Some(eol) = endline_char()
1568 && text.ends_with(eol)
1569 {
1570 text.pop();
1571 }
1572 let decoded = self
1573 .buffer
1574 .iter()
1575 .map(|line| std::borrow::Cow::Borrowed(line.as_str()));
1576 let raw = self
1577 .raw_buffer
1578 .iter()
1579 .map(|line| String::from_utf8_lossy(&self.raw_bytes[line.clone()]));
1580 for line in decoded.chain(raw).take(max_lines) {
1581 if room == 0 {
1582 break;
1583 }
1584 if joined {
1585 text.push('\n');
1586 }
1587 joined = true;
1588 let mut count = 0;
1589 text.extend(line.chars().take(room).inspect(|_| count += 1));
1590 room = room.saturating_sub(count + 1);
1591 }
1592 text
1593 }
1594
1595 pub fn read_raw_line(&mut self, noread: bool) -> Option<String> {
1596 let mut line = String::new();
1597 if self.colno < self.nchars {
1598 line = self.chars.iter().skip(self.colno).collect();
1599 // Strip the final carriage return, if it has been added back (Perl: s/\r$//s)
1600 if line.ends_with('\r') {
1601 line.pop();
1602 }
1603 self.colno = self.nchars;
1604 } else if !noread {
1605 match self.get_next_line() {
1606 None => {
1607 // We've exhausted this mouth
1608 self.at_eof = true;
1609 self.chars = VecDeque::new();
1610 self.nchars = 0;
1611 self.colno = 0;
1612 return None;
1613 },
1614 Some(next_line) => {
1615 // Strip trailing spaces (Perl: s/ *$//s)
1616 line = next_line.trim_end_matches(' ').to_string();
1617 self.lineno += 1;
1618 self.chars.clear();
1619 self.chars.extend(line.chars());
1620 self.nchars = self.chars.len();
1621 self.colno = self.nchars;
1622 },
1623 }
1624 }
1625 Some(line)
1626 }
1627
1628 fn dispatch_char(&mut self, ch: char, cc: Catcode) -> Option<Token> {
1629 // Possibly want to think about caching (common) letters, etc to keep from
1630 // creating tokens like crazy... or making them more compact... or ???
1631 use crate::token::Catcode::*;
1632 match cc {
1633 ESCAPE => self.handle_escape(), // T_ESCAPE
1634 BEGIN => {
1635 if ch == '{' {
1636 Some(T_BEGIN!())
1637 } else {
1638 Some(CharToken!(ch, BEGIN))
1639 }
1640 },
1641 END => {
1642 if ch == '}' {
1643 Some(T_END!())
1644 } else {
1645 Some(CharToken!(ch, END))
1646 }
1647 },
1648 MATH => {
1649 if ch == '$' {
1650 Some(T_MATH!())
1651 } else {
1652 Some(CharToken!(ch, MATH))
1653 }
1654 },
1655 ALIGN => {
1656 if ch == '&' {
1657 Some(T_ALIGN!())
1658 } else {
1659 Some(CharToken!(ch, ALIGN))
1660 }
1661 },
1662 EOL => Some(self.handle_end_of_line()),
1663 PARAM => {
1664 if ch == '#' {
1665 Some(T_PARAM!())
1666 } else {
1667 Some(CharToken!(ch, PARAM))
1668 }
1669 }, // T_PARAM
1670 SUPER => {
1671 if ch == '^' {
1672 Some(T_SUPER!())
1673 } else {
1674 Some(CharToken!(ch, SUPER))
1675 }
1676 }, // T_SUPER
1677 SUB => {
1678 if ch == '_' {
1679 Some(T_SUB!())
1680 } else {
1681 Some(CharToken!(ch, SUB))
1682 }
1683 }, // T_SUB
1684 SPACE => self.handle_space(),
1685 LETTER => Some(CharToken!(ch, LETTER)),
1686 OTHER => Some(CharToken!(ch, OTHER)),
1687 ACTIVE => Some(T_ACTIVE!(ch)),
1688 COMMENT => self.handle_comment(),
1689 INVALID => Some(CharToken!(ch, OTHER)), // T_INVALID (we could get unicode!)
1690 _ => None, // IGNORE, others
1691 }
1692 }
1693
1694 fn handle_end_of_line(&mut self) -> Token {
1695 self.colno = self.nchars; // Ignore any remaining characters after EOL
1696 if lookup_int("PRESERVE_NEWLINES") != 0 {
1697 Token!("\n", Catcode::SPACE)
1698 } else {
1699 T_SPACE!()
1700 }
1701 }
1702
1703 fn handle_space(&mut self) -> Option<Token> {
1704 // Skip any following spaces!
1705 while let Some((_ch, cc)) = self.get_next_char() {
1706 if (cc != Catcode::SPACE) && (cc != Catcode::EOL) {
1707 // backup at nonspace/eol
1708 if self.colno <= self.nchars {
1709 self.colno -= 1;
1710 }
1711 break;
1712 }
1713 }
1714 Some(T_SPACE!())
1715 }
1716
1717 fn handle_comment(&mut self) -> Option<Token> {
1718 let n = self.colno;
1719 self.colno = self.nchars;
1720 // the comment's text is spelled only when comments are kept (`--nocomments`, cortex's default, drops them)
1721 if lookup_bool_sym(crate::pin!("INCLUDE_COMMENTS")) {
1722 let comment: String = self.chars.iter().skip(n).take(self.nchars - n).collect();
1723 let trimmed_comment = comment.trim();
1724 if !trimmed_comment.is_empty() {
1725 // Perl T_COMMENT prepends '%' to the comment text (Token.pm L81)
1726 return Some(T_COMMENT!(s!("%{}", trimmed_comment)));
1727 }
1728 }
1729 if lookup_int("PRESERVE_NEWLINES") > 1 {
1730 Some(T_MARKER!("EOL")) // Required EOL during \read
1731 } else {
1732 None
1733 }
1734 }
1735
1736 //**********************************************************************
1737 // See The TeXBook, Chapter 8, The Characters You Type, pp.46--47.
1738 //**********************************************************************
1739
1740 /// Read control sequence
1741 fn handle_escape(&mut self) -> Option<Token> {
1742 // NOTE: We're using control sequences WITH the \ prepended!!!
1743 if let Some((ch, mut cc)) = self.get_next_char() {
1744 // Knuth, p.46 says that Newlines are converted to spaces,
1745 // Bit I believe that he does NOT mean within control sequences
1746 let mut cs = std::mem::take(&mut self.cs_name);
1747 cs.clear();
1748 cs.push('\\');
1749 cs.push(ch);
1750 if cc == Catcode::LETTER {
1751 // For letter, read more letters for csname.
1752 while let Some((nch, ncc)) = self.get_next_char() {
1753 cc = ncc;
1754 if ncc == Catcode::LETTER {
1755 cs.push(nch);
1756 } else {
1757 break;
1758 }
1759 }
1760 // We WILL skip spaces, but not till next token is read (in case catcode changes!!!!)
1761 self.skipping_spaces = true;
1762 if cc != Catcode::LETTER {
1763 self.colno -= 1;
1764 }
1765 }
1766 let token = T_CS!(&cs);
1767 self.cs_name = cs;
1768 Some(token)
1769 } else {
1770 None
1771 }
1772 }
1773
1774 /// TODO: Can we use/build a generic that does this reliably for VecDeque
1775 fn splice<R>(&mut self, range: R, with: &[char])
1776 where R: RangeBounds<usize> {
1777 let mut v: Vec<char> = self.chars.drain(..).collect();
1778 v.splice(range, with.iter().cloned());
1779 self.chars = v.into_iter().collect();
1780 }
1781
1782 /// Checks if Mouth read is at the end of a line.
1783 ///
1784 /// Careful:
1785 /// used BOTH for flushing input for `\endinput`
1786 /// and for detecting line end for `\read`
1787 /// tex.web §485-486: a `\read` consumes the WHOLE physical line
1788 /// (`input_ln`); the catcode regime only decides which tokens the line
1789 /// yields. Called by `\read` after its token loop so a residual
1790 /// `\endlinechar` character left behind under one regime (an IGNORE-catcode
1791 /// space under `\ExplSyntaxOn`) is never re-read as a spurious empty line by
1792 /// a later `\read` under another (l3prefixes: header `\ior_get` in the
1793 /// preamble, `\ior_map_inline` in the body → an empty first row →
1794 /// `Until:,` runaway).
1795 pub fn finish_physical_line(&mut self) { self.colno = self.nchars; }
1796
1797 pub fn is_eol(&mut self) -> bool {
1798 let savecolno = self.colno;
1799 // We have to peek past any ignored tokens & also spaces, if skipping
1800 let mut cc = None;
1801 while let Some((_, ncc)) = self.get_next_char() {
1802 if ncc != Catcode::IGNORE && (!self.skipping_spaces || ncc != Catcode::SPACE) {
1803 cc = Some(ncc);
1804 break;
1805 }
1806 }
1807 if self.colno <= self.nchars && cc.is_some() {
1808 // Back-up if too far.
1809 self.colno -= 1;
1810 }
1811 // If skipping spaces (really, reading for input (\endinput) ?), jump to end of EOL or comments
1812 if self.skipping_spaces && (cc == Some(Catcode::EOL) || cc == Some(Catcode::COMMENT)) {
1813 // If we've got an EOL | COMMENT
1814 self.colno = self.nchars
1815 }
1816 let eol = self.colno >= self.nchars;
1817 self.colno = savecolno;
1818 eol
1819 }
1820
1821 pub fn at_eof(&self) -> bool { self.at_eof }
1822
1823 /// The number of the line the Mouth is reading (1-based once the first line is fetched).
1824 pub fn line_number(&self) -> usize { self.lineno }
1825
1826 /// Where the most recently begun token starts: (line, 0-based column).
1827 pub fn last_token_start(&self) -> (usize, usize) { self.last_token_start }
1828
1829 /// §1 accurate-start locator (docs/performance/SOURCE_PROVENANCE.md): `from` = the captured
1830 /// start of the most recently *begun* token (`last_token_start`), `to` = the
1831 /// mouth's current position. Unlike `get_locator`, whose `from` is the
1832 /// eating-disorder heuristic (line start vs current col), this `from` is exact
1833 /// for the token currently being processed — the basis for accurate
1834 /// construct-start ranges under `--source-map`. `lineno` is already 1-indexed
1835 /// (it counts from 1 after the first line fetch); `colno` is 0-indexed, +1 to
1836 /// 1-indexed columns, matching `get_locator`.
1837 pub fn get_locator_from_start(&self) -> Locator {
1838 let (from_line, from_col0) = self.last_token_start;
1839 Locator::from_sym(
1840 self.source_sym,
1841 from_line as u32,
1842 (from_col0 + 1) as u32,
1843 self.lineno as u32,
1844 (self.colno + 1) as u32,
1845 )
1846 }
1847
1848 pub fn get_location(&self) -> String {
1849 let loc = self.get_locator().unwrap_or_default();
1850 s!("at {}", loc)
1851 }
1852}
1853
1854/// Tokenize a string under the **standard** catcode table — Perl
1855/// `Package.pm:Tokenize` L1019-1023.
1856///
1857/// "Standard" is the document-level table: `@` is an ordinary letter-less
1858/// character, so this is how user-facing text should be read. The current
1859/// state's catcodes are deliberately NOT consulted; the table is swapped in for
1860/// the duration and restored afterwards, exactly as Perl's `local $STATE =
1861/// $STD_CATTABLE` does, so a document that has been playing with catcodes
1862/// cannot change what a binding's own string means.
1863///
1864/// See [`tokenize_internal`] for the `.sty`-style table that treats `@` as a
1865/// letter.
1866///
1867/// The argument is an `impl Into<`[`TeXString`]`>`, not a `&str`: a string
1868/// literal converts implicitly, but a `String` — the shape a control-word-welding
1869/// `Tokens::to_string()` arrives in — must declare itself via
1870/// [`Tokens::untex_string`] or [`TeXString::assembled`]. See the [`TeXString`]
1871/// docs for why.
1872pub fn tokenize(text: impl Into<TeXString>) -> Tokens {
1873 let text = text.into();
1874 // special case! empty input is empty Tokens
1875 if text.is_empty() {
1876 return NO_TOKENS;
1877 }
1878 use_std_state();
1879 let result = Mouth::new(text.as_str(), None).unwrap().read_tokens();
1880 use_main_state();
1881 result
1882}
1883/// The characters a [`Mouth::with_bib_data_literals`] mouth reads as data: `% & #`, which BibTeX's lexer hands back as
1884/// ordinary characters (OXIDIZED_DESIGN #74), and `@`, which the entry scaffold's handler names
1885/// (`\csname bib@field@…\endcsname`) carry. A document's active `@` (1810.11524's amsrefs list reads `@book{…}`
1886/// records through it) re-entered `\bib` from inside the scaffold without end; Perl, reading the scaffold under the
1887/// live catcodes (BibTeX.pool.ltxml:166), errs 24 times.
1888pub const BIB_DATA_LITERALS: [char; 4] = ['%', '&', '#', '@'];
1889
1890/// Tokenize a string under the standard catcode table, reading `% & #` as
1891/// ordinary characters rather than comment, alignment tab and parameter.
1892///
1893/// For text that came out of the BibTeX lexer, which has none of those
1894/// constructs, so all three are data — treatment 1 of `OXIDIZED_DESIGN #74`,
1895/// see [`Mouth::with_bib_data_literals`] (including why `_` is not in the set).
1896/// Plain [`tokenize`] would let a `%` comment out the rest of the string, which
1897/// for a `.bib` field means losing its closing brace and leaving whatever it
1898/// opened unclosed, and would make the `&` in "Taylor & Francis" a stray
1899/// alignment tab.
1900///
1901/// This exists because the handlers that re-read a raw field — `\bib@@title`
1902/// recasing, name splitting, date/pages assembly — build their tokens from the
1903/// stored string and never pass through the per-entry mouth.
1904///
1905/// Takes an `impl Into<`[`TeXString`]`>` for the same reason as [`tokenize`] —
1906/// and it is the sink that most needs it: the bibliography is where the
1907/// control-word weld has surfaced three times (PR #399, PR #400, issue 410).
1908pub fn tokenize_bib_literal(text: impl Into<TeXString>) -> Tokens {
1909 let text = text.into();
1910 // special case! empty input is empty Tokens
1911 if text.is_empty() {
1912 return NO_TOKENS;
1913 }
1914 use_std_state();
1915 let result = Mouth::new(text.as_str(), None)
1916 .unwrap()
1917 .with_bib_data_literals()
1918 .read_tokens();
1919 use_main_state();
1920 result
1921}
1922
1923/// Tokenize a string under the **style-file** catcode table — Perl
1924/// `Package.pm:TokenizeInternal` L1026-1030.
1925///
1926/// Same swap-and-restore discipline as [`tokenize`], but with `@` a letter, so
1927/// internal control sequences (`\@ifnextchar`, `\@currentlabel`, …) tokenize as
1928/// single names. This is the right choice for a macro body a binding writes
1929/// itself, and the wrong one for text that came from the document.
1930///
1931/// Takes an `impl Into<`[`TeXString`]`>` for the same reason as [`tokenize`].
1932pub fn tokenize_internal(text: impl Into<TeXString>) -> Tokens {
1933 let text = text.into();
1934 // special case! empty input is empty Tokens
1935 if text.is_empty() {
1936 return NO_TOKENS;
1937 }
1938 use_sty_state();
1939 let result = Mouth::new(text.as_str(), None).unwrap().read_tokens();
1940 use_main_state();
1941 result
1942}
1943
1944/// The character `\endlinechar` ends each input line with (tex.web §362: none when it is outside 0..255).
1945fn endline_char() -> Option<char> {
1946 match lookup_definition(&T_CS!("\\endlinechar")).unwrap() {
1947 Some(defn) => {
1948 if defn.is_register()
1949 && let Some(eol) = defn.value_of(Vec::new())
1950 {
1951 let eol = eol.value_of() as i16;
1952 if eol > 0 && eol <= 255 {
1953 return Some((eol as u8) as char);
1954 }
1955 }
1956 None
1957 },
1958 _ => Some('\r'),
1959 }
1960}
1961
1962#[cfg(test)]
1963mod newline_tests {
1964 use super::*;
1965
1966 /// CRLF-input regression guard (WINDOWS_COMPATIBILITY_PLAN risk #5): a
1967 /// document saved with Windows line endings must tokenize identically to
1968 /// its LF twin — split_raw_lines implements TeX's universal end-of-line
1969 /// (\r\n, \r, and \n all terminate a line, and the terminator itself
1970 /// never reaches the catcode machinery).
1971 #[test]
1972 fn split_raw_lines_universal_newlines() {
1973 let lines = |bytes: &[u8]| -> Vec<Vec<u8>> {
1974 Mouth::split_raw_lines(bytes)
1975 .into_iter()
1976 .map(|range| bytes[range].to_vec())
1977 .collect()
1978 };
1979 let lf = lines(b"a\nb\nc");
1980 let crlf = lines(b"a\r\nb\r\nc");
1981 let cr = lines(b"a\rb\rc");
1982 assert_eq!(lf, crlf, "CRLF must split identically to LF");
1983 assert_eq!(lf, cr, "bare CR must split identically to LF");
1984 assert_eq!(lf.len(), 3);
1985 assert_eq!(lf[0], b"a");
1986 // A lone \r inside the terminator pair is consumed, not leaked into
1987 // the following line.
1988 assert!(
1989 crlf.iter().all(|line| !line.contains(&b'\r')),
1990 "no line may retain a raw CR byte"
1991 );
1992 }
1993}