Reuse settled TeX suffixes after physical line edits
This commit is contained in:
1 parent
5b86a7ac7e
commit
ac5f691a48
15 files changed
+518
-30
No files matched your search
@@ -1,4 +1,4 @@
|
||||
use std::collections::{BTreeSet, VecDeque};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -282,6 +282,7 @@ pub struct Executor {
|
||||
format_image_warnings: Vec<String>,
|
||||
pdf_force_pagebox_warned: bool,
|
||||
input_position: Option<(usize, usize)>,
|
||||
line_observations: BTreeMap<usize, usize>,
|
||||
paragraph: Option<super::paragraph::Builder>,
|
||||
vertical: super::boxes::VerticalBuilder,
|
||||
box_frames: Vec<boxes::BoxFrame>,
|
||||
@@ -617,6 +618,7 @@ impl Executor {
|
||||
format_image_warnings: Vec::new(),
|
||||
pdf_force_pagebox_warned: false,
|
||||
input_position: None,
|
||||
line_observations: BTreeMap::new(),
|
||||
paragraph: None,
|
||||
vertical,
|
||||
box_frames: Vec::new(),
|
||||
@@ -702,6 +704,10 @@ impl Executor {
|
||||
self.state.page_marks.clear();
|
||||
self
|
||||
}
|
||||
/// Keep every observation even when its source was already read in the prefix.
|
||||
fn observe_line_number(&mut self, source: usize) {
|
||||
*self.line_observations.entry(source).or_default() += 1;
|
||||
}
|
||||
fn error(&self, message: impl Into<String>, span: Span) -> Error {
|
||||
let mut error = Error::at(&self.sources, self.state.input_profile(), message, span);
|
||||
if let Some(generated) = self.generated_inputs.get(&span.source) {
|
||||
@@ -2781,6 +2787,7 @@ impl Executor {
|
||||
self.error("no native input position available", self.current)
|
||||
})?;
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
i32::try_from(line)
|
||||
.map_err(|_| self.error("input line number overflow", self.current))
|
||||
}
|
||||
@@ -3253,10 +3260,10 @@ impl Executor {
|
||||
.decode_line(&line[bom..bom + length], base + bom, &self.state, &mut self.reads)
|
||||
.map_err(|e| self.error(e, Span { source, start: base + bom, end }))?;
|
||||
if warnings > 0 {
|
||||
self.observe_xe_utf8_warnings(
|
||||
vec![(self.input_position.map_or(1, |(_, line)| line), warnings)],
|
||||
files,
|
||||
)?;
|
||||
let (line_source, line) = self
|
||||
.input_position
|
||||
.map_or((None, 1), |(source, line)| (Some(source), line));
|
||||
self.observe_xe_utf8_warnings(line_source, vec![(line, warnings)], files)?;
|
||||
}
|
||||
chars
|
||||
} else {
|
||||
@@ -3352,7 +3359,7 @@ impl Executor {
|
||||
return self.fail("native read token limit exceeded");
|
||||
}
|
||||
}
|
||||
self.observe_xe_utf8_warnings(mouth.take_utf8_warnings(), files)?;
|
||||
self.observe_xe_utf8_warnings(Some(source), mouth.take_utf8_warnings(), files)?;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -3584,6 +3591,7 @@ impl Executor {
|
||||
stream_sources: self.stream_sources,
|
||||
generated_inputs: self.generated_inputs,
|
||||
reads,
|
||||
line_observations: Some(self.line_observations),
|
||||
events: self.events.into_vec(),
|
||||
steps: self.steps,
|
||||
reads_event_history: self.reads_event_history,
|
||||
@@ -4089,6 +4097,7 @@ impl Executor {
|
||||
stream_sources: self.stream_sources,
|
||||
generated_inputs: self.generated_inputs,
|
||||
reads,
|
||||
line_observations: Some(self.line_observations),
|
||||
incoming_state,
|
||||
steps: self.steps,
|
||||
reads_event_history: self.reads_event_history,
|
||||
@@ -4187,11 +4196,12 @@ impl Executor {
|
||||
let Some(InputFrame::Source { source, mouth, .. }) = self.inputs.last_mut() else {
|
||||
unreachable!("new job starts with its entry source");
|
||||
};
|
||||
let source = *source;
|
||||
let line = mouth
|
||||
.load_line(&self.state, &mut self.reads)
|
||||
.map(|_| (*source, mouth.line_number()));
|
||||
.map(|_| (source, mouth.line_number()));
|
||||
let warnings = mouth.take_utf8_warnings();
|
||||
self.observe_xe_utf8_warnings(warnings, files)?;
|
||||
self.observe_xe_utf8_warnings(Some(source), warnings, files)?;
|
||||
self.input_position =
|
||||
Some(line.map_err(|(span, message)| self.error(message, span))?);
|
||||
self.push_mode_hook(TokenParameter::Everyjob)?;
|
||||
|
||||
@@ -811,6 +811,7 @@ impl Executor {
|
||||
};
|
||||
let (b, (missing, extra)) = result.map_err(|e| self.error(e, frame.span))?;
|
||||
if missing != 0 || extra != 0 {
|
||||
self.observe_line_number(self.current.source);
|
||||
let line = self.error("", self.current).line;
|
||||
files
|
||||
.observe_message(&format!(
|
||||
|
||||
@@ -193,6 +193,25 @@ impl EntryCheckpoint {
|
||||
None if self.frontier == prior.frontier => None,
|
||||
None => return None,
|
||||
};
|
||||
let observes_entry_line = completed.line_observations.as_ref().is_none_or(|observations| {
|
||||
observations.get(&self.entry) != old.line_observations.get(&self.entry)
|
||||
});
|
||||
if observes_entry_line
|
||||
&& relocation.as_ref().map_or_else(
|
||||
|| !SourceRelocation::same_line_breaks(previous_bytes, current_bytes),
|
||||
SourceRelocation::changes_line_numbers,
|
||||
)
|
||||
{
|
||||
// The old line number can be embedded in outputs. Equal byte
|
||||
// offsets can also mean different lines if a newline moved.
|
||||
return None;
|
||||
}
|
||||
let line_observations = match &completed.line_observations {
|
||||
Some(later) => Some(splice_line_observations(
|
||||
¤t.line_observations, &old.line_observations, later,
|
||||
)?),
|
||||
None => None,
|
||||
};
|
||||
// Comparison and publication visit some of the same original
|
||||
// allocations. Keep the checked relocations for this donor only.
|
||||
let mut moved = relocation.as_ref().map(EventRelocation::new);
|
||||
@@ -240,6 +259,7 @@ impl EntryCheckpoint {
|
||||
stream_sources: completed.stream_sources.clone(),
|
||||
generated_inputs: completed.generated_inputs.clone(),
|
||||
reads: completed.reads.clone(),
|
||||
line_observations,
|
||||
incoming_state: completed.incoming_state,
|
||||
outgoing_state: completed.outgoing_state,
|
||||
steps,
|
||||
@@ -344,6 +364,9 @@ impl EntryCheckpoint {
|
||||
}
|
||||
|
||||
let mut executor = next.clone();
|
||||
executor.line_observations = splice_line_observations(
|
||||
¤t.line_observations, &old.line_observations, &next.line_observations,
|
||||
)?;
|
||||
let mut events = prefix.clone();
|
||||
// Checkpoint capture seals the event log. Share the old suffix
|
||||
// chunks so all carried checkpoints keep the same allocation graph.
|
||||
@@ -400,6 +423,26 @@ fn measure<T>(elapsed: Option<&mut Duration>, action: impl FnOnce() -> T) -> T {
|
||||
value
|
||||
}
|
||||
|
||||
// Counts describe reads observed on a particular execution history.
|
||||
fn splice_line_observations(
|
||||
current: &BTreeMap<usize, usize>,
|
||||
prior: &BTreeMap<usize, usize>,
|
||||
later: &BTreeMap<usize, usize>,
|
||||
) -> Option<BTreeMap<usize, usize>> {
|
||||
if prior.keys().any(|source| !later.contains_key(source)) {
|
||||
return None;
|
||||
}
|
||||
let mut combined = current.clone();
|
||||
for (&source, &count) in later {
|
||||
let suffix = count.checked_sub(prior.get(&source).copied().unwrap_or_default())?;
|
||||
if suffix != 0 {
|
||||
let total = combined.entry(source).or_default();
|
||||
*total = total.checked_add(suffix)?;
|
||||
}
|
||||
}
|
||||
Some(combined)
|
||||
}
|
||||
|
||||
fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> {
|
||||
match event {
|
||||
Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))),
|
||||
@@ -469,7 +512,6 @@ fn same_kernel_continuation(
|
||||
restored_pdf_image_count,
|
||||
format_image_warnings,
|
||||
pdf_force_pagebox_warned,
|
||||
input_position,
|
||||
box_nodes_created,
|
||||
material_charge,
|
||||
mark_cells_created,
|
||||
@@ -492,6 +534,8 @@ fn same_kernel_continuation(
|
||||
generated_inputs,
|
||||
conditionals,
|
||||
current,
|
||||
input_position,
|
||||
line_observations,
|
||||
pdf_catalog_tokens,
|
||||
pdf_outlines,
|
||||
pdf_info_tokens,
|
||||
@@ -548,6 +592,7 @@ fn same_kernel_continuation(
|
||||
&& current.generated_inputs == prior.generated_inputs
|
||||
&& current.conditionals == prior.conditionals
|
||||
&& current.current == prior.current
|
||||
&& current.input_position == prior.input_position
|
||||
&& current.pdf_catalog_tokens == prior.pdf_catalog_tokens
|
||||
&& current.pdf_outlines == prior.pdf_outlines
|
||||
&& current.pdf_info_tokens == prior.pdf_info_tokens
|
||||
|
||||
@@ -7,7 +7,9 @@ pub(super) fn same_kernel_provenance(
|
||||
relocation: &mut EventRelocation<'_>,
|
||||
) -> Option<bool> {
|
||||
let map = relocation.map();
|
||||
if current.current != map.relocate_span(prior.current)? {
|
||||
if current.current != map.relocate_span(prior.current)?
|
||||
|| current.input_position != map.relocate_position(prior.input_position)?
|
||||
{
|
||||
return Some(false);
|
||||
}
|
||||
for (current, prior) in current.inputs.iter().zip(&prior.inputs) {
|
||||
@@ -58,6 +60,7 @@ pub(super) fn same_kernel_provenance(
|
||||
let mut conditionals = prior.conditionals.clone();
|
||||
for conditional in &mut conditionals {
|
||||
conditional.span = map.relocate_span(conditional.span)?;
|
||||
conditional.origin = map.relocate_position(conditional.origin)?;
|
||||
}
|
||||
let mut catalog = prior.pdf_catalog_tokens.clone();
|
||||
let mut info = prior.pdf_info_tokens.clone();
|
||||
@@ -128,6 +131,7 @@ pub(super) fn append_suffix(
|
||||
execution.events.push(relocation.relocate_event(event)?);
|
||||
}
|
||||
}
|
||||
execution.input_position = map.relocate_position(execution.input_position)?;
|
||||
execution.state.relocate_source(relocation)?;
|
||||
relocate_page(&mut execution.native_page, relocation)?;
|
||||
relocation.relocate_vertical(&mut execution.split_discards)?;
|
||||
|
||||
@@ -43,6 +43,7 @@ impl Executor {
|
||||
record.push_str(&format!("(level {level})"));
|
||||
if let Some((source, line)) = origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
record.push_str(&format!(" entered on line {line}"));
|
||||
}
|
||||
@@ -208,6 +209,11 @@ impl Executor {
|
||||
self.reads.insert(Dependency::EscapeChar);
|
||||
self.reads.insert(Dependency::NewLineChar);
|
||||
let context = self.input_context();
|
||||
for frame in &context.frames {
|
||||
if let ContextKind::Source { source, .. } = frame.kind {
|
||||
self.observe_line_number(source);
|
||||
}
|
||||
}
|
||||
self.reads.extend(context.reads.iter().cloned());
|
||||
context
|
||||
}
|
||||
@@ -457,6 +463,11 @@ impl Executor {
|
||||
let (body, dependencies) = self
|
||||
.activity_lists(breadth, depth, wrap)
|
||||
.map_err(|message| self.error(message, span))?;
|
||||
for dependency in &dependencies {
|
||||
if let Dependency::InputPosition(source) = dependency {
|
||||
self.observe_line_number(*source);
|
||||
}
|
||||
}
|
||||
self.reads.extend(dependencies);
|
||||
body
|
||||
}
|
||||
@@ -523,6 +534,7 @@ impl Executor {
|
||||
}
|
||||
if let Some((source, line)) = frame.origin.filter(|(_, line)| *line != 0) {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
description.push_str(&format!(" entered on line {line}"));
|
||||
}
|
||||
format!("### level {}: {description}", index + 1)
|
||||
@@ -547,6 +559,7 @@ impl Executor {
|
||||
);
|
||||
if let Some((source, line)) = origin.filter(|(_, line)| *line != 0) {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
*self.line_observations.entry(source).or_default() += 1;
|
||||
text.push_str(&format!(" entered at line {line}"));
|
||||
}
|
||||
let detail = if let Some(frame) =
|
||||
|
||||
@@ -124,7 +124,8 @@ impl Executor {
|
||||
Err((span, text)) => Next::Error(span, text),
|
||||
};
|
||||
if !warnings.is_empty() {
|
||||
self.observe_xe_utf8_warnings(warnings, files)?;
|
||||
let source = *source;
|
||||
self.observe_xe_utf8_warnings(Some(source), warnings, files)?;
|
||||
}
|
||||
next
|
||||
}
|
||||
@@ -252,9 +253,13 @@ impl Executor {
|
||||
|
||||
pub(super) fn observe_xe_utf8_warnings(
|
||||
&mut self,
|
||||
source: Option<usize>,
|
||||
warnings: Vec<(usize, usize)>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
if !warnings.is_empty() && let Some(source) = source {
|
||||
self.observe_line_number(source);
|
||||
}
|
||||
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"),
|
||||
|
||||
@@ -121,6 +121,7 @@ impl Executor {
|
||||
);
|
||||
if let Some((source, line)) = origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
name.push_str(&format!(" entered at line {line}"));
|
||||
}
|
||||
@@ -146,6 +147,7 @@ impl Executor {
|
||||
}
|
||||
if let Some((source, line)) = frame.origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
name.push_str(&format!(" entered on line {line}"));
|
||||
}
|
||||
|
||||
@@ -108,6 +108,7 @@ impl Executor {
|
||||
let mut message = format!("{{{action} {name} group (level {level})");
|
||||
if let Some((source, line)) = origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
let location = if entering {
|
||||
"at line"
|
||||
|
||||
@@ -681,6 +681,9 @@ pub struct Execution {
|
||||
/// Reads made during this execution, not a license to reuse output after
|
||||
/// state changes. Incremental execution/cache reuse is a later milestone.
|
||||
pub reads: BTreeSet<Dependency>,
|
||||
/// Per-source observations distinguish suffix reads from identical prefix reads.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
line_observations: Option<BTreeMap<usize, usize>>,
|
||||
pub incoming_state: u64,
|
||||
pub outgoing_state: u64,
|
||||
pub steps: usize,
|
||||
|
||||
@@ -287,6 +287,32 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocated_mouth_maps_whole_lines_only_under_static_framing() {
|
||||
use super::super::InputProfile;
|
||||
|
||||
let shorter = b"cover\r\nunchanged\r\nlater\r\n";
|
||||
let longer = b"cover\r\n% note\r\nunchanged\r\nlater\r\n";
|
||||
let insert = SourceRelocation::new(4, shorter, longer).unwrap();
|
||||
let delete = SourceRelocation::new(4, longer, shorter).unwrap();
|
||||
for profile in [InputProfile::TeX8Bit, InputProfile::UnicodeScalar, InputProfile::XeTeX] {
|
||||
let state = State::default().with_input_profile(profile);
|
||||
let mut reads = DependencyReads::default();
|
||||
let mut old = Mouth::new(4, shorter.to_vec(), profile);
|
||||
let mut current = Mouth::new(4, longer.to_vec(), profile);
|
||||
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!(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);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_line_endings_and_utf8_byte_offsets_are_preserved() {
|
||||
let result = tokens("é界 \r\nB\rC");
|
||||
@@ -339,12 +365,12 @@ impl Mouth {
|
||||
&& self.state == other.state
|
||||
&& self.end_after_line == other.end_after_line
|
||||
&& self.line_breaks == other.line_breaks
|
||||
&& self.line_number == other.line_number
|
||||
&& self.invalid_utf8 == other.invalid_utf8
|
||||
}
|
||||
|
||||
pub(super) fn same_unread_input(&self, other: &Self) -> bool {
|
||||
self.same_unread_state(other)
|
||||
&& self.line_number == other.line_number
|
||||
&& self.offset == other.offset
|
||||
&& self.line == other.line
|
||||
&& self.xe == other.xe
|
||||
@@ -358,6 +384,11 @@ 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))
|
||||
|| relocation.relocate_line(old.line_number) != Some(self.line_number)
|
||||
|| self.physical_frontier().is_none()
|
||||
|| old.physical_frontier().is_none()
|
||||
|| relocation.relocate_offset(old.offset) != Some(self.offset)
|
||||
@@ -390,13 +421,13 @@ impl Mouth {
|
||||
|
||||
// Compare the full physical line as well as its normalized characters.
|
||||
// Bytes discarded or transformed by the decoder still affect context.
|
||||
relocation.relocate_loaded_line(old_start) == Some(start)
|
||||
relocation.relocate_loaded_offset(old_start) == Some(start)
|
||||
&& self.data[start..] == old.data[old_start..]
|
||||
&& self.line.len() == old.line.len()
|
||||
&& self.line.iter().zip(&old.line).all(|(new, old)| {
|
||||
new.value == old.value
|
||||
&& relocation.relocate_offset(old.start) == Some(new.start)
|
||||
&& relocation.relocate_offset(old.end) == Some(new.end)
|
||||
&& relocation.relocate_loaded_offset(old.start) == Some(new.start)
|
||||
&& relocation.relocate_loaded_offset(old.end) == Some(new.end)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::Span;
|
||||
|
||||
/// Byte coordinates that can survive a length-changing edit to a physical
|
||||
/// line. The changed interval has no correspondence in the other revision.
|
||||
/// Coordinates preserved across a length-changing edit within a physical line
|
||||
/// or an insertion or deletion of complete physical lines.
|
||||
pub(super) struct SourceRelocation {
|
||||
source: usize,
|
||||
unchanged_prefix: usize,
|
||||
@@ -9,6 +9,13 @@ pub(super) struct SourceRelocation {
|
||||
current_suffix: usize,
|
||||
old_len: usize,
|
||||
first_unchanged_line: usize,
|
||||
line_edit: Option<PhysicalLineEdit>,
|
||||
}
|
||||
|
||||
struct PhysicalLineEdit {
|
||||
prefix_lines: usize,
|
||||
removed: usize,
|
||||
inserted: usize,
|
||||
}
|
||||
|
||||
impl SourceRelocation {
|
||||
@@ -30,11 +37,13 @@ impl SourceRelocation {
|
||||
.chain(¤t[unchanged_prefix..current_suffix])
|
||||
.copied()
|
||||
.any(is_line_break)
|
||||
// Inserting between CR and LF, or deleting there to join them,
|
||||
// changes the physical line count without changing either byte.
|
||||
|| (unchanged_prefix > 0
|
||||
&& old[unchanged_prefix - 1] == b'\r'
|
||||
&& old.get(old_suffix) == Some(&b'\n'))
|
||||
{
|
||||
return Self::whole_line_edit(source, old, current, unchanged_prefix);
|
||||
}
|
||||
// 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')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -51,6 +60,63 @@ impl SourceRelocation {
|
||||
current_suffix,
|
||||
old_len: old.len(),
|
||||
first_unchanged_line: next_break + delimiter_width,
|
||||
line_edit: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn whole_line_edit(
|
||||
source: usize,
|
||||
old: &[u8],
|
||||
current: &[u8],
|
||||
common_prefix: usize,
|
||||
) -> Option<Self> {
|
||||
let inserting = current.len() > old.len();
|
||||
let (shorter, longer) = if inserting {
|
||||
(old, current)
|
||||
} else {
|
||||
(current, old)
|
||||
};
|
||||
let changed_bytes = longer.len() - shorter.len();
|
||||
// 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.
|
||||
let common_suffix = shorter
|
||||
.iter()
|
||||
.rev()
|
||||
.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 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]);
|
||||
if count == 0 {
|
||||
return None;
|
||||
}
|
||||
let (old_suffix, current_suffix, removed, inserted) = if inserting {
|
||||
(start, end, 0, count)
|
||||
} else {
|
||||
(end, start, count, 0)
|
||||
};
|
||||
Some(Self {
|
||||
source,
|
||||
unchanged_prefix: start,
|
||||
old_suffix,
|
||||
current_suffix,
|
||||
old_len: old.len(),
|
||||
first_unchanged_line: old_suffix,
|
||||
line_edit: Some(PhysicalLineEdit {
|
||||
prefix_lines: physical_break_count(&shorter[..start]),
|
||||
removed,
|
||||
inserted,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -58,6 +124,46 @@ impl SourceRelocation {
|
||||
self.source
|
||||
}
|
||||
|
||||
pub(super) fn changes_line_numbers(&self) -> bool {
|
||||
self.line_edit.is_some()
|
||||
}
|
||||
|
||||
/// Byte-aligned diagnostic locations keep their physical line numbers
|
||||
/// when the same CR and LF bytes occupy the same positions.
|
||||
pub(super) fn same_line_breaks(old: &[u8], current: &[u8]) -> bool {
|
||||
old.len() == current.len()
|
||||
&& old.iter().zip(current).all(|(&old, ¤t)| {
|
||||
old == current || !(is_line_break(old) || is_line_break(current))
|
||||
})
|
||||
}
|
||||
|
||||
/// Map a line of this input with static byte 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 {
|
||||
return Some(line);
|
||||
};
|
||||
if line <= edit.prefix_lines {
|
||||
return Some(line);
|
||||
}
|
||||
let surviving_line = line.checked_sub(edit.removed)?;
|
||||
(surviving_line > edit.prefix_lines)
|
||||
.then_some(surviving_line)?
|
||||
.checked_add(edit.inserted)
|
||||
}
|
||||
|
||||
pub(super) fn relocate_position(
|
||||
&self,
|
||||
position: Option<(usize, usize)>,
|
||||
) -> Option<Option<(usize, usize)>> {
|
||||
match position {
|
||||
Some((source, line)) if source == self.source => {
|
||||
Some(Some((source, self.relocate_line(line)?)))
|
||||
}
|
||||
_ => Some(position),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn relocate_offset(&self, old_offset: usize) -> Option<usize> {
|
||||
let one_side_is_empty = self.unchanged_prefix == self.old_suffix
|
||||
|| self.unchanged_prefix == self.current_suffix;
|
||||
@@ -100,11 +206,13 @@ impl SourceRelocation {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn relocate_loaded_line(&self, old_start: usize) -> Option<usize> {
|
||||
if old_start < self.first_unchanged_line {
|
||||
/// A coordinate in the loaded raw line after its start and full suffix
|
||||
/// have been checked. Unlike a general point, its side of the seam is known.
|
||||
pub(super) fn relocate_loaded_offset(&self, old_offset: usize) -> Option<usize> {
|
||||
if old_offset < self.first_unchanged_line {
|
||||
return None;
|
||||
}
|
||||
self.relocate_suffix_offset(old_start)
|
||||
self.relocate_suffix_offset(old_offset)
|
||||
}
|
||||
|
||||
fn relocate_suffix_offset(&self, old_offset: usize) -> Option<usize> {
|
||||
@@ -120,6 +228,24 @@ 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 physical_break_count(bytes: &[u8]) -> usize {
|
||||
let mut previous = 0;
|
||||
let mut count = 0;
|
||||
for &byte in bytes {
|
||||
if byte == b'\r' || (byte == b'\n' && previous != b'\r') {
|
||||
count += 1;
|
||||
}
|
||||
previous = byte;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -136,8 +262,45 @@ mod tests {
|
||||
assert_eq!(map.relocate_span(span(2, 4)), Some(span(3, 5)));
|
||||
assert_eq!(map.relocate_span(span(1, 3)), None);
|
||||
assert_eq!(map.relocate_span(span(2, 2)), None);
|
||||
assert_eq!(map.relocate_loaded_line(2), None);
|
||||
assert_eq!(map.relocate_loaded_line(6), Some(7));
|
||||
assert_eq!(map.relocate_loaded_offset(2), None);
|
||||
assert_eq!(map.relocate_loaded_offset(6), Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocation_maps_complete_physical_lines_in_both_directions() {
|
||||
for delimiter in ["\n", "\r\n", "\r"] {
|
||||
let prefix = format!("cover{delimiter}");
|
||||
let inserted = format!("% note{delimiter}% second{delimiter}");
|
||||
let suffix = format!("unchanged{delimiter}ending{delimiter}");
|
||||
let shorter = format!("{prefix}{suffix}");
|
||||
let longer = format!("{prefix}{inserted}{suffix}");
|
||||
let insert = SourceRelocation::new(4, shorter.as_bytes(), longer.as_bytes()).unwrap();
|
||||
let delete = SourceRelocation::new(4, longer.as_bytes(), shorter.as_bytes()).unwrap();
|
||||
let point = prefix.len();
|
||||
assert!(insert.changes_line_numbers() && delete.changes_line_numbers());
|
||||
assert_eq!(insert.relocate_offset(point), None);
|
||||
assert_eq!(
|
||||
insert.relocate_loaded_offset(point),
|
||||
Some(point + inserted.len())
|
||||
);
|
||||
assert_eq!(insert.relocate_line(0), Some(0));
|
||||
assert_eq!(insert.relocate_line(1), Some(1));
|
||||
assert_eq!(insert.relocate_line(2), Some(4));
|
||||
assert_eq!(insert.relocate_line(4), Some(6)); // Virtual EOF line.
|
||||
assert_eq!(delete.relocate_position(Some((4, 2))), None);
|
||||
assert_eq!(delete.relocate_position(Some((4, 3))), None);
|
||||
assert_eq!(delete.relocate_position(Some((4, 4))), Some(Some((4, 2))));
|
||||
assert_eq!(delete.relocate_position(Some((7, 3))), Some(Some((7, 3))));
|
||||
assert_eq!(delete.relocate_position(None), Some(None));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocation_rejects_ambiguous_whole_line_seams() {
|
||||
let shorter = b"cover\nrepeat\nending\n";
|
||||
let longer = b"cover\nrepeat\nrepeat\nending\n";
|
||||
assert!(SourceRelocation::new(4, shorter, longer).is_none());
|
||||
assert!(SourceRelocation::new(4, longer, shorter).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -254,15 +254,17 @@ impl Relocate for Event {
|
||||
| Self::Show(_)
|
||||
| Self::ShowBox(_)
|
||||
| Self::ShowRedirected { .. } => None,
|
||||
Self::ConditionalTrace { origin, .. } | Self::GroupTrace { origin, .. } => {
|
||||
*origin = context.map.relocate_position(*origin)?;
|
||||
Some(())
|
||||
}
|
||||
Self::PdfImageObject(_)
|
||||
| Self::ShipoutTrace { .. }
|
||||
| Self::AssignmentTrace { .. }
|
||||
| Self::RestoreTrace { .. }
|
||||
| Self::CommandTrace { .. }
|
||||
| Self::MacroTrace { .. }
|
||||
| Self::PseudoInput { .. }
|
||||
| Self::ConditionalTrace { .. }
|
||||
| Self::GroupTrace { .. } => Some(()),
|
||||
| Self::PseudoInput { .. } => Some(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,7 @@ impl State {
|
||||
}
|
||||
}
|
||||
for group in &mut self.groups {
|
||||
group.origin = relocation.map().relocate_position(group.origin)?;
|
||||
relocate_tokens(&mut group.after, relocation)?;
|
||||
for saved in group.saved.values_mut() {
|
||||
match saved {
|
||||
|
||||
@@ -18,6 +18,29 @@
|
||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 |
|
||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||
|
||||
## 2026-12-01 整行增删后的后缀复用
|
||||
|
||||
固定字节分行的 TeX8Bit 和 UnicodeScalar 输入支持完整物理行的插入和
|
||||
删除。需要有唯一的行边界,且起点之后的原始输入与已加载行能逐字节
|
||||
核验。支持 LF、CRLF 和 CR。会合和发布时分别换算扫描行、组和条件的
|
||||
来源行号、最终输入位置,以及实际 glyph 的字节坐标。XeTeX 可在作业中
|
||||
切换分行编码,整行编辑目前继续重新执行。
|
||||
|
||||
复用按输入源比较会合点和完成作业的行号观测数。即使前缀已经执行过
|
||||
`\inputlineno`,后缀再次读取仍会被发现。诊断和追踪携带的行号也有
|
||||
记录。字节数不变但换行符位置移动时,同样检查后缀中的行号观测。
|
||||
旧执行记录缺少这项证据时,行边界变化后的后缀重新执行。
|
||||
|
||||
四页作业从各自唯一的旧修订增删整行,实际跳过未变后缀。最终的物理
|
||||
行号及后页 glyph 来源同步换算,原页面无需更新。延迟写出重新读取
|
||||
同一源文件行号时,重新执行并在日志中写入新值。另用等长编辑移动
|
||||
保存令牌的来源行,方向盒警告从第 4 行改为第 5 行。与独立全量的
|
||||
执行、PDF、预览、来源映射、资源和生成日志均对照一致。
|
||||
|
||||
八项来源与扫描单测和十一项管线回归通过。日志及复现入口在
|
||||
`target/p4-physical-line-edit/`。原有资源、文件副作用和状态会合
|
||||
条件继续适用。
|
||||
|
||||
## 2026-12-01 减少后缀拼接的复制
|
||||
|
||||
发布事件列表按最终长度一次分配。来源换算直接更新已有的草稿节点,
|
||||
|
||||
@@ -1917,6 +1917,190 @@ fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() {
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_line_edits_reuse_the_settled_suffix_and_relocate_provenance() {
|
||||
check_whole_line_suffix_edits("whole-line-safe-suffix", 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);
|
||||
}
|
||||
|
||||
fn check_whole_line_suffix_edits(label: &str, observe_delayed_line: bool) {
|
||||
let cwd = directory(label);
|
||||
let entry = cwd.join("main.tex");
|
||||
let delayed = if observe_delayed_line {
|
||||
r"\write16{Suffix line \number\inputlineno}"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let body = |inserted| {
|
||||
format!(
|
||||
r"
|
||||
\tracingstats=2
|
||||
\count42=\inputlineno\relax
|
||||
\shipout\hbox{{Cover}}\relax% Preserve the comment catcode read before either edit.
|
||||
{inserted}\shipout\hbox{{Checkpoint}}\relax
|
||||
\gdef\saved{{Suffix glyphs}}
|
||||
\shipout\hbox{{\saved}}\relax
|
||||
\setbox5=\hbox{{Final{delayed}}}
|
||||
\endinput\shipout\box5\relax\end
|
||||
"
|
||||
)
|
||||
};
|
||||
let final_line = |body: &str| {
|
||||
body.lines()
|
||||
.position(|line| line.starts_with(r"\endinput"))
|
||||
.unwrap()
|
||||
+ 1
|
||||
};
|
||||
let comment = "% 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 mut input = request(&cwd).observe_generated_initial();
|
||||
input.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let donor = session
|
||||
.compile(input.clone().with_project(project.clone()))
|
||||
.unwrap();
|
||||
let donor_execution = &donor.execution.execution;
|
||||
let donor_line = final_line(&original);
|
||||
assert_eq!(donor_execution.input_position, Some((0, donor_line)));
|
||||
|
||||
let changed = body(edited);
|
||||
let current_line = final_line(&changed);
|
||||
assert_eq!(
|
||||
current_line,
|
||||
if edited.is_empty() {
|
||||
donor_line - 1
|
||||
} else {
|
||||
donor_line + 1
|
||||
}
|
||||
);
|
||||
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 project = project
|
||||
.with_file_edits(2, [(entry.clone(), Arc::from(source.into_bytes()))].into())
|
||||
.unwrap();
|
||||
let input = input.with_project(project);
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let execution = &updated.execution.execution;
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(!work.reused_completion, "{work:?}");
|
||||
assert!(
|
||||
work.reused_frontier.is_some_and(|frontier| frontier >= prefix_read_end),
|
||||
"{work:?}"
|
||||
);
|
||||
assert_eq!(execution.input_position, Some((0, current_line)));
|
||||
assert_eq!(execution.state.count(42), 3);
|
||||
assert_eq!(updated.pages.len(), 4);
|
||||
assert!(updated.source_map.pages[2].entries.iter().any(|glyph| {
|
||||
glyph.source.tokens.iter().any(|origin| origin.span.start == glyph_offset)
|
||||
}));
|
||||
|
||||
if observe_delayed_line {
|
||||
// The write's tokens were saved in the preceding box. The
|
||||
// terminal line ends input before shipout, so no later checkpoint
|
||||
// can legitimately skip work after the delayed observation.
|
||||
assert_eq!(work.reused_suffix_steps, 0, "{work:?}");
|
||||
for (execution, line) in [(donor_execution, donor_line), (execution, current_line)] {
|
||||
let expected = format!("Suffix line {line}\n");
|
||||
assert!(execution.events.iter().any(|event| {
|
||||
matches!(event, texrra_tex_core::execution::Event::Write { text, .. } if text == &expected)
|
||||
}), "{expected:?}");
|
||||
}
|
||||
} else {
|
||||
assert!(work.reused_suffix_steps > 0, "{work:?}");
|
||||
assert!(updated.shipout_layout_work.reused_pages >= 2, "{work:?}");
|
||||
}
|
||||
assert!(
|
||||
updated.preview_since(Some(donor.revision())).unwrap().pages.is_empty(),
|
||||
"a physical source line moved without changing any page paint"
|
||||
);
|
||||
|
||||
let log = fs::read(cwd.join("job.log")).unwrap();
|
||||
let independent = NativeCompiler::default().compile(input).unwrap();
|
||||
assert_eq!(execution, &independent.execution.execution);
|
||||
assert_eq!(updated.execution.source_versions, independent.execution.source_versions);
|
||||
assert_eq!(updated.resources.trace, independent.resources.trace);
|
||||
assert_eq!(updated.resources.stream_io, independent.resources.stream_io);
|
||||
assert_eq!(updated.export_diagnostics, independent.export_diagnostics);
|
||||
assert_eq!(updated.pdf, independent.pdf);
|
||||
assert_eq!(updated.pages, independent.pages);
|
||||
assert_eq!(updated.source_map.sources, independent.source_map.sources);
|
||||
assert_eq!(updated.source_map.pages, independent.source_map.pages);
|
||||
assert_eq!(
|
||||
updated.preview_since(None).unwrap().pages,
|
||||
independent.preview_since(None).unwrap().pages
|
||||
);
|
||||
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_length_line_edits_refresh_suffix_diagnostics_from_saved_prefix_tokens() {
|
||||
let cwd = directory("equal-length-suffix-line-diagnostic");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |before, after| {
|
||||
format!(
|
||||
"\n\
|
||||
\\TeXXeTstate=1\\relax\n\
|
||||
\\shipout\\hbox{{Cover}}\\relax\n\
|
||||
\\relax{before}\\afterassignment}}\\relax{after}\\relax\n\
|
||||
\\shipout\\hbox{{Checkpoint}}\\relax\n\
|
||||
\\endinput\\shipout\\hbox{{\\beginR X\\count0=1\\relax\\end\n"
|
||||
)
|
||||
};
|
||||
// The scheduled right brace keeps its byte offset and closes the last
|
||||
// box after the assignment. Its source line supplies the LR warning.
|
||||
let original = body(" ", "\n");
|
||||
let changed = body("\n", " ");
|
||||
let scheduled_brace = |body: &str| {
|
||||
body.find(r"\afterassignment}").unwrap() + r"\afterassignment".len()
|
||||
};
|
||||
let warning = |body: &str| {
|
||||
let line = body[..scheduled_brace(body)].matches('\n').count() + 1;
|
||||
format!("(1 missing, 0 extra) detected at line {line}\n")
|
||||
};
|
||||
assert_eq!(original.len(), changed.len());
|
||||
assert_eq!(scheduled_brace(&original), scheduled_brace(&changed));
|
||||
assert_ne!(warning(&original), warning(&changed));
|
||||
|
||||
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &original)).unwrap();
|
||||
let mut input = request(&cwd).observe_generated_initial();
|
||||
input.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
session.compile(input.clone().with_project(project.clone())).unwrap();
|
||||
let log_file = cwd.join("job.log");
|
||||
let donor_log = fs::read_to_string(&log_file).unwrap();
|
||||
assert!(donor_log.contains(&warning(&original)), "{donor_log}");
|
||||
|
||||
let source = format!("{HEADER}{changed}");
|
||||
let cover = source.find(r"\shipout\hbox{Cover}").unwrap();
|
||||
let project = project
|
||||
.with_file_edits(2, [(entry, Arc::from(source.into_bytes()))].into())
|
||||
.unwrap();
|
||||
let input = input.with_project(project);
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(work.reused_frontier.is_some_and(|frontier| frontier >= cover), "{work:?}");
|
||||
assert_eq!(work.reused_suffix_steps, 0, "{work:?}");
|
||||
let updated_log = fs::read_to_string(&log_file).unwrap();
|
||||
assert!(updated_log.contains(&warning(&changed)), "{updated_log}");
|
||||
assert!(!updated_log.contains(&warning(&original)), "{updated_log}");
|
||||
|
||||
let cold = NativeCompiler::default().compile(input).unwrap();
|
||||
assert_eq!(updated.execution.execution, cold.execution.execution);
|
||||
assert_eq!(updated_log, fs::read_to_string(log_file).unwrap());
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocated_suffix_cannot_reuse_layouts_from_a_different_donor() {
|
||||
let cwd = directory("relocated-suffix-older-donor");
|
||||
|
||||
Reference in new issue
Block a user