Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

@@ -0,0 +1,572 @@
use super::{CatCode, CommandName, Dependency, Span, State, Token, TokenKind};
use std::collections::BTreeSet;
#[derive(Clone, Copy)]
struct Character {
value: char,
start: usize,
end: usize,
}
#[cfg(test)]
mod tests {
use super::*;
fn tokens(text: &str) -> Vec<Token> {
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 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 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,
}
enum LineBreaks {
Physical,
Generated(Option<char>),
}
pub(super) struct Mouth {
source: usize,
data: Vec<u8>,
profile: super::InputProfile,
offset: usize,
line: Vec<Character>,
cursor: usize,
state: LineState,
end_after_line: bool,
line_breaks: LineBreaks,
line_number: usize,
}
impl Mouth {
pub(super) fn payload_bytes(&self) -> usize {
self.data.len()
}
pub fn new(source: usize, data: Vec<u8>, profile: super::InputProfile) -> Self {
Self {
source,
data,
profile,
offset: 0,
line: Vec::new(),
cursor: 0,
state: LineState::New,
end_after_line: false,
line_breaks: LineBreaks::Physical,
line_number: 0,
}
}
pub(super) fn generated(
source: usize,
data: Vec<u8>,
profile: super::InputProfile,
separator: Option<char>,
) -> Self {
let mut mouth = Self::new(source, data, profile);
mouth.line_breaks = LineBreaks::Generated(separator);
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 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<Dependency>,
) -> Result<bool, (Span, String)> {
if self.end_after_line || self.offset == self.data.len() {
return Ok(false);
}
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 => {
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,
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(),
));
}
};
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;
Ok(true)
}
fn catcode(state: &State, reads: &mut BTreeSet<Dependency>, c: char) -> CatCode {
reads.insert(Dependency::CatCode(c));
state.catcode(c)
}
/// 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<Dependency>) -> Option<Character> {
loop {
let c = *self.line.get(self.cursor)?;
if Self::catcode(state, reads, c.value) != CatCode::Superscript
|| self.line.get(self.cursor + 1).map(|c| c.value) != Some(c.value)
{
return Some(c);
}
let Some(next) = self.line.get(self.cursor + 2).copied() else {
return Some(c);
};
let hex = |c: char| {
if c.is_ascii_digit() || ('a'..='f').contains(&c) {
c.to_digit(16)
} else {
None
}
};
let (value, consumed) = if let Some(a) = hex(next.value)
&& let Some(b) = self.line.get(self.cursor + 3).and_then(|c| hex(c.value))
{
(char::from_u32(16 * a + b).unwrap(), 4)
} else if (next.value as u32) < 128 {
(char::from_u32((next.value as u32) ^ 64).unwrap(), 3)
} else {
return Some(c);
};
let end = self.line[self.cursor + consumed - 1].end;
self.line.splice(
self.cursor..self.cursor + consumed,
[Character {
value,
start: c.start,
end,
}],
);
}
}
/// 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<Dependency>) -> Character {
let mut c = self.line[self.cursor];
let mut consumed = 1;
loop {
let second = self.cursor + consumed;
if Self::catcode(state, reads, c.value) != CatCode::Superscript
|| self.line.get(second).map(|v| v.value) != Some(c.value)
{
break;
}
let Some(next) = self.line.get(second + 1).copied() else {
break;
};
let hex = |c: char| {
if c.is_ascii_digit() || ('a'..='f').contains(&c) {
c.to_digit(16)
} else {
None
}
};
let (value, extra) = if let Some(a) = hex(next.value)
&& let Some(b) = self.line.get(second + 2).and_then(|v| hex(v.value))
{
(char::from_u32(16 * a + b).unwrap(), 3)
} else if (next.value as u32) < 128 {
(char::from_u32(next.value as u32 ^ 64).unwrap(), 2)
} else {
break;
};
c.value = value;
c.end = self.line[self.cursor + consumed + extra - 1].end;
consumed += extra;
}
self.cursor += consumed;
c
}
pub fn next(
&mut self,
state: &State,
reads: &mut BTreeSet<Dependency>,
) -> Result<Option<Token>, (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 => TokenKind::Command(CommandName::Control("par".into())),
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.end = 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.end = 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());
}
}
}