diff --git a/Cargo.lock b/Cargo.lock index 377cedc..4e9cdcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -758,6 +758,16 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + [[package]] name = "libm" version = "0.2.16" @@ -1522,6 +1532,7 @@ dependencies = [ "hyphenate", "image 0.23.14", "libc", + "libloading", "lopdf", "md5", "png 0.18.1", diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index c3be018..f209667 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -9,6 +9,7 @@ description = "Experimental incremental TeX-compatible typesetting core (route D flate2 = "1.1" image = { version = "0.23.12", default-features = false, features = ["bmp"] } lopdf = "0.26" +libloading = "=0.8.9" md5 = "0.8" png = "0.18.1" rusttype = "0.8.3" diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index f76ff3b..037af73 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -513,6 +513,15 @@ impl Executor { } } } + if let Some((line, column)) = self.inputs.iter().rev().find_map(|frame| match frame { + InputFrame::Source { source, mouth, .. } if *source == span.source => { + mouth.xe_location(span.start) + } + _ => None, + }) { + error.line = line; + error.column = column; + } error.context = self.input_context(); error.scanner_status = self.scanner_status.clone(); error @@ -561,7 +570,13 @@ impl Executor { return self.fail("native input stack limit exceeded"); } let source = self.sources.len(); - let mouth = Mouth::new(source, file.data.clone(), self.state.input_profile()); + let profile = self.state.input_profile(); + if profile == InputProfile::XeTeX { + self.reads.insert(Dependency::XeDefaultInputEncoding); + } + let mouth = Mouth::with_encoding( + source, file.data.clone(), profile, &self.state.xe_default_encoding, + ); self.sources.push(file); self.reads.insert(Dependency::Source(source)); self.inputs.push(InputFrame::Source { @@ -2728,7 +2743,11 @@ impl Executor { data: Vec::new(), }); self.stream_sources.insert(source); - self.io.inputs.insert(index, InputStream { source }); + let xe_encoding = (self.state.input_profile() == InputProfile::XeTeX).then(|| { + self.reads.insert(Dependency::XeDefaultInputEncoding); + self.state.xe_default_encoding.clone() + }); + self.io.inputs.insert(index, InputStream { source, xe_encoding, xe_skip_lf: false }); self.reads.insert(Dependency::Source(source)); } } @@ -2774,9 +2793,7 @@ impl Executor { let mut depth = 0i32; loop { self.tick()?; - let line = files - .read_line(index) - .map_err(|e| self.error(e, self.current))?; + let (line, encoding) = self.read_physical_stream_line(index, source, files)?; let eof = line.is_none(); if eof { files @@ -2793,42 +2810,52 @@ impl Executor { let end = self.sources[source].data.len(); self.reads.insert(Dependency::EndLineChar); if readline { - let mut length = line.len(); - while length > 0 && matches!(line[length - 1], b'\r' | b'\n' | b' ') { - length -= 1; - } - let characters = self - .state - .input_profile() - .characters(&line[..length]) - .map_err(|e| { - self.error( + let chars: Vec = if let Some(encoding) = &encoding { + let (resolved, bom) = encoding.resolve(&line); + let (length, _) = resolved.framing().line_boundary(&line[bom..]); + let (mut chars, warnings) = resolved.decode(&line[bom..bom + length], base + bom) + .map_err(|e| self.error(e, Span { source, start: base + bom, end }))?; + while chars.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) { + chars.pop(); + } + if warnings > 0 { + self.observe_xe_utf8_warnings( + vec![(self.input_position.map_or(1, |(_, line)| line), warnings)], + files, + )?; + } + chars + } else { + let mut length = line.len(); + while length > 0 && matches!(line[length - 1], b'\r' | b'\n' | b' ') { + length -= 1; + } + let profile = self.state.input_profile(); + profile.characters(&line[..length]) + .map_err(|e| self.error( "invalid UTF-8 input for Unicode scalar profile", Span { source, start: base + e.valid_up_to(), - end: base - + e.valid_up_to() + end: base + e.valid_up_to() + e.error_len().unwrap_or(length - e.valid_up_to()), }, - ) - })?; - for (offset, c) in characters { + ))? + .map(|(offset, value)| xe_encoding::Character { + value, + start: base + offset, + end: base + offset + profile.width(value), + }) + .collect() + }; + for c in chars { self.tick()?; body.push(Token::new( TokenKind::Character( - c, - if c == ' ' { - CatCode::Space - } else { - CatCode::Other - }, + c.value, + if c.value == ' ' { CatCode::Space } else { CatCode::Other }, ), - Span { - source, - start: base + offset, - end: base + offset + self.state.input_profile().width(c), - }, + Span { source, start: c.start, end: c.end }, )); if body.len() > self.limits.tokens { return self.fail("native read token limit exceeded"); @@ -2855,11 +2882,14 @@ impl Executor { } // Mouth reads exactly one physical line with the current categories; // the virtual EOF line is real TeX read semantics, not host data. - let mut mouth = Mouth::new( - source, - if eof { b"\n".to_vec() } else { line }, - self.state.input_profile(), - ); + let profile = self.state.input_profile(); + let mut mouth = if eof { + Mouth::generated(source, b"\n".to_vec(), profile, Some('\n')) + } else { + Mouth::with_encoding( + source, line, profile, encoding.as_ref().unwrap_or(&xe_encoding::Encoding::Auto), + ) + }; while let Some(mut token) = mouth .next(&self.state, &mut self.reads) @@ -2888,6 +2918,7 @@ impl Executor { return self.fail("native read token limit exceeded"); } } + self.observe_xe_utf8_warnings(mouth.take_utf8_warnings(), files)?; if depth == 0 { break; } @@ -3188,6 +3219,8 @@ impl Executor { Primitive::XeTeXrevision => "XeTeXrevision".into(), Primitive::XeTeXpdffile => "XeTeXpdffile".into(), Primitive::XeTeXpicfile => "XeTeXpicfile".into(), + Primitive::XeTeXinputencoding => "XeTeXinputencoding".into(), + Primitive::XeTeXdefaultencoding => "XeTeXdefaultencoding".into(), Primitive::BeginL => "beginL".into(), Primitive::EndL => "endL".into(), Primitive::BeginR => "beginR".into(), @@ -3645,6 +3678,8 @@ impl Executor { let line = mouth .load_line(&self.state, &mut self.reads) .map(|_| (*source, mouth.line_number())); + let warnings = mouth.take_utf8_warnings(); + self.observe_xe_utf8_warnings(warnings, files)?; self.input_position = Some(line.map_err(|(span, message)| self.error(message, span))?); self.push_mode_hook(TokenParameter::Everyjob)?; @@ -3872,6 +3907,9 @@ impl Executor { self.request_page(); self.events.push(Event::Paragraph(token.span)); } + XeTeXinputencoding | XeTeXdefaultencoding => { + self.change_xe_encoding(primitive, files)?; + } BeginL | EndL | BeginR | EndR => { let boundary = match primitive { BeginL => DirectionBoundary::BeginL, diff --git a/crates/texrra-tex-core/src/execution/engine/input.rs b/crates/texrra-tex-core/src/execution/engine/input.rs index 4964507..92da1c9 100644 --- a/crates/texrra-tex-core/src/execution/engine/input.rs +++ b/crates/texrra-tex-core/src/execution/engine/input.rs @@ -38,6 +38,7 @@ impl Executor { let Some(input) = self.inputs.last_mut() else { return Ok(None); }; + let mut warnings = Vec::new(); let next = match input { InputFrame::Tokens { tokens, cursor, .. } => { let t = tokens.get(*cursor).cloned(); @@ -85,41 +86,45 @@ impl Executor { eof_seen, pseudo_trace, .. - } => match mouth.next(&self.state, &mut self.reads) { - Ok(Some(token)) => { - self.input_position = Some((*source, mouth.line_number())); - Next::Token(Some(token.into())) - } - Ok(None) => { - if self.state.profile() == Profile::EtexBootstrap - && !*eof_seen - && !mouth.forced_eof() - { - self.reads - .insert(Dependency::TokenParameter(TokenParameter::Everyeof)); - if self - .state - .token_parameter(TokenParameter::Everyeof) - .is_some() + } => { + let token = mouth.next(&self.state, &mut self.reads); + warnings = mouth.take_utf8_warnings(); + match token { + Ok(Some(token)) => { + self.input_position = Some((*source, mouth.line_number())); + Next::Token(Some(token.into())) + } + Ok(None) => { + if self.state.profile() == Profile::EtexBootstrap + && !*eof_seen + && !mouth.forced_eof() { - *eof_seen = true; - self.input_position = Some((*source, mouth.enter_eof_line())); - Next::EofHook + self.reads + .insert(Dependency::TokenParameter(TokenParameter::Everyeof)); + if self + .state + .token_parameter(TokenParameter::Everyeof) + .is_some() + { + *eof_seen = true; + self.input_position = Some((*source, mouth.enter_eof_line())); + Next::EofHook + } else { + Next::EndSource { + source: *source, + trace: *pseudo_trace, + } + } } else { Next::EndSource { source: *source, trace: *pseudo_trace, } } - } else { - Next::EndSource { - source: *source, - trace: *pseudo_trace, - } } + Err((span, text)) => Next::Error(span, text), } - Err((span, text)) => Next::Error(span, text), - }, + } InputFrame::Hook { tokens, cursor, .. } => { let t = tokens.get(*cursor).cloned().map(InputToken::from); if t.is_some() { @@ -129,6 +134,7 @@ impl Executor { } InputFrame::Boundary => Next::Boundary, }; + self.observe_xe_utf8_warnings(warnings, files)?; match next { Next::Token(Some(token)) => { self.current = token.token.invocation.unwrap_or(token.token.span); @@ -169,6 +175,119 @@ impl Executor { } } } + pub(super) fn read_physical_stream_line( + &mut self, + index: u8, + source: usize, + files: &mut impl SourceProvider, + ) -> Result<(Option>, Option), Error> { + loop { + let stream = &self.io.inputs[&index]; + let Some(encoding) = stream.xe_encoding.clone() else { + return files + .read_line(index) + .map(|line| (line, None)) + .map_err(|error| self.error(error, self.current)); + }; + let Some(line) = files + .read_xe_line(index, encoding.framing()) + .map_err(|error| self.error(error, self.current))? + else { + return Ok((None, Some(encoding))); + }; + let (resolved, bom) = encoding.resolve(&line); + let framing = resolved.framing(); + let (length, terminator) = framing.line_boundary(&line[bom..]); + let empty_after_bom = bom != 0 && line.len() == bom; + let skipped_lf = stream.xe_skip_lf && length == 0 && terminator == Some(10); + let stream = self.io.inputs.get_mut(&index).unwrap(); + stream.xe_encoding = Some(resolved); + // External providers may deliver an already joined CRLF. + stream.xe_skip_lf = + terminator == Some(13) && bom + length + framing.unit_width() == line.len(); + if empty_after_bom || skipped_lf { + self.sources[source].data.extend_from_slice(&line); + } else { + return Ok((Some(line), Some(encoding))); + } + } + } + + pub(super) fn change_xe_encoding( + &mut self, + primitive: Primitive, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + use super::super::xe_encoding::Encoding; + let name = self.filename(files)?; + let encoding = match Encoding::parse(&name).map_err(|e| self.error(e, self.current))? { + Some(encoding) => encoding, + None => { + self.observe_xe_input_warning( + &format!("\nUnknown encoding `{name}'; reading as raw bytes\n"), + 1, + files, + )?; + Encoding::Bytes + } + }; + if primitive == Primitive::XeTeXdefaultencoding { + self.state.xe_default_encoding = encoding; + return Ok(()); + } + if encoding == Encoding::Auto { + return self.fail(r"Encoding mode `auto' is not valid for \XeTeXinputencoding"); + } + for frame in self.inputs.iter_mut().rev() { + if let InputFrame::Source { mouth, .. } = frame + && mouth.change_encoding(encoding.clone()) + { + return Ok(()); + } + } + self.fail(r"\XeTeXinputencoding requires a physical input file") + } + + pub(super) fn observe_xe_utf8_warnings( + &mut self, + warnings: Vec<(usize, usize)>, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + for (line, count) in warnings { + self.observe_xe_input_warning( + &format!("\nInvalid UTF-8 byte or sequence at line {line} replaced by U+FFFD.\n"), + count, + files, + )?; + } + Ok(()) + } + + fn observe_xe_input_warning( + &mut self, + message: &str, + count: usize, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + self.diagnostic_bytes = self + .diagnostic_bytes + .saturating_add(message.len().saturating_mul(count)); + if self.diagnostic_bytes > self.limits.tokens { + return self.fail("native diagnostic output limit exceeded"); + } + let destination = if self.read_parameter(Parameter::Tracingonline).width() > 0 { + WriteDestination::TerminalAndLog + } else { + WriteDestination::Log + }; + for _ in 0..count { + files + .observe_diagnostic(destination, message) + .map_err(|e| self.error(e, self.current))?; + } + Ok(()) + } + fn restore_input_position(&mut self) { if let Some(position) = self.inputs.iter().rev().find_map(|frame| match frame { InputFrame::Source { source, mouth, .. } => Some((*source, mouth.line_number())), diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 6a53292..9b74d2d 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,9 +8,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 68; -const COMPATIBLE_SCHEMAS: [u32; 35] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, SCHEMA, +const SCHEMA: u32 = 69; +const COMPATIBLE_SCHEMAS: [u32; 36] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/input_profile.rs b/crates/texrra-tex-core/src/execution/input_profile.rs index a9285aa..7dab9ba 100644 --- a/crates/texrra-tex-core/src/execution/input_profile.rs +++ b/crates/texrra-tex-core/src/execution/input_profile.rs @@ -7,7 +7,7 @@ pub enum InputProfile { TeX8Bit, #[default] UnicodeScalar, - /// UTF-8 input, XeTeX primitives and XDV-device semantics. + /// Per-file Unicode input encodings, XeTeX primitives and XDV semantics. XeTeX, } impl InputProfile { diff --git a/crates/texrra-tex-core/src/execution/job.rs b/crates/texrra-tex-core/src/execution/job.rs index 071ead1..0c5fc3e 100644 --- a/crates/texrra-tex-core/src/execution/job.rs +++ b/crates/texrra-tex-core/src/execution/job.rs @@ -325,6 +325,10 @@ impl OutputNode { #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub(super) struct InputStream { pub source: usize, + #[serde(default)] + pub xe_encoding: Option, + #[serde(default)] + pub xe_skip_lf: bool, } /// Logical stream metadata only. Live host handles are NOT serialized. A diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index b47ed24..3e4a8fa 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -18,6 +18,8 @@ pub use format_image::FormatImage; mod hooks; mod hyphenation; mod input_profile; +mod xe_encoding; +pub use xe_encoding::XeLineFraming; mod insertions; mod job; mod ligature; @@ -368,6 +370,20 @@ pub trait SourceProvider { fn read_line(&mut self, _stream: u8) -> Result>, String> { Err("host input streams unavailable".into()) } + /// Return original bytes through one delimiter of the requested framing. + /// Hosts with byte-framed streams can retain the existing UTF-8 path. + fn read_xe_line(&mut self, stream: u8, framing: XeLineFraming) -> Result>, String> { + if matches!(framing, XeLineFraming::Utf16Le | XeLineFraming::Utf16Be) { + return Err("host UTF-16 input streams unavailable".into()); + } + let bytes = self.read_line(stream)?; + if framing == XeLineFraming::Auto + && bytes.as_deref().is_some_and(|data| XeLineFraming::detect(data).0.unit_width() == 2) + { + return Err("host UTF-16 input streams unavailable".into()); + } + Ok(bytes) + } fn close_in(&mut self, _stream: u8) -> Result<(), String> { Err("host input streams unavailable".into()) } @@ -459,6 +475,7 @@ pub enum Dependency { value: Option, }, InputStream(u8), + XeDefaultInputEncoding, InputPosition(usize), OutputStream(u8), ParagraphToken, diff --git a/crates/texrra-tex-core/src/execution/mouth.rs b/crates/texrra-tex-core/src/execution/mouth.rs index 5288267..f7f5f86 100644 --- a/crates/texrra-tex-core/src/execution/mouth.rs +++ b/crates/texrra-tex-core/src/execution/mouth.rs @@ -1,11 +1,15 @@ use super::{CatCode, CommandName, Dependency, Span, State, Token, TokenKind}; use std::collections::BTreeSet; -#[derive(Clone, Copy)] -struct Character { - value: char, - start: usize, - end: usize, +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)] @@ -184,6 +188,36 @@ mod tests { } } + #[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"); @@ -224,6 +258,8 @@ pub(super) struct Mouth { end_after_line: bool, line_breaks: LineBreaks, line_number: usize, + xe: Option, + invalid_utf8: Vec<(usize, usize)>, } impl Mouth { @@ -236,6 +272,11 @@ impl Mouth { 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() { @@ -253,17 +294,41 @@ impl Mouth { 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, profile, - offset: 0, + 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( @@ -274,6 +339,8 @@ impl Mouth { ) -> 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 { @@ -291,6 +358,24 @@ impl Mouth { 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(|| (self.line_number, 1 + self.line.partition_point(|c| c.end <= offset && c.start < offset))) + } + + 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 } @@ -322,6 +407,9 @@ impl Mouth { 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..]; @@ -399,6 +487,57 @@ impl Mouth { )); } }; + 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 (mut chars, invalid_utf8) = xe.encoding.decode(&self.data[start..content_end], start) + .map_err(|message| (Span { source: self.source, start, end: content_end }, message))?; + while chars.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) { + chars.pop(); + } + self.line = chars; + 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 @@ -412,7 +551,6 @@ impl Mouth { } self.cursor = 0; self.state = LineState::New; - Ok(true) } fn catcode(state: &State, reads: &mut BTreeSet, c: char) -> CatCode { reads.insert(Dependency::CatCode(c)); diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 6998b5f..72eb3dc 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -385,6 +385,8 @@ pub enum Primitive { EndL, BeginR, EndR, + XeTeXinputencoding, + XeTeXdefaultencoding, } impl Primitive { @@ -698,6 +700,8 @@ pub struct State { initex: bool, #[serde(default)] input_profile: super::InputProfile, + #[serde(default)] + pub(super) xe_default_encoding: super::xe_encoding::Encoding, pub endlinechar: i32, pub newlinechar: i32, pub escapechar: i32, @@ -905,6 +909,7 @@ impl Default for State { pdftex_revision: PdftexRevision::R24, initex: false, input_profile: super::InputProfile::default(), + xe_default_encoding: super::xe_encoding::Encoding::Auto, endlinechar: 13, newlinechar: -1, escapechar: 92, @@ -1702,6 +1707,8 @@ impl State { ("XeTeXpdffile", Primitive::XeTeXpdffile), ("XeTeXpicfile", Primitive::XeTeXpicfile), ("XeTeXpdfpagecount", Primitive::XeTeXpdfpagecount), + ("XeTeXinputencoding", Primitive::XeTeXinputencoding), + ("XeTeXdefaultencoding", Primitive::XeTeXdefaultencoding), ] { self.update_profile_command(name, Meaning::Primitive(primitive), enabled); } diff --git a/crates/texrra-tex-core/src/execution/xe_encoding.rs b/crates/texrra-tex-core/src/execution/xe_encoding.rs new file mode 100644 index 0000000..e1dc3eb --- /dev/null +++ b/crates/texrra-tex-core/src/execution/xe_encoding.rs @@ -0,0 +1,207 @@ +//! XeTeX physical input encodings. Decoded units retain their source bytes. +use std::sync::Arc; + +mod icu; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub(super) enum Encoding { + #[default] + Auto, + Utf8, + Bytes, + Utf16Le, + Utf16Be, + Legacy(Arc), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum XeLineFraming { + Bytes, + Utf16Le, + Utf16Be, + Auto, +} + +impl XeLineFraming { + pub fn detect(data: &[u8]) -> (Self, usize) { + match data { + [0xfe, 0xff, ..] => (Self::Utf16Be, 2), + [0xff, 0xfe, ..] => (Self::Utf16Le, 2), + [0, n, ..] if *n != 0 => (Self::Utf16Be, 0), + [n, 0, ..] if *n != 0 => (Self::Utf16Le, 0), + [0xef, 0xbb, 0xbf, ..] => (Self::Bytes, 3), + _ => (Self::Bytes, 0), + } + } + + pub fn unit_width(self) -> usize { + match self { + Self::Utf16Be | Self::Utf16Le => 2, + Self::Bytes | Self::Auto => 1, + } + } + + pub fn code_unit(self, data: &[u8]) -> Option { + match self { + Self::Utf16Le => Some(u16::from_le_bytes(data.get(..2)?.try_into().unwrap())), + Self::Utf16Be => Some(u16::from_be_bytes(data.get(..2)?.try_into().unwrap())), + Self::Bytes | Self::Auto => data.first().map(|b| u16::from(*b)), + } + } + + pub fn line_boundary(self, data: &[u8]) -> (usize, Option) { + let width = self.unit_width(); + for (index, unit) in data.chunks_exact(width).enumerate() { + let code = self.code_unit(unit).unwrap(); + if matches!(code, 10 | 13) { + return (index * width, Some(code)); + } + } + (data.len(), None) + } +} + +#[derive(Clone, Copy)] +pub(super) struct Character { + pub value: char, + pub start: usize, + pub end: usize, +} + +impl Encoding { + pub fn parse(name: &str) -> Result, String> { + let builtin = match name.to_ascii_lowercase().as_str() { + "auto" => Self::Auto, + "utf8" => Self::Utf8, + "utf16" if cfg!(target_endian = "little") => Self::Utf16Le, + "utf16" | "utf16be" => Self::Utf16Be, + "utf16le" => Self::Utf16Le, + "bytes" => Self::Bytes, + _ => { + return Ok(icu::recognizes(name)?.then(|| Self::Legacy(Arc::from(name)))); + } + }; + Ok(Some(builtin)) + } + + pub fn framing(&self) -> XeLineFraming { + match self { + Self::Auto => XeLineFraming::Auto, + Self::Utf16Le => XeLineFraming::Utf16Le, + Self::Utf16Be => XeLineFraming::Utf16Be, + _ => XeLineFraming::Bytes, + } + } + + pub fn resolve(&self, data: &[u8]) -> (Self, usize) { + if *self != Self::Auto { + return (self.clone(), 0); + } + let (framing, bom) = XeLineFraming::detect(data); + let encoding = match framing { + XeLineFraming::Utf16Le => Self::Utf16Le, + XeLineFraming::Utf16Be => Self::Utf16Be, + _ => Self::Utf8, + }; + (encoding, bom) + } + + pub fn decode(&self, data: &[u8], base: usize) -> Result<(Vec, usize), String> { + let mut invalid_utf8 = 0; + let chars = match self { + Self::Auto => unreachable!("resolve the encoding at file open"), + Self::Utf8 => { + if let Ok(str) = std::str::from_utf8(data) { + str.char_indices() + .map(|(i, value)| Character { + value, + start: base + i, + end: base + i + value.len_utf8(), + }) + .collect() + } else { + let mut chars = Vec::new(); + let mut at = 0; + while at < data.len() { + let (value, length, bad) = decode_utf8_character(&data[at..]); + invalid_utf8 += usize::from(bad); + chars.push(Character { + value, + start: base + at, + end: base + at + length, + }); + at += length; + } + chars + } + } + Self::Bytes => data + .iter() + .enumerate() + .map(|(i, byte)| Character { + value: char::from(*byte), + start: base + i, + end: base + i + 1, + }) + .collect(), + Self::Utf16Le | Self::Utf16Be => { + let framing = self.framing(); + let mut chars = Vec::new(); + let mut at = 0; + while let Some(first) = framing.code_unit(&data[at..]) { + let second = framing.code_unit(&data[at + 2..]); + let (value, units) = utf16_character(first, second); + let end = at + 2 * units; + chars.push(Character { + value, + start: base + at, + end: base + end, + }); + at = end; + } + if at < data.len() { + chars.push(Character { + value: char::REPLACEMENT_CHARACTER, + start: base + at, + end: base + data.len(), + }); + } + chars + } + Self::Legacy(name) => icu::decode(name, data, base)?, + }; + Ok((chars, invalid_utf8)) + } +} + +fn decode_utf8_character(input: &[u8]) -> (char, usize, bool) { + let first = input[0]; + let (mut value, continuation) = match first { + 0x00..=0xbf => return (char::from(first), 1, false), + 0xc0..=0xdf => (u32::from(first & 0x1f), 1), + 0xe0..=0xef => (u32::from(first & 0x0f), 2), + 0xf0..=0xf7 => (u32::from(first & 0x07), 3), + _ => return (char::REPLACEMENT_CHARACTER, 1, true), + }; + for at in 1..=continuation { + let Some(&b @ 0x80..=0xbf) = input.get(at) else { + return (char::REPLACEMENT_CHARACTER, at, true); + }; + value = (value << 6) | u32::from(b & 0x3f); + } + match char::from_u32(value) { + Some(c) => (c, continuation + 1, false), + None => (char::REPLACEMENT_CHARACTER, continuation + 1, true), + } +} + +fn utf16_character(first: u16, second: Option) -> (char, usize) { + if let (0xd800..=0xdbff, Some(low @ 0xdc00..=0xdfff)) = (first, second) { + let value = 0x10000 + ((u32::from(first) - 0xd800) << 10) + u32::from(low) - 0xdc00; + return (char::from_u32(value).unwrap(), 2); + } + ( + char::from_u32(u32::from(first)).unwrap_or(char::REPLACEMENT_CHARACTER), + 1, + ) +} diff --git a/crates/texrra-tex-core/src/execution/xe_encoding/icu.rs b/crates/texrra-tex-core/src/execution/xe_encoding/icu.rs new file mode 100644 index 0000000..fe54844 --- /dev/null +++ b/crates/texrra-tex-core/src/execution/xe_encoding/icu.rs @@ -0,0 +1,192 @@ +//! The ICU converter used by XeTeX for non-built-in encoding names. +use super::{Character, utf16_character}; +use libloading::Library; +use std::{ + ffi::{CString, c_char, c_void}, + sync::OnceLock, +}; + +type Open = unsafe extern "C" fn(*const c_char, *mut i32) -> *mut c_void; +type Close = unsafe extern "C" fn(*mut c_void); +type ToUnicode = unsafe extern "C" fn( + *mut c_void, + *mut *mut u16, + *const u16, + *mut *const c_char, + *const c_char, + *mut i32, + i8, + *mut i32, +); + +struct Icu { + open: Open, + close: Close, + to_unicode: ToUnicode, + _library: Library, +} + +fn library() -> Result<&'static Icu, String> { + static ICU: OnceLock> = OnceLock::new(); + ICU.get_or_init(load) + .as_ref() + .ok_or_else(|| "XeTeX legacy input encodings require an ICU4C runtime".into()) +} + +fn load() -> Option { + #[cfg(target_os = "windows")] + let unversioned = ["icu.dll", "icuuc.dll"]; + #[cfg(target_os = "macos")] + let unversioned = ["libicucore.dylib", "libicuuc.dylib"]; + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + let unversioned = ["libicuuc.so"]; + let versions = (50..=100).rev(); + // Only the platform loader's library search path is used, never the input + // directory or the encoding name supplied by a document. + for name in unversioned + .into_iter() + .map(str::to_owned) + .chain(versions.clone().map(|v| { + if cfg!(target_os = "windows") { + format!("icuuc{v}.dll") + } else if cfg!(target_os = "macos") { + format!("libicuuc.{v}.dylib") + } else { + format!("libicuuc.so.{v}") + } + })) + { + #[cfg(target_os = "windows")] + let loaded = unsafe { + // LOAD_LIBRARY_SEARCH_DEFAULT_DIRS excludes a document's cwd. + libloading::os::windows::Library::load_with_flags(name, 0x0000_1000).map(Library::from) + }; + #[cfg(not(target_os = "windows"))] + let loaded = unsafe { Library::new(name) }; + let Ok(lib) = loaded else { continue }; + for suffix in + std::iter::once(String::new()).chain(versions.clone().map(|v| format!("_{v}"))) + { + // ICU4C ships these declarations as stable C ABI. All three must + // come from this same library and use the same export suffix. + let symbols = unsafe { + ( + lib.get::(format!("ucnv_open{suffix}").as_bytes()), + lib.get::(format!("ucnv_close{suffix}").as_bytes()), + lib.get::(format!("ucnv_toUnicode{suffix}").as_bytes()), + ) + }; + if let (Ok(open), Ok(close), Ok(to_unicode)) = symbols { + return Some(Icu { + open: *open, + close: *close, + to_unicode: *to_unicode, + _library: lib, + }); + } + } + } + None +} + +struct Converter { + icu: &'static Icu, + value: *mut c_void, +} + +impl Converter { + fn new(name: &str) -> Result, String> { + let Ok(name) = CString::new(name) else { + return Ok(None); + }; + let icu = library()?; + let mut status = 0; + // name has a C terminator and only lives for this call. + let value = unsafe { (icu.open)(name.as_ptr(), &mut status) }; + Ok((!value.is_null()).then(|| Self { icu, value })) + } +} + +impl Drop for Converter { + fn drop(&mut self) { + // Each converter belongs to a single line conversion. + unsafe { (self.icu.close)(self.value) }; + } +} + +pub(super) fn recognizes(name: &str) -> Result { + Converter::new(name).map(|converter| converter.is_some()) +} + +pub(super) fn decode(name: &str, data: &[u8], base: usize) -> Result, String> { + if data.is_empty() { + return Ok(Vec::new()); + } + let mut capacity = data.len().saturating_add(4); + let (units, offsets) = loop { + if capacity > i32::MAX as usize { + return Err("XeTeX legacy input line is too long".into()); + } + let converter = Converter::new(name)? + .ok_or_else(|| format!("ICU converter for {name} is unavailable"))?; + let mut units = vec![0u16; capacity]; + let mut offsets = vec![0; capacity]; + let target = units.as_mut_ptr(); + let source = data.as_ptr().cast::(); + let (mut end, mut read, mut status) = (target, source, 0); + // Both limits point one past allocated buffers. ICU writes one offset + // per UTF-16 unit and advances end and read within those buffers. + let count = unsafe { + (converter.icu.to_unicode)( + converter.value, + &mut end, + target.add(capacity), + &mut read, + source.add(data.len()), + offsets.as_mut_ptr(), + 1, + &mut status, + ); + end.offset_from(target) as usize + }; + if status == 15 { + // U_BUFFER_OVERFLOW_ERROR + capacity *= 2; + continue; + } + if status > 0 { + return Err(format!( + "Unicode conversion failed (ICU error code = {status})" + )); + } + units.truncate(count); + offsets.truncate(count); + break (units, offsets); + }; + let mut chars = Vec::new(); + let mut index = 0; + let mut start = 0; + let mut next_distinct = 0; + while index < units.len() { + let (value, width) = utf16_character(units[index], units.get(index + 1).copied()); + if let Ok(offset) = usize::try_from(offsets[index]) { + start = offset.min(data.len()); + } + next_distinct = next_distinct.max(index + width); + while next_distinct < offsets.len() + && !usize::try_from(offsets[next_distinct]).is_ok_and(|offset| offset > start) + { + next_distinct += 1; + } + let end = offsets + .get(next_distinct) + .map_or(data.len(), |&offset| (offset as usize).min(data.len())); + chars.push(Character { + value, + start: base + start, + end: base + end, + }); + index += width; + } + Ok(chars) +} diff --git a/crates/texrra-tex-core/tests/execution_xetex_profile.rs b/crates/texrra-tex-core/tests/execution_xetex_profile.rs index 0f6fe4f..2f7cf26 100644 --- a/crates/texrra-tex-core/tests/execution_xetex_profile.rs +++ b/crates/texrra-tex-core/tests/execution_xetex_profile.rs @@ -274,3 +274,40 @@ fn xetex_formats_and_paints_nested_direction_spans() { .unwrap_err(); assert!(error.message.contains(r"Improper \beginR")); } + +#[test] +fn xetex_default_encoding_survives_dump_and_current_line_is_already_decoded() { + let state = State::initex().with_input_profile(InputProfile::XeTeX).with_etex(); + let mut data = br"\catcode123=1 \catcode125=2".to_vec(); + data.extend_from_slice("\n\\XeTeXinputencoding \"bytes\" \\message{\\number`é}\n".as_bytes()); + data.extend_from_slice(b"\\message{\\number`\xe9}\n"); + data.extend_from_slice(br#"{\XeTeXdefaultencoding "utf16be"}\dump"#); + let execution = Executor::new(state, Limits::default()) + .run(SourceFile { name: "seed.tex".into(), data: data.clone() }, &mut NoFiles) + .unwrap(); + assert_eq!(messages(&execution), ["233", "233"]); + let bytes = FormatImage::from_dump(execution, Vec::new(), Vec::new()) + .unwrap().encode().unwrap(); + let job = FormatImage::decode(&bytes).unwrap() + .new_job( + Profile::EtexBootstrap, + InputProfile::XeTeX, + JobTime::new(2025, 10, 9, 0).unwrap(), + Limits::default(), + |_| Ok(data.clone()), + ) + .unwrap(); + let input = r"\def\word{😀}\message{\word}\end"; + // A UTF-16 source without a BOM must follow the stored mode. + let data = input.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let result = job.run(SourceFile { name: "next.tex".into(), data: data.clone() }, &mut NoFiles) + .unwrap(); + assert_eq!(messages(&result), ["😀"]); + let Meaning::Macro(word) = result.state.meaning(&CommandName::Control("word".into())) else { + panic!("expected the real definition"); + }; + let [Replacement::Token(token)] = word.replacement.as_slice() else { + panic!("expected one scalar token"); + }; + assert_eq!(&data[token.span.start..token.span.end], [0xd8, 0x3d, 0xde, 0x00]); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index f1d1a86..63fe0a1 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,44 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### XeTeX 逐文件输入编码与原始字节位置 + +`\XeTeXinputencoding` 切换当前物理文件之后的行,每行按读入时的编码 +保留字符和原始字节区间。`\XeTeXdefaultencoding` 设置后续输入和 +读取流的默认编码。自动模式识别 UTF-8、UTF-16 的 BOM 和 UTF-16 +首码元特征。UTF-16 流按码元读取实际文件,CR 后的 LF 在下一次取行时 +处理。传统编码进入真正的 ICU4C 转换器,UTF-8 和 UTF-16 自带编解码 +路径。传统编码依赖宿主 ICU4C。此次验证采用 Fedora 提取的 ICU 77, +Windows 和 macOS 的运行路径待在对应系统验证。 +[XeTeX 上游编码选择](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeX_ext.c#L497-L543) +[ICU 映射与源偏移接口](https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/ucnv_8h.html) + +同一源的对照覆盖原始字节、BOM、UTF-16BE/LE、Shift_JIS、 +Latin-1 与 Windows-1252。两个告警逐字一致。UTF-16 失败标出真实第 +3 行,UTF-16 读取流四段原始字节的偏移、长度和摘要闭合。schema69 +保存后来打开的文件所用的默认编码,真实小格式重载后输出。 +15 项输入和 profile 定向检查通过。 + +UTF-16 三页项目的第二页编辑中,恢复已读取的编码与真实流状态, +复用 197 步、重放 9 次宿主调用,只替换第二页。PDF、SVG、来源映射 +与辅助文件和独立全量一致。字形指向第 26374 至 26376 字节的半开 +区间。首轮从生成文件不存在到存在的前置角色变化触发保守失效,保留 +原诊断;用正常首次编译建立辅助文件后通过续编对照。 + +未改动的发行版 `xelatex.ini` 成功转储 schema69,旧 schema68 +也实际加载并输出单页。原样 ACL 已越过 Babel 的编码检测,停在 +`xebabel.def:282:7` 的 `\xe@alloc@intercharclass`。同发行版 +LaTeX 在格式生成时用 `\XeTeXcharclass` 判断是否初始化分配器。 +下一步将字符类别、成对 token 列表与启用参数接入通用状态和字体 +文字运行边界,再由真实内核生成其分配器。已保留 XeTeX 最小对照, +涵盖关闭和开启时的盒宽、忽略类、显式 `\char`、分组恢复及全局赋值。 +[LaTeX 分配器的格式初始化](https://github.com/latex3/latex2e/blob/develop/base/ltfinal.dtx#L206-L251) +[XeTeX 字符运行中的 token 插入](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L22427-L22469) + +回执 `target/p3-xetex-input-encoding/receipt.json` 的 SHA-256 为 +`8d1a4cfab4f9e9f75b453fb0063d3b12f299d207ae95da0f1516291796cbb6fd`。 +同目录保留新旧格式证据、原样 ACL 诊断及 `interchar-reference`。 + ### TeX--XeT 水平列表方向与 ACL Unicode 样稿 pdfTeX 和 XeTeX 的扩展 profile 执行 `\TeXXeTstate`、`\beginL`、 diff --git a/docs/PUBLISHER_TEMPLATE_MATRIX.md b/docs/PUBLISHER_TEMPLATE_MATRIX.md index b2e7937..a01c946 100644 --- a/docs/PUBLISHER_TEMPLATE_MATRIX.md +++ b/docs/PUBLISHER_TEMPLATE_MATRIX.md @@ -701,6 +701,13 @@ Noto Sans Arabic 及冻结 Type 1 映射。几次缺包和字体名称探测的 原生诊断见 `target/p3-xetex-acl`。 [阶段记录](P2_M1_PROGRESS.md#tex--xet-水平列表方向与-acl-unicode-样稿) +逐文件编码接入后,同一官方归档和冻结资源以未改动的 `xelatex.ini` +重新转储 schema69。原样 ACL 已执行到 `xebabel.def:282:7`, +首次停止于 `\xe@alloc@intercharclass`,尚未生成 PDF。格式生成时 +缺少 `\XeTeXcharclass`,LaTeX 因此跳过该分配器的初始化。保留 +原样输入摘要、格式摘要及新诊断 `target/p3-xetex-input-encoding/receipt.json`。 +[编码阶段记录](P2_M1_PROGRESS.md#xetex-逐文件输入编码与原始字节位置) + ### 原样 Elsevier CAS 双栏与 NeurIPS 2025 以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。 diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index b7e449e..55b86b4 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -232,6 +232,13 @@ impl SourceProvider for RecordingHost<'_> { fn read_line(&mut self, stream: u8) -> Result>, String> { call!(self, read_line(stream)) } + fn read_xe_line( + &mut self, + stream: u8, + framing: texrra_tex_core::execution::XeLineFraming, + ) -> Result>, String> { + call!(self, read_xe_line(stream, framing)) + } fn close_in(&mut self, stream: u8) -> Result<(), String> { call!(self, close_in(stream)) } diff --git a/src/native_job.rs b/src/native_job.rs index 61b7581..684d7f3 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -112,6 +112,7 @@ struct Input { reader: Box, path: PathBuf, offset: u64, + xe_lookahead: std::collections::VecDeque, } struct Output { handle: u64, @@ -1424,6 +1425,67 @@ pub(crate) fn absolute_output(cwd: &Path, path: &Path) -> Result, + ) -> Result>, String> { + let Some(input) = self.inputs.get_mut(&stream) else { + let error = "host input stream is not open".to_owned(); + self.stream_io.push(StreamEffect::ReadLine { + stream, + handle: None, + consumed_before: None, + consumed: std::sync::Arc::from([]), + observed_eof: false, + delivered: false, + error: Some(error.clone()), + }); + return Err(error); + }; + let before = input.offset; + let transfer = match framing { + Some(framing) => native_stream::xe_physical_line( + input.reader.as_mut(), &mut input.xe_lookahead, framing, + ), + None => native_stream::physical_line(input.reader.as_mut()), + }; + input.offset += transfer.bytes.len() as u64; + let error = transfer.error.map(|e| format!("read stream {stream}: {e}")); + self.stream_io.push(StreamEffect::ReadLine { + stream, + handle: Some(input.handle), + consumed_before: Some(before), + consumed: std::sync::Arc::from(transfer.bytes.clone()), + observed_eof: transfer.observed_eof, + delivered: error.is_none(), + error: error.clone(), + }); + if let Some(error) = error { + self.world.observe_read_error(&input.path, error.clone()); + Err(error) + } else { + let line = (!transfer.bytes.is_empty()).then_some(transfer.bytes); + self.world.observe_stream_read(&input.path, before, line.as_deref()); + if framing == Some(texrra_tex_core::execution::XeLineFraming::Auto) { + // The detection may have inspected bytes in the following + // line. Validate those bytes without advancing delivered I/O. + let peeked = input.xe_lookahead.make_contiguous(); + if !peeked.is_empty() { + self.world.observe_stream_read(&input.path, input.offset, Some(peeked)); + } + if transfer.observed_eof && line.is_some() { + self.world.observe_stream_read( + &input.path, input.offset + peeked.len() as u64, None, + ); + } + } + Ok(line) + } + } +} + impl SourceProvider for Files { #[cfg(all(target_os = "linux", target_env = "gnu"))] fn match_pdf_regex( @@ -1647,6 +1709,7 @@ impl SourceProvider for Files { reader, path, offset: 0, + xe_lookahead: Default::default(), }, ); Ok(Some(opened)) @@ -1660,41 +1723,14 @@ impl SourceProvider for Files { result.map(|opened| opened.map(|o| o.path.display().to_string())) } fn read_line(&mut self, stream: u8) -> Result>, String> { - let Some(input) = self.inputs.get_mut(&stream) else { - let error = "host input stream is not open".to_owned(); - self.stream_io.push(StreamEffect::ReadLine { - stream, - handle: None, - consumed_before: None, - consumed: std::sync::Arc::from([]), - observed_eof: false, - delivered: false, - error: Some(error.clone()), - }); - return Err(error); - }; - let before = input.offset; - let transfer = native_stream::physical_line(input.reader.as_mut()); - input.offset += transfer.bytes.len() as u64; - let error = transfer.error.map(|e| format!("read stream {stream}: {e}")); - self.stream_io.push(StreamEffect::ReadLine { - stream, - handle: Some(input.handle), - consumed_before: Some(before), - consumed: std::sync::Arc::from(transfer.bytes.clone()), - observed_eof: transfer.observed_eof, - delivered: error.is_none(), - error: error.clone(), - }); - if let Some(error) = error { - self.world.observe_read_error(&input.path, error.clone()); - Err(error) - } else { - let line = (!transfer.bytes.is_empty()).then_some(transfer.bytes); - self.world - .observe_stream_read(&input.path, before, line.as_deref()); - Ok(line) - } + self.read_input_line(stream, None) + } + fn read_xe_line( + &mut self, + stream: u8, + framing: texrra_tex_core::execution::XeLineFraming, + ) -> Result>, String> { + self.read_input_line(stream, Some(framing)) } fn close_in(&mut self, stream: u8) -> Result<(), String> { self.release_input(stream, ReleaseCause::Explicit, true); @@ -2562,6 +2598,7 @@ mod generated_file_tests { handle, path: root.join("actual-stream"), offset: 0, + xe_lookahead: Default::default(), reader: Box::new(BufReader::new(reader)), }, ); diff --git a/src/native_stream.rs b/src/native_stream.rs index 85ec6c5..38f0e10 100644 --- a/src/native_stream.rs +++ b/src/native_stream.rs @@ -2,12 +2,13 @@ //! by this handle, not an OS descriptor cursor hidden behind BufReader. This //! journal does not serialize read-ahead buffers or authorize effect replay. use std::{ + collections::VecDeque, fs::File, io::{self, BufRead, Write}, path::PathBuf, sync::Arc, }; -use texrra_tex_core::resources::ResourceVersion; +use texrra_tex_core::{execution::XeLineFraming, resources::ResourceVersion}; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct DescriptorIdentity { @@ -208,6 +209,76 @@ pub(crate) fn physical_line(reader: &mut (impl BufRead + ?Sized)) -> LineTransfe error: result.err(), } } +/// One XeTeX physical delimiter. Bytes read for BOM detection that belong to +/// a later line stay in this handle's lookahead until that line is delivered. +pub(crate) fn xe_physical_line( + reader: &mut (impl BufRead + ?Sized), + pending: &mut VecDeque, + mut framing: XeLineFraming, +) -> LineTransfer { + let mut bytes = Vec::new(); + let mut observed_eof = false; + let result = (|| -> io::Result<()> { + if framing == XeLineFraming::Auto { + while pending.len() < 3 { + let buffer = reader.fill_buf()?; + if buffer.is_empty() { + observed_eof = true; + break; + } + let count = (3 - pending.len()).min(buffer.len()); + pending.extend(&buffer[..count]); + reader.consume(count); + } + let (detected, bom) = XeLineFraming::detect(pending.make_contiguous()); + framing = detected; + bytes.extend(pending.drain(..bom)); + } + let width = framing.unit_width(); + loop { + if width == 1 && pending.is_empty() { + let buffer = reader.fill_buf()?; + if buffer.is_empty() { + observed_eof = true; + break; + } + let terminator = buffer.iter().position(|&byte| matches!(byte, b'\r' | b'\n')); + let count = terminator.map_or(buffer.len(), |at| at + 1); + bytes.extend_from_slice(&buffer[..count]); + reader.consume(count); + if terminator.is_some() { + break; + } + continue; + } + let start = bytes.len(); + while bytes.len() - start < width { + if let Some(byte) = pending.pop_front() { + bytes.push(byte); + continue; + } + let buffer = reader.fill_buf()?; + if buffer.is_empty() { + observed_eof = true; + return Ok(()); + } + let count = (width - (bytes.len() - start)).min(buffer.len()); + bytes.extend_from_slice(&buffer[..count]); + reader.consume(count); + } + if matches!(framing.code_unit(&bytes[start..]), Some(10 | 13)) { + break; + } + } + Ok(()) + })(); + LineTransfer { + bytes, + observed_eof, + error: result.err(), + } +} + pub(crate) struct WriteTransfer { pub accepted: usize, pub attempts: Vec,