use super::{CatCode, CommandName, Dependency, Span, State, Token, TokenKind}; use std::{collections::BTreeSet, sync::Arc}; use super::xe_encoding::{Character, Encoding}; #[derive(Clone)] struct XePhysical { encoding: Encoding, autodetected: Option<(Encoding, usize)>, skip_lf: bool, terminated: bool, line_start: usize, } #[cfg(test)] mod tests { use super::*; fn tokens(text: &str) -> Vec { let mut mouth = Mouth::new(0, text.into(), super::super::InputProfile::UnicodeScalar); let mut reads = BTreeSet::new(); let mut tokens = Vec::new(); while let Some(token) = mouth.next(&State::default(), &mut reads).unwrap() { tokens.push(token); } tokens } #[test] fn whitespace_comments_control_words_and_empty_lines() { let kinds: Vec<_> = tokens(" \nA% no newline space\nB\n\n\\word C\\%D") .into_iter() .map(|t| t.kind) .collect(); assert_eq!( kinds, [ TokenKind::Command(CommandName::Control("par".into())), TokenKind::Character('A', CatCode::Letter), TokenKind::Character('B', CatCode::Letter), TokenKind::Character(' ', CatCode::Space), TokenKind::Command(CommandName::Control("par".into())), TokenKind::Command(CommandName::Control("word".into())), TokenKind::Character('C', CatCode::Letter), TokenKind::Command(CommandName::Control("%".into())), TokenKind::Character('D', CatCode::Letter), TokenKind::Character(' ', CatCode::Space), ] ); } #[test] fn escaped_spacer_keeps_its_character_and_skips_following_blanks() { let mut mouth = Mouth::new(0, "\\~ A\\ B".into(), super::super::InputProfile::TeX8Bit); let mut state = State::default(); state.assign_catcode('~', CatCode::Space, false); let mut reads = BTreeSet::new(); let mut kinds = Vec::new(); while let Some(token) = mouth.next(&state, &mut reads).unwrap() { kinds.push(token.kind); } assert_eq!( kinds, [ TokenKind::Command(CommandName::Control("~".into())), TokenKind::Character('A', CatCode::Letter), TokenKind::Command(CommandName::Control(" ".into())), TokenKind::Character('B', CatCode::Letter), TokenKind::Character(' ', CatCode::Space), ] ); } #[test] fn unread_character_category_changes_after_control_word_lookahead() { let mut mouth = Mouth::new( 0, "\\set!".into(), super::super::InputProfile::UnicodeScalar, ); let mut state = State::default(); let mut reads = BTreeSet::new(); assert_eq!( mouth.next(&state, &mut reads).unwrap().unwrap().kind, TokenKind::Command(CommandName::Control("set".into())) ); state.assign_catcode('!', CatCode::Active, false); assert_eq!( mouth.next(&state, &mut reads).unwrap().unwrap().kind, TokenKind::Command(CommandName::Active('!')) ); } #[test] fn endlinechar_is_frozen_when_the_physical_line_is_loaded() { let mut mouth = Mouth::new( 0, "A\nB\n".into(), super::super::InputProfile::UnicodeScalar, ); let mut state = State::default(); let mut reads = BTreeSet::new(); assert_eq!( mouth.next(&state, &mut reads).unwrap().unwrap().kind, TokenKind::Character('A', CatCode::Letter) ); state.assign_integer(super::super::state::Key::Endlinechar, -1, false); assert_eq!( mouth.next(&state, &mut reads).unwrap().unwrap().kind, TokenKind::Character(' ', CatCode::Space) ); assert_eq!( mouth.next(&state, &mut reads).unwrap().unwrap().kind, TokenKind::Character('B', CatCode::Letter) ); assert!(mouth.next(&state, &mut reads).unwrap().is_none()); } #[test] fn xe_normalization_preserves_reordered_bytes_and_control_word_extent() { use super::super::{InputProfile, Parameter, ParameterValue, state::Key}; let mut state = State::default().with_input_profile(InputProfile::XeTeX); state.assign_integer(Key::Endlinechar, -1, false); for mark in ['\u{0300}', '\u{0315}'] { state.assign_catcode(mark, CatCode::Letter, false); } let mut mouth = Mouth::new(0, "é\n\\a\u{0315}\u{0300}!\na\u{0315}\u{0300}é".into(), InputProfile::XeTeX); let mut reads = BTreeSet::new(); let first = mouth.next(&state, &mut reads).unwrap().unwrap(); assert!(matches!(first.kind, TokenKind::Character('é', _))); assert_eq!((first.span.start, first.span.end), (0, 2)); state.assign_parameter(Parameter::XeTeXinputnormalization, ParameterValue::Integer(2), false); let name = mouth.next(&state, &mut reads).unwrap().unwrap(); assert_eq!(name.kind, TokenKind::Command(CommandName::Control("a\u{0300}\u{0315}".into()))); assert_eq!((name.span.start, name.span.end), (3, 9)); for (value, range) in [ ('!', (9, 10)), ('a', (11, 12)), ('\u{0300}', (14, 16)), ('\u{0315}', (12, 14)), ('e', (16, 18)), ('\u{0301}', (16, 18)), ] { let token = mouth.next(&state, &mut reads).unwrap().unwrap(); assert!(matches!(token.kind, TokenKind::Character(c, _) if c == value)); assert_eq!((token.span.start, token.span.end), range); } assert!(reads.contains(&Dependency::Parameter(Parameter::XeTeXinputnormalization))); } #[test] fn disabled_endlinechar_does_not_merge_control_names_across_lines() { let mut mouth = Mouth::new( 0, "\\word\nabc\n".into(), super::super::InputProfile::UnicodeScalar, ); let mut state = State::default(); state.assign_integer(super::super::state::Key::Endlinechar, -1, false); let mut reads = BTreeSet::new(); assert_eq!( mouth.next(&state, &mut reads).unwrap().unwrap().kind, TokenKind::Command(CommandName::Control("word".into())) ); assert_eq!( mouth.next(&state, &mut reads).unwrap().unwrap().kind, TokenKind::Character('a', CatCode::Letter) ); } #[test] fn superscript_conversion_keeps_the_full_original_byte_span() { let tokens = tokens("\\^^61 ^^41 ^^a"); assert_eq!( tokens[0].kind, TokenKind::Command(CommandName::Control("a".into())) ); assert_eq!((tokens[0].span.start, tokens[0].span.end), (0, 5)); assert!( tokens .iter() .any(|t| t.kind == TokenKind::Character('A', CatCode::Letter)) ); assert!( tokens .iter() .any(|t| t.kind == TokenKind::Character('!', CatCode::Other)) ); } #[test] fn xetex_extended_superscripts_preserve_spans_in_characters_and_control_words() { use super::super::InputProfile; let text = r"^^^^2032 \wide^^^^4e2d^^^^^^01f600 ^^41 ^^^041 ^^^^^1f600"; let mut state = State::default().with_input_profile(InputProfile::XeTeX); state.assign_catcode('中', CatCode::Letter, false); state.assign_catcode('😀', CatCode::Letter, false); let mut mouth = Mouth::new(0, text.into(), InputProfile::XeTeX); let mut reads = BTreeSet::new(); let prime = mouth.next(&state, &mut reads).unwrap().unwrap(); assert_eq!(prime.kind, TokenKind::Character('′', state.catcode('′'))); assert_eq!((prime.span.start, prime.span.end), (0, 8)); assert!( mouth .next(&state, &mut reads) .unwrap() .unwrap() .kind .is_space() ); let word = mouth.next(&state, &mut reads).unwrap().unwrap(); let name = r"\wide^^^^4e2d^^^^^^01f600"; assert_eq!( word.kind, TokenKind::Command(CommandName::Control("wide中😀".into())) ); assert_eq!(&text[word.span.start..word.span.end], name); for expected in ['A', 'A', '😀'] { let token = loop { let token = mouth.next(&state, &mut reads).unwrap().unwrap(); if !token.kind.is_space() { break token; } }; assert_eq!(token.kind, TokenKind::Character(expected, CatCode::Letter)); } } #[test] fn xetex_utf16_lookahead_preserves_physical_spans_and_rebinding() { use super::super::InputProfile; let utf16 = |text: &str| { [0xff, 0xfe].into_iter() .chain(text.encode_utf16().flat_map(u16::to_le_bytes)) .collect::>() }; let state = State::default().with_input_profile(InputProfile::XeTeX); let mut reads = BTreeSet::new(); let mut mouth = Mouth::new(8, utf16("A\r\n😀\r\n"), InputProfile::XeTeX); let first = mouth.next(&state, &mut reads).unwrap().unwrap(); assert_eq!(first.span, Span { source: 8, start: 2, end: 4 }); assert_eq!(mouth.physical_frontier(), Some(6)); assert!(!mouth.matches_loaded_prefix(&utf16("B\r\n😀\r\n"))); let edited = utf16("A\r\nΩ\r\n"); assert!(mouth.matches_loaded_prefix(&edited)); mouth.rebind_loaded_prefix(edited); let white = mouth.next(&state, &mut reads).unwrap().unwrap(); assert!(white.kind.is_space()); let next = mouth.next(&state, &mut reads).unwrap().unwrap(); assert_eq!(next.kind, TokenKind::Character('Ω', state.catcode('Ω'))); assert_eq!(next.span, Span { source: 8, start: 8, end: 10 }); // With only CR loaded, the second byte still affects Auto detection. let mut first_line = Mouth::new(0, b"\rA".to_vec(), InputProfile::XeTeX); first_line.load_line(&state, &mut reads).unwrap(); assert!(!first_line.matches_loaded_prefix(b"\r\0A\0")); } #[test] fn physical_line_endings_and_utf8_byte_offsets_are_preserved() { let result = tokens("é界 \r\nB\rC"); assert_eq!((result[0].span.start, result[0].span.end), (0, 2)); assert_eq!((result[1].span.start, result[1].span.end), (2, 5)); let chars: String = result .iter() .filter_map(|t| match t.kind { TokenKind::Character(c, _) => Some(c), _ => None, }) .collect(); assert_eq!(chars, "é界 B C "); } } #[derive(Clone, Copy)] enum LineState { New, Middle, Skip, } #[derive(Clone)] enum LineBreaks { Physical, Generated(Option), } #[derive(Clone)] pub(super) struct Mouth { source: usize, data: Arc>, profile: super::InputProfile, offset: usize, line: Vec, cursor: usize, state: LineState, end_after_line: bool, line_breaks: LineBreaks, line_number: usize, xe: Option, invalid_utf8: Vec<(usize, usize)>, } impl Mouth { pub(super) fn physical_frontier(&self) -> Option { (matches!(self.line_breaks, LineBreaks::Physical) && !self.end_after_line && self.offset > 0) .then_some(self.offset) } pub(super) fn matches_loaded_prefix(&self, data: &[u8]) -> bool { let Some(offset) = self.physical_frontier() else { return false; }; let loaded = &self.data[..offset]; if let Some(xe) = &self.xe { return (xe.terminated || offset == data.len()) && xe.autodetected.as_ref().is_none_or(|old| *old == Encoding::Auto.resolve(data)) && data.starts_with(loaded); } // A CR looks ahead for LF. For an unterminated line, EOF is part // of what has already been observed. let same_boundary = match loaded.last() { Some(b'\r') => data.get(offset) != Some(&b'\n'), Some(b'\n') => true, _ => data.len() == offset, }; same_boundary && data.starts_with(loaded) } pub(super) fn rebind_loaded_prefix(&mut self, data: Vec) { debug_assert!(self.matches_loaded_prefix(&data)); self.data = Arc::new(data); } pub(super) fn payload_bytes(&self) -> usize { self.data.len() } pub fn new(source: usize, data: Vec, profile: super::InputProfile) -> Self { Self::with_encoding(source, data, profile, &Encoding::Auto) } pub(super) fn with_encoding( source: usize, data: Vec, profile: super::InputProfile, encoding: &Encoding, ) -> Self { let (xe, offset) = if profile == super::InputProfile::XeTeX { let (resolved, bom) = encoding.resolve(&data); let detected = (*encoding == Encoding::Auto).then(|| (resolved.clone(), bom)); (Some(XePhysical { encoding: resolved, autodetected: detected, skip_lf: false, terminated: false, line_start: bom, }), bom) } else { (None, 0) }; Self { source, data: Arc::new(data), profile, offset, line: Vec::new(), cursor: 0, state: LineState::New, end_after_line: false, line_breaks: LineBreaks::Physical, line_number: 0, xe, invalid_utf8: Vec::new(), } } pub(super) fn generated( source: usize, data: Vec, profile: super::InputProfile, separator: Option, ) -> Self { let mut mouth = Self::new(source, data, profile); mouth.line_breaks = LineBreaks::Generated(separator); mouth.xe = None; mouth.offset = 0; mouth } pub(super) fn forced_eof(&self) -> bool { self.end_after_line } pub(super) fn advance_eof_context(&mut self) { self.line_number += 1; } pub(super) fn enter_eof_line(&mut self) -> usize { self.line_number += 1; self.line.clear(); self.cursor = 0; self.line_number } pub fn end_input(&mut self) { self.end_after_line = true; } pub(super) fn change_encoding(&mut self, encoding: Encoding) -> bool { if let Some(xe) = &mut self.xe { xe.encoding = encoding; true } else { false } } pub(super) fn xe_location(&self, offset: usize) -> Option<(usize, usize)> { let xe = self.xe.as_ref()?; (xe.line_start <= offset && offset <= self.offset && self.line_number > 0).then(|| { // Canonical ordering can move a mark ahead of an earlier byte range. let preceding = self .line .iter() .filter(|c| c.end <= offset && c.start < offset) .count(); (self.line_number, 1 + preceding) }) } pub(super) fn take_utf8_warnings(&mut self) -> Vec<(usize, usize)> { std::mem::take(&mut self.invalid_utf8) } pub fn line_number(&self) -> usize { self.line_number } pub(super) fn context(&self, out: &mut super::context::Pseudo, endlinechar: i32) { let end = if self .line .last() .is_some_and(|c| c.value as i32 == endlinechar) { self.line.len().saturating_sub(1) } else { self.line.len() }; for (i, c) in self.line[..end].iter().enumerate() { if i == self.cursor { out.split(); } out.character(c.value); } if self.cursor >= end { out.split(); } } pub(super) fn load_line( &mut self, state: &State, reads: &mut BTreeSet, ) -> Result { if self.end_after_line || self.offset == self.data.len() { return Ok(false); } if self.xe.is_some() { return self.load_xe_line(state, reads); } let start = self.offset; self.line_number += 1; let remaining = &self.data[start..]; let (content_end, end) = if let LineBreaks::Generated(separator) = self.line_breaks { let boundary = separator.and_then(|separator| { let mut encoded = [0; 4]; let delimiter = match self.profile { super::InputProfile::TeX8Bit => { encoded[0] = separator as u8; &encoded[..1] } super::InputProfile::UnicodeScalar | super::InputProfile::XeTeX => { separator.encode_utf8(&mut encoded).as_bytes() } }; remaining .windows(delimiter.len()) .position(|part| part == delimiter) .map(|index| (start + index, delimiter.len())) }); boundary.map_or( (self.data.len(), self.data.len()), |(content_end, width)| (content_end, content_end + width), ) } else { let length = remaining .iter() .position(|c| matches!(c, b'\r' | b'\n')) .unwrap_or(remaining.len()); let content_end = start + length; let mut end = content_end; if self.data.get(end) == Some(&b'\r') { end += 1; } if self.data.get(end) == Some(&b'\n') { end += 1; } (content_end, end) }; self.offset = end; let mut trimmed = content_end; while trimmed > start && self.data[trimmed - 1] == b' ' { trimmed -= 1; } self.line = match self.profile.characters(&self.data[start..trimmed]) { Ok(characters) => characters .map(|(index, value)| Character { value: if matches!(self.line_breaks, LineBreaks::Generated(_)) { value } else { state.translate_input_character(value) }, start: start + index, end: start + index + self.profile.width(value), }) .collect(), Err(e) => { // A malformed scalar line still owns real bytes. Show those // bytes at the failing cursor, never a stale previous line or // replacement characters masquerading as source input. self.line = self.data[start..trimmed] .iter() .enumerate() .map(|(i, &b)| Character { value: char::from(b), start: start + i, end: start + i + 1, }) .collect(); self.cursor = e.valid_up_to(); let at = start + e.valid_up_to(); return Err(( Span { source: self.source, start: at, end: at + e.error_len().unwrap_or(trimmed - at), }, "invalid UTF-8 input for Unicode scalar profile".into(), )); } }; self.finish_line(content_end, end, state, reads); Ok(true) } fn load_xe_line( &mut self, state: &State, reads: &mut BTreeSet, ) -> Result { let xe = self.xe.as_mut().unwrap(); let framing = xe.encoding.framing(); let width = framing.unit_width(); if std::mem::take(&mut xe.skip_lf) && framing.code_unit(&self.data[self.offset..]) == Some(10) { self.offset += width; } let start = self.offset; if start == self.data.len() { return Ok(false); } let (length, terminator) = framing.line_boundary(&self.data[start..]); let content_end = start + length; let end = content_end + if terminator.is_some() { width } else { 0 }; xe.line_start = start; xe.skip_lf = terminator == Some(13); xe.terminated = terminator.is_some(); self.offset = end; self.line_number += 1; self.line.clear(); self.cursor = 0; let (characters, invalid_utf8) = xe.encoding .decode_line(&self.data[start..content_end], start, state, reads) .map_err(|message| (Span { source: self.source, start, end: content_end }, message))?; self.line = characters; if invalid_utf8 > 0 { self.invalid_utf8.push((self.line_number, invalid_utf8)); } self.finish_line(content_end, end, state, reads); Ok(true) } fn finish_line( &mut self, content_end: usize, end: usize, state: &State, reads: &mut BTreeSet, ) { reads.insert(Dependency::EndLineChar); if let Ok(value) = u32::try_from(state.endlinechar) && value <= 255 && let Some(value) = char::from_u32(value) { self.line.push(Character { value, start: content_end, end, }); } self.cursor = 0; self.state = LineState::New; } fn catcode(state: &State, reads: &mut BTreeSet, c: char) -> CatCode { reads.insert(Dependency::CatCode(c)); state.catcode(c) } // next points at the second superscript mark. The returned length // includes that mark and all remaining characters in the encoding. fn expanded_superscript(&self, mark: char, next: usize) -> Option<(char, usize)> { if self.line.get(next)?.value != mark { return None; } let single = self.line.get(next + 1)?.value; let mut count = 2; if self.profile == super::InputProfile::XeTeX { // XeTeX counts matching marks while the current encoding still // has enough physical line slots. It supports up to six digits. while count < 6 && next + 2 * count - 2 < self.line.len() && self.line[next + count - 1].value == mark { count += 1; } } let first_digit = next + count - 1; let hex = self .line .get(first_digit..first_digit + count) .and_then(|digits| { digits.iter().try_fold(0, |value, digit| { let digit = match digit.value { '0'..='9' => digit.value as u32 - u32::from('0'), 'a'..='f' => digit.value as u32 - u32::from('a') + 10, _ => return None, }; Some(value * 16 + digit) }) }); if let Some(code) = hex { return char::from_u32(code).map(|value| (value, 2 * count - 1)); } single .is_ascii() .then(|| (char::from(single as u8 ^ 64), 2)) } /// Decode TeX's ^^ form before category lookup. Category changes affect /// unread characters; tokens already in macro bodies are never retokenized. fn peek(&mut self, state: &State, reads: &mut BTreeSet) -> Option { loop { let c = *self.line.get(self.cursor)?; if Self::catcode(state, reads, c.value) != CatCode::Superscript { return Some(c); } let Some((value, extra)) = self.expanded_superscript(c.value, self.cursor + 1) else { return Some(c); }; let mut replacement = Character { value, ..c }; for &part in &self.line[self.cursor + 1..=self.cursor + extra] { replacement.cover(part); } self.line.splice(self.cursor..=self.cursor + extra, [replacement]); } } /// get_next's ordinary ^^ conversion changes cur_chr and advances loc. /// Only the control-sequence scanner rewrites the input buffer (peek). /// Keeping these paths distinct also preserves TeX's displayed context. fn next_character(&mut self, state: &State, reads: &mut BTreeSet) -> Character { let mut c = self.line[self.cursor]; self.cursor += 1; while Self::catcode(state, reads, c.value) == CatCode::Superscript { let Some((value, extra)) = self.expanded_superscript(c.value, self.cursor) else { break; }; c.value = value; for &part in &self.line[self.cursor..self.cursor + extra] { c.cover(part); } self.cursor += extra; } c } pub fn next( &mut self, state: &State, reads: &mut BTreeSet, ) -> Result, (Span, String)> { loop { while self.cursor == self.line.len() { if !self.load_line(state, reads)? { return Ok(None); } } let c = self.next_character(state, reads); let mut span = Span { source: self.source, start: c.start, end: c.end, }; let code = Self::catcode(state, reads, c.value); let kind = match code { CatCode::Ignored => continue, CatCode::Invalid => { return Err(( span, format!("invalid input character U+{:04X}", c.value as u32), )); } CatCode::Comment => { self.cursor = self.line.len(); continue; } CatCode::Space => { if !matches!(self.state, LineState::Middle) { continue; } self.state = LineState::Skip; TokenKind::Character(' ', CatCode::Space) } CatCode::EndLine => { self.cursor = self.line.len(); let kind = match self.state { LineState::New => { reads.insert(Dependency::ParagraphToken); state.paragraph_token() } LineState::Middle => TokenKind::Character(' ', CatCode::Space), LineState::Skip => continue, }; self.state = LineState::New; kind } CatCode::Escape => { let mut name = String::new(); if let Some(next) = self.peek(state, reads) { self.cursor += 1; span.start = span.start.min(next.start); span.end = span.end.max(next.end); name.push(next.value); let code = Self::catcode(state, reads, next.value); if code == CatCode::Letter { while let Some(next) = self.peek(state, reads) { if Self::catcode(state, reads, next.value) != CatCode::Letter { break; } name.push(next.value); span.start = span.start.min(next.start); span.end = span.end.max(next.end); self.cursor += 1; } self.state = LineState::Skip; } else if code == CatCode::Space { self.state = LineState::Skip; } else { self.state = LineState::Middle; } } TokenKind::Command(CommandName::Control(name)) } CatCode::Active => { self.state = LineState::Middle; TokenKind::Command(CommandName::Active(c.value)) } _ => { self.state = LineState::Middle; TokenKind::Character(c.value, code) } }; return Ok(Some(Token::new(kind, span))); } } } #[cfg(test)] mod byte_tests { use super::*; use crate::execution::InputProfile; #[test] fn raw_bytes_have_byte_spans_and_profile_decoding_preserves_original_offsets() { let mut state = State::default().with_input_profile(InputProfile::TeX8Bit); for b in 0..=255u8 { state.assign_catcode(char::from(b), CatCode::Other, false); } state.assign_integer(crate::execution::state::Key::Endlinechar, -1, false); let mut mouth = Mouth::new(7, (0..=255u8).collect(), InputProfile::TeX8Bit); let mut reads = BTreeSet::new(); for b in (0..=255u8).filter(|b| !matches!(b, b'\r' | b'\n')) { let t = mouth.next(&state, &mut reads).unwrap().unwrap(); assert_eq!(t.kind, TokenKind::Character(char::from(b), CatCode::Other)); assert_eq!( t.span, Span { source: 7, start: usize::from(b), end: usize::from(b) + 1 } ); } assert!(mouth.next(&state, &mut reads).unwrap().is_none()); for (profile, expected) in [ ( InputProfile::TeX8Bit, vec![ ('Ã', 0, 1), ('©', 1, 2), ('ç', 2, 3), ('\u{95}', 3, 4), ('\u{8c}', 4, 5), ], ), (InputProfile::UnicodeScalar, vec![('é', 0, 2), ('界', 2, 5)]), ] { let mut m = Mouth::new(2, "é界".as_bytes().to_vec(), profile); for (c, start, end) in expected { let t = m.next(&state, &mut reads).unwrap().unwrap(); assert_eq!(t.kind, TokenKind::Character(c, CatCode::Other)); assert_eq!((t.span.start, t.span.end), (start, end)); } assert!(m.next(&state, &mut reads).unwrap().is_none()); } } }