Reuse XeTeX suffixes across physical line edits

This commit is contained in:
gloamxun committed 2026-12-02 00:22:21 +08:00
1 parent 0b4aa49a71
commit bf42a88dff
5 files changed
+337 -73

No files matched your search

@@ -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 {
+115 -13
View File
@@ -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<XeLineFraming>,
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(&current, &delete), supported);
assert!(current.same_unread_input_relocated(&old, &insert));
assert!(old.same_unread_input_relocated(&current, &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(&current).unwrap();
assert!(previous.same_unread_input_relocated(&current, &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::<Vec<_>>()
};
let previous = source(b"");
let current = source(b"% note\n");
let raw_map = SourceRelocation::new(4, &previous, &current).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<SourceRelocation> {
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<bool, (Span, String)> {
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)
@@ -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<PhysicalLineEdit>,
}
@@ -20,46 +21,73 @@ struct PhysicalLineEdit {
impl SourceRelocation {
pub(super) fn new(source: usize, old: &[u8], current: &[u8]) -> Option<Self> {
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<Self> {
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 = &current[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(&current[unchanged_prefix..current_suffix])
.copied()
.any(is_line_break)
if framing
.line_boundary(&old[unchanged_prefix..old_suffix])
.1
.is_some()
|| framing
.line_boundary(&current[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<Self> {
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<usize> {
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<u8> {
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, &current, 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, &current, framing, 2).unwrap();
let delete = SourceRelocation::with_framing(4, &current, &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, &current[..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";