From bf42a88dff3f3dc4a56a347dcb5b53173b90e5fd Mon Sep 17 00:00:00 2001 From: GloamXun Date: Wed, 2 Dec 2026 00:22:21 +0800 Subject: [PATCH] Reuse XeTeX suffixes across physical line edits --- .../src/execution/engine/continuation.rs | 7 +- crates/texrra-tex-core/src/execution/mouth.rs | 128 +++++++++-- .../src/execution/source_relocation.rs | 201 ++++++++++++++---- docs/P2_M1_PROGRESS.md | 20 ++ tests/native_pipeline.rs | 54 +++-- 5 files changed, 337 insertions(+), 73 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index d3de888..381969e 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -184,7 +184,8 @@ impl EntryCheckpoint { .then_some((previous_bytes.len(), current_bytes.len())); let relocation = match entry_sizes { Some(_) => { - let map = SourceRelocation::new(self.entry, previous_bytes, current_bytes)?; + let map = self.source_mouth(self.entry) + .relocation_from(prior.source_mouth(prior.entry))?; if map.relocate_offset(prior.frontier) != Some(self.frontier) { return None; } @@ -199,11 +200,13 @@ impl EntryCheckpoint { if observes_entry_line && relocation.as_ref().map_or_else( || !SourceRelocation::same_line_breaks(previous_bytes, current_bytes), - SourceRelocation::changes_line_numbers, + |map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1, ) { // The old line number can be embedded in outputs. Equal byte // offsets can also mean different lines if a newline moved. + // In wide encodings even a same-line edit can change the number + // of raw CR/LF bytes counted by byte-based diagnostic fallbacks. return None; } let line_observations = match &completed.line_observations { diff --git a/crates/texrra-tex-core/src/execution/mouth.rs b/crates/texrra-tex-core/src/execution/mouth.rs index b1d2a04..d62c7e8 100644 --- a/crates/texrra-tex-core/src/execution/mouth.rs +++ b/crates/texrra-tex-core/src/execution/mouth.rs @@ -3,13 +3,16 @@ use std::sync::Arc; use super::{ source_relocation::SourceRelocation, - xe_encoding::{Character, Encoding}, + xe_encoding::{Character, Encoding, XeLineFraming}, }; #[derive(Clone, PartialEq, Eq)] struct XePhysical { encoding: Encoding, autodetected: Option<(Encoding, usize)>, + // A decoder can change without changing which code units end a line. + // Once framing varies, the prefix cannot be counted in one mode. + framing_history: Option, skip_lf: bool, terminated: bool, line_start: usize, @@ -303,16 +306,85 @@ mod tests { assert!(old.load_line(&state, &mut reads).unwrap()); assert!(current.load_line(&state, &mut reads).unwrap()); assert!(!current.same_unread_input_relocated(&old, &insert)); + if profile == InputProfile::XeTeX { + assert!(old.change_encoding(Encoding::Bytes)); + assert!(current.change_encoding(Encoding::Bytes)); + } assert!(old.load_line(&state, &mut reads).unwrap()); assert!(current.load_line(&state, &mut reads).unwrap()); assert!(!current.same_unread_input_relocated(&old, &insert)); assert!(current.load_line(&state, &mut reads).unwrap()); - let supported = profile != InputProfile::XeTeX; - assert_eq!(current.same_unread_input_relocated(&old, &insert), supported); - assert_eq!(old.same_unread_input_relocated(¤t, &delete), supported); + assert!(current.same_unread_input_relocated(&old, &insert)); + assert!(old.same_unread_input_relocated(¤t, &delete)); } } + #[test] + fn relocated_xetex_lines_use_the_loaded_utf16_framing() { + use super::super::InputProfile; + let state = State::default().with_input_profile(InputProfile::XeTeX); + for (bom, encode) in [ + ([0xff, 0xfe], u16::to_le_bytes as fn(u16) -> [u8; 2]), + ([0xfe, 0xff], u16::to_be_bytes), + ] { + let physical = |text: &str| { + bom.into_iter().chain(text.encode_utf16().flat_map(encode)).collect() + }; + let mut previous = Mouth::new( + 4, physical("cover\r\n\u{010a} next"), InputProfile::XeTeX, + ); + let mut current = Mouth::new( + 4, physical("cover\r\n% note\r\n\u{010a} next"), InputProfile::XeTeX, + ); + let mut reads = DependencyReads::default(); + for _ in 0..2 { + assert!(previous.load_line(&state, &mut reads).unwrap()); + assert!(current.load_line(&state, &mut reads).unwrap()); + } + let insert = current.relocation_from(&previous).unwrap(); + assert!(!current.same_unread_input_relocated(&previous, &insert)); + assert!(current.load_line(&state, &mut reads).unwrap()); + assert!(current.same_unread_input_relocated(&previous, &insert)); + + let delete = previous.relocation_from(¤t).unwrap(); + assert!(previous.same_unread_input_relocated(¤t, &delete)); + } + } + + #[test] + fn a_matching_current_decoder_cannot_prove_a_mixed_prefix() { + use super::super::InputProfile; + let source = |comment: &[u8]| { + b"head\n".iter().copied() + .chain("\u{050a}\n".encode_utf16().flat_map(u16::to_le_bytes)) + .chain(b"before\n".iter().copied()) + .chain(comment.iter().copied()) + .chain(b"entry\nanchor\nend\n".iter().copied()) + .collect::>() + }; + let previous = source(b""); + let current = source(b"% note\n"); + let raw_map = SourceRelocation::new(4, &previous, ¤t).unwrap(); + let mut previous = Mouth::new(4, previous, InputProfile::XeTeX); + let mut current = Mouth::new(4, current, InputProfile::XeTeX); + let state = State::default().with_input_profile(InputProfile::XeTeX); + let mut reads = DependencyReads::default(); + for mouth in [&mut previous, &mut current] { + assert!(mouth.load_line(&state, &mut reads).unwrap()); + assert!(mouth.change_encoding(Encoding::Utf16Le)); + assert!(mouth.load_line(&state, &mut reads).unwrap()); + assert!(mouth.change_encoding(Encoding::Utf8)); + for _ in 0..3 { + assert!(mouth.load_line(&state, &mut reads).unwrap()); + } + } + assert!(current.load_line(&state, &mut reads).unwrap()); + assert_eq!(raw_map.relocate_line(previous.line_number), Some(current.line_number)); + assert_eq!(raw_map.relocate_offset(previous.offset), Some(current.offset)); + assert!(current.relocation_from(&previous).is_none()); + assert!(!current.same_unread_input_relocated(&previous, &raw_map)); + } + #[test] fn physical_line_endings_and_utf8_byte_offsets_are_preserved() { let result = tokens("é界 \r\nB\rC"); @@ -377,6 +449,33 @@ impl Mouth { && self.data[self.offset..] == other.data[other.offset..] } + pub(super) fn relocation_from(&self, old: &Self) -> Option { + let (framing, content_start) = self.physical_framing()?; + if self.source != old.source || old.physical_framing() != Some((framing, content_start)) { + return None; + } + if framing == XeLineFraming::Bytes && content_start == 0 { + SourceRelocation::new(self.source, &old.data, &self.data) + } else { + SourceRelocation::with_framing( + self.source, &old.data, &self.data, framing, content_start, + ) + } + } + + fn physical_framing(&self) -> Option<(XeLineFraming, usize)> { + if !matches!(self.line_breaks, LineBreaks::Physical) { + return None; + } + match &self.xe { + Some(xe) => Some(( + xe.framing_history?, + xe.autodetected.as_ref().map_or(0, |(_, bom)| *bom), + )), + None => Some((XeLineFraming::Bytes, 0)), + } + } + pub(super) fn same_unread_input_relocated( &self, old: &Self, @@ -384,10 +483,8 @@ impl Mouth { ) -> bool { if self.source != relocation.source() || !self.same_unread_state(old) - // XeTeX can change physical framing within a file. Matching the - // current decoder is insufficient to prove earlier line numbers. - || (relocation.changes_line_numbers() - && !matches!(self.profile, super::InputProfile::TeX8Bit | super::InputProfile::UnicodeScalar)) + || self.physical_framing() != Some(relocation.physical_framing()) + || old.physical_framing() != Some(relocation.physical_framing()) || relocation.relocate_line(old.line_number) != Some(self.line_number) || self.physical_frontier().is_none() || old.physical_frontier().is_none() @@ -398,12 +495,12 @@ impl Mouth { let (start, old_start) = match (&self.xe, &old.xe) { (Some(current), Some(previous)) - if matches!(current.encoding, Encoding::Utf8 | Encoding::Bytes) - && current.encoding == previous.encoding + if current.encoding == previous.encoding && current.autodetected == previous.autodetected && current.skip_lf == previous.skip_lf - && current.terminated - && previous.terminated => + && current.terminated == previous.terminated + && (current.terminated + || (self.offset == self.data.len() && old.offset == old.data.len())) => { (current.line_start, previous.line_start) } @@ -436,7 +533,8 @@ impl Mouth { let content = prefix .strip_suffix(b"\r\n") .or_else(|| prefix.strip_suffix(b"\n")) - .or_else(|| prefix.strip_suffix(b"\r"))?; + .or_else(|| prefix.strip_suffix(b"\r")) + .or_else(|| (self.offset == self.data.len()).then_some(prefix))?; Some(content.iter().rposition(|b| matches!(b, b'\r' | b'\n')).map_or(0, |i| i + 1)) } @@ -504,6 +602,7 @@ impl Mouth { let (resolved, bom) = encoding.resolve(&data); let detected = (*encoding == Encoding::Auto).then(|| (resolved.clone(), bom)); (Some(XePhysical { + framing_history: Some(resolved.framing()), encoding: resolved, autodetected: detected, skip_lf: false, @@ -706,6 +805,9 @@ impl Mouth { ) -> Result { let xe = self.xe.as_mut().unwrap(); let framing = xe.encoding.framing(); + if xe.framing_history != Some(framing) { + xe.framing_history = None; + } let width = framing.unit_width(); if std::mem::take(&mut xe.skip_lf) && framing.code_unit(&self.data[self.offset..]) == Some(10) diff --git a/crates/texrra-tex-core/src/execution/source_relocation.rs b/crates/texrra-tex-core/src/execution/source_relocation.rs index 33a9d85..ba889bc 100644 --- a/crates/texrra-tex-core/src/execution/source_relocation.rs +++ b/crates/texrra-tex-core/src/execution/source_relocation.rs @@ -1,4 +1,4 @@ -use super::Span; +use super::{Span, XeLineFraming}; /// Coordinates preserved across a length-changing edit within a physical line /// or an insertion or deletion of complete physical lines. @@ -9,6 +9,7 @@ pub(super) struct SourceRelocation { current_suffix: usize, old_len: usize, first_unchanged_line: usize, + physical_framing: (XeLineFraming, usize), line_edit: Option, } @@ -20,46 +21,73 @@ struct PhysicalLineEdit { impl SourceRelocation { pub(super) fn new(source: usize, old: &[u8], current: &[u8]) -> Option { - if old.len() == current.len() { + Self::with_framing(source, old, current, XeLineFraming::Bytes, 0) + } + + pub(super) fn with_framing( + source: usize, + old: &[u8], + current: &[u8], + framing: XeLineFraming, + bom: usize, + ) -> Option { + if framing == XeLineFraming::Auto + || old.len() == current.len() + || old.get(..bom)? != current.get(..bom)? + { return None; } - let unchanged_prefix = old.iter().zip(current).take_while(|(a, b)| a == b).count(); - let unchanged_suffix = old[unchanged_prefix..] + let old = &old[bom..]; + let current = ¤t[bom..]; + let width = framing.unit_width(); + if old.len() % width != 0 || current.len() % width != 0 { + return None; + } + // Align byte matches down to complete units. The matching bytes + // within a changed unit do not prove a usable framing boundary. + let common_prefix = old.iter().zip(current).take_while(|(a, b)| a == b).count(); + let unchanged_prefix = common_prefix - common_prefix % width; + let common_suffix = old[unchanged_prefix..] .iter() .rev() .zip(current[unchanged_prefix..].iter().rev()) .take_while(|(a, b)| a == b) .count(); + let unchanged_suffix = common_suffix - common_suffix % width; let old_suffix = old.len() - unchanged_suffix; let current_suffix = current.len() - unchanged_suffix; - if old[unchanged_prefix..old_suffix] - .iter() - .chain(¤t[unchanged_prefix..current_suffix]) - .copied() - .any(is_line_break) + if framing + .line_boundary(&old[unchanged_prefix..old_suffix]) + .1 + .is_some() + || framing + .line_boundary(¤t[unchanged_prefix..current_suffix]) + .1 + .is_some() { - return Self::whole_line_edit(source, old, current, unchanged_prefix); + return Self::whole_line_edit(source, old, current, unchanged_prefix, framing, bom); } // Reject insertion between CR and LF or deletion that joins them. if unchanged_prefix > 0 - && old[unchanged_prefix - 1] == b'\r' - && old.get(old_suffix) == Some(&b'\n') + && framing.code_unit(&old[unchanged_prefix - width..]) == Some(13) + && framing.code_unit(&old[old_suffix..]) == Some(10) { return None; } - let next_break = old_suffix + old[old_suffix..].iter().copied().position(is_line_break)?; - let delimiter_width = if old[next_break..].starts_with(b"\r\n") { - 2 - } else { - 1 - }; + let (length, terminator) = framing.line_boundary(&old[old_suffix..]); + let terminator = terminator?; + let mut end = old_suffix + length + width; + if terminator == 13 && framing.code_unit(&old[end..]) == Some(10) { + end += width; + } Some(Self { source, - unchanged_prefix, - old_suffix, - current_suffix, - old_len: old.len(), - first_unchanged_line: next_break + delimiter_width, + unchanged_prefix: bom + unchanged_prefix, + old_suffix: bom + old_suffix, + current_suffix: bom + current_suffix, + old_len: bom + old.len(), + first_unchanged_line: bom + end, + physical_framing: (framing, bom), line_edit: None, }) } @@ -69,6 +97,8 @@ impl SourceRelocation { old: &[u8], current: &[u8], common_prefix: usize, + framing: XeLineFraming, + bom: usize, ) -> Option { let inserting = current.len() > old.len(); let (shorter, longer) = if inserting { @@ -77,6 +107,7 @@ impl SourceRelocation { (current, old) }; let changed_bytes = longer.len() - shorter.len(); + let width = framing.unit_width(); // Unlike the single-line check, allow the common prefix and suffix // to overlap. Repeated bytes can admit more than one line-aligned // decomposition, so accept only a unique seam. @@ -86,17 +117,20 @@ impl SourceRelocation { .zip(longer.iter().rev()) .take_while(|(a, b)| a == b) .count(); - let mut seams = (shorter.len() - common_suffix..=common_prefix).filter(|&start| { - starts_physical_line(shorter, start) - && starts_physical_line(longer, start) - && starts_physical_line(longer, start + changed_bytes) - }); + let suffix_start = shorter.len() - (common_suffix - common_suffix % width); + let mut seams = (suffix_start..=common_prefix) + .step_by(width) + .filter(|&start| { + starts_physical_line(shorter, start, framing) + && starts_physical_line(longer, start, framing) + && starts_physical_line(longer, start + changed_bytes, framing) + }); let start = seams.next()?; if start == shorter.len() || seams.next().is_some() { return None; } let end = start + changed_bytes; - let count = physical_break_count(&longer[start..end]); + let count = physical_break_count(&longer[start..end], framing); if count == 0 { return None; } @@ -107,19 +141,24 @@ impl SourceRelocation { }; Some(Self { source, - unchanged_prefix: start, - old_suffix, - current_suffix, - old_len: old.len(), - first_unchanged_line: old_suffix, + unchanged_prefix: bom + start, + old_suffix: bom + old_suffix, + current_suffix: bom + current_suffix, + old_len: bom + old.len(), + first_unchanged_line: bom + old_suffix, + physical_framing: (framing, bom), line_edit: Some(PhysicalLineEdit { - prefix_lines: physical_break_count(&shorter[..start]), + prefix_lines: physical_break_count(&shorter[..start], framing), removed, inserted, }), }) } + pub(super) fn physical_framing(&self) -> (XeLineFraming, usize) { + self.physical_framing + } + pub(super) fn source(&self) -> usize { self.source } @@ -137,7 +176,7 @@ impl SourceRelocation { }) } - /// Map a line of this input with static byte framing. Physical lines + /// Map a line of this input with static physical framing. Physical lines /// start at one, and zero and any virtual EOF positions remain meaningful. pub(super) fn relocate_line(&self, line: usize) -> Option { let Some(edit) = &self.line_edit else { @@ -228,20 +267,26 @@ fn is_line_break(byte: u8) -> bool { matches!(byte, b'\r' | b'\n') } -fn starts_physical_line(bytes: &[u8], offset: usize) -> bool { - offset == 0 - || bytes[offset - 1] == b'\n' - || (bytes[offset - 1] == b'\r' && bytes.get(offset) != Some(&b'\n')) +fn starts_physical_line(bytes: &[u8], offset: usize, framing: XeLineFraming) -> bool { + if offset == 0 { + return true; + } + match framing.code_unit(&bytes[offset - framing.unit_width()..offset]) { + Some(10) => true, + Some(13) => framing.code_unit(&bytes[offset..]) != Some(10), + _ => false, + } } -fn physical_break_count(bytes: &[u8]) -> usize { - let mut previous = 0; +fn physical_break_count(bytes: &[u8], framing: XeLineFraming) -> usize { + let mut previous = None; let mut count = 0; - for &byte in bytes { - if byte == b'\r' || (byte == b'\n' && previous != b'\r') { + for unit in bytes.chunks_exact(framing.unit_width()) { + let code = framing.code_unit(unit); + if code == Some(13) || (code == Some(10) && previous != Some(13)) { count += 1; } - previous = byte; + previous = code; } count } @@ -295,6 +340,72 @@ mod tests { } } + fn utf16(text: &str, framing: XeLineFraming) -> Vec { + let encode: fn(u16) -> [u8; 2] = match framing { + XeLineFraming::Utf16Le => u16::to_le_bytes, + XeLineFraming::Utf16Be => u16::to_be_bytes, + _ => unreachable!(), + }; + std::iter::once(0xfeff) + .chain(text.encode_utf16()) + .flat_map(encode) + .collect() + } + + #[test] + fn wide_relocation_ignores_separator_bytes_inside_other_units() { + for framing in [XeLineFraming::Utf16Le, XeLineFraming::Utf16Be] { + let old = utf16("aΩb\r\nnext\r\n", framing); + let current = utf16("aΩ\u{050a}\u{0d41}b\r\nnext\r\n", framing); + let map = SourceRelocation::with_framing(4, &old, ¤t, framing, 2).unwrap(); + let next = utf16("aΩb\r\n", framing).len(); + assert_eq!(map.physical_framing(), (framing, 2)); + assert!(!map.changes_line_numbers()); + assert_eq!(map.relocate_line(2), Some(2)); + assert_eq!(map.relocate_loaded_offset(next - 2), None); + assert_eq!(map.relocate_loaded_offset(next), Some(next + 4)); + } + } + + #[test] + fn wide_relocation_maps_unique_crlf_seams_from_the_bom() { + for framing in [XeLineFraming::Utf16Le, XeLineFraming::Utf16Be] { + let old = utf16("first\u{050a}\r\nsecond\r\n", framing); + let current = utf16("first\u{050a}\r\nthird\u{0d41}\r\nsecond\r\n", framing); + let seam = utf16("first\u{050a}\r\n", framing).len(); + let insert = SourceRelocation::with_framing(4, &old, ¤t, framing, 2).unwrap(); + let delete = SourceRelocation::with_framing(4, ¤t, &old, framing, 2).unwrap(); + assert_eq!(insert.relocate_offset(seam), None); + assert_eq!( + insert.relocate_loaded_offset(seam), + Some(seam + current.len() - old.len()) + ); + assert_eq!(insert.relocate_line(1), Some(1)); + assert_eq!(insert.relocate_line(2), Some(3)); + assert_eq!(delete.relocate_line(2), None); + assert_eq!(delete.relocate_line(3), Some(2)); + + let leading = utf16("new\r\nfirst\u{050a}\r\nsecond\r\n", framing); + let map = SourceRelocation::with_framing(4, &old, &leading, framing, 2).unwrap(); + assert_eq!( + map.relocate_loaded_offset(2), + Some(2 + leading.len() - old.len()) + ); + assert_eq!(map.relocate_line(1), Some(2)); + + let split = utf16("first\u{050a}\rX\nsecond\r\n", framing); + assert!(SourceRelocation::with_framing(4, &old, &split, framing, 2).is_none()); + assert!(SourceRelocation::with_framing(4, &split, &old, framing, 2).is_none()); + assert!( + SourceRelocation::with_framing(4, &old, ¤t[..current.len() - 1], framing, 2) + .is_none() + ); + let mut changed_bom = current; + changed_bom[0] = 0; + assert!(SourceRelocation::with_framing(4, &old, &changed_bom, framing, 2).is_none()); + } + } + #[test] fn relocation_rejects_ambiguous_whole_line_seams() { let shorter = b"cover\nrepeat\nending\n"; diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index a26465f..f5e26f5 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,26 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-12-02 XeTeX 整行编辑复用 + +XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他 +按字节分行的解码器可以在同类规则内切换。稳定的 UTF-16 LE/BE +按真实端序和代码单元核对 CR、LF、CRLF、BOM 及接缝。文件末行 +直接结束时,需同时验证已加载行和 EOF。若已读前缀跨过不同分行 +规则,继续执行以恢复真实状态。已观察过变化行号的后缀同样重跑。 + +原样 12 页 NeurIPS 2025 在第 408 行前插入一条 34 字节注释, +并在只保留长版的会话中删除。两次各复用 14,696,911 步前缀和 +26,853 步后缀,执行 4,847,127 步。两次共各发布 0 个页面更新。 +末行位置由 765 变为 766,随后恢复。第 4 页字形来源双向移动 +34 字节。执行、PDF、SVG、页面与来源映射、资源和生成文件均 +与各自的独立全量相同。更早的会合点之后仍有入口行号观测。 +记录及资源冻结清单位于 `target/p4-xetex-physical-lines/`。 + +四页集成样例使用实写 UTF-16 LE BOM 和 CRLF,并覆盖含 LF 字节的 +普通字符,整行增删均复用后缀。变更前的十二项扫描及来源单测、 +加入 EOF 支持后的十二项管线回归通过。 + ## 2026-12-01 整行增删后的后缀复用 固定字节分行的 TeX8Bit 和 UnicodeScalar 输入支持完整物理行的插入和 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 67190c8..c3790ee 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -15,7 +15,7 @@ use std::{ use texrra_engine::native::*; use texrra_tex_core::{ artifacts::file_version, - execution::{Cancellation, JobTime}, + execution::{Cancellation, InputProfile, JobTime}, resources::{FileWorld, GeneratedLookupOrigin, ResourceKind, SearchPath, WorldConfig}, }; const HEADER: &str = r"\catcode123=1\catcode125=2\catcode35=6\font\f=cmr10\f "; @@ -444,6 +444,10 @@ fn paragraph_search_reuse_keeps_current_paint_sources_writes_and_layout() { fs::remove_dir_all(p).unwrap(); } fn atomic_definition(p: &Path, revision: u64, body: &str) -> ProjectDefinition { + atomic_definition_with_source(p, revision, format!("{HEADER}{body}").into_bytes()) +} + +fn atomic_definition_with_source(p: &Path, revision: u64, source: Vec) -> ProjectDefinition { let mut configuration = request(p).world; let map = match &configuration.paths[&ResourceKind::Map][0] { SearchPath::Directory { path, .. } => path.join("pdftex.map"), @@ -451,10 +455,7 @@ fn atomic_definition(p: &Path, revision: u64, body: &str) -> ProjectDefinition { }; let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); let mut files = std::collections::BTreeMap::new(); - files.insert( - p.join("main.tex"), - Arc::from(format!("{HEADER}{body}").into_bytes()), - ); + files.insert(p.join("main.tex"), Arc::from(source)); for font in ["cmr10", "cmr7"] { for (relative, actual) in [ ( @@ -1919,17 +1920,36 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { #[test] fn whole_line_edits_reuse_the_settled_suffix_and_relocate_provenance() { - check_whole_line_suffix_edits("whole-line-safe-suffix", false); + check_whole_line_suffix_edits("whole-line-safe-suffix", InputProfile::TeX8Bit, false); +} + +#[test] +fn xetex_utf16_whole_line_edits_reuse_and_relocate_the_settled_suffix() { + check_whole_line_suffix_edits("whole-line-utf16-suffix", InputProfile::XeTeX, false); } #[test] fn whole_line_edits_reexecute_a_delayed_input_line_read_on_the_same_source() { - check_whole_line_suffix_edits("whole-line-delayed-inputlineno", true); + check_whole_line_suffix_edits("whole-line-delayed-inputlineno", InputProfile::TeX8Bit, true); } -fn check_whole_line_suffix_edits(label: &str, observe_delayed_line: bool) { +fn check_whole_line_suffix_edits(label: &str, profile: InputProfile, observe_delayed_line: bool) { let cwd = directory(label); let entry = cwd.join("main.tex"); + let encode = |source: &str| -> Vec { + if profile == InputProfile::XeTeX { + let physical_lines = source.replace('\n', "\r\n"); + [0xff, 0xfe] + .into_iter() + .chain(physical_lines.encode_utf16().flat_map(u16::to_le_bytes)) + .collect() + } else { + source.as_bytes().to_vec() + } + }; + let byte_offset = |source: &str, marker: &str| { + encode(&source[..source.find(marker).unwrap()]).len() + }; let delayed = if observe_delayed_line { r"\write16{Suffix line \number\inputlineno}" } else { @@ -1955,14 +1975,22 @@ fn check_whole_line_suffix_edits(label: &str, observe_delayed_line: bool) { .unwrap() + 1 }; - let comment = "% Inserted physical line\n"; + let comment = if profile == InputProfile::XeTeX { + // U+010A contains an LF byte in UTF-16 LE without ending the line. + "% Inserted physical line \u{010a}\n" + } else { + "% Inserted physical line\n" + }; for (seed, edited) in [("", comment), (comment, "")] { // Give each direction one donor, so the deletion cannot reuse a // completed revision that already contained the shorter source. let original = body(seed); - let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &original)).unwrap(); + let original_source = encode(&format!("{HEADER}{original}")); + let project = + ProjectSnapshot::new(atomic_definition_with_source(&cwd, 1, original_source)).unwrap(); let mut input = request(&cwd).observe_generated_initial(); input.world = project.configuration(); + input.input_profile = profile; let session = NativeCompiler::default().with_automatic_entry_checkpoints(); let donor = session .compile(input.clone().with_project(project.clone())) @@ -1982,10 +2010,10 @@ fn check_whole_line_suffix_edits(label: &str, observe_delayed_line: bool) { } ); let source = format!("{HEADER}{changed}"); - let prefix_read_end = source.find(r"\shipout\hbox{Cover}").unwrap(); - let glyph_offset = source.find("Suffix glyphs").unwrap(); + let prefix_read_end = byte_offset(&source, r"\shipout\hbox{Cover}"); + let glyph_offset = byte_offset(&source, "Suffix glyphs"); let project = project - .with_file_edits(2, [(entry.clone(), Arc::from(source.into_bytes()))].into()) + .with_file_edits(2, [(entry.clone(), Arc::from(encode(&source)))].into()) .unwrap(); let input = input.with_project(project); let updated = session.compile(input.clone()).unwrap();