diff --git a/crates/texrra-tex-core/src/execution/boxes/interword.rs b/crates/texrra-tex-core/src/execution/boxes/interword.rs index 5d44d2e..04453db 100644 --- a/crates/texrra-tex-core/src/execution/boxes/interword.rs +++ b/crates/texrra-tex-core/src/execution/boxes/interword.rs @@ -8,7 +8,7 @@ use std::{ops::Range, sync::Arc}; #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub(in crate::execution) struct Run { pub(super) nodes: Range, - pub(super) word: Arc, + pub(in crate::execution) word: Arc, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(super) effects: Vec, } diff --git a/crates/texrra-tex-core/src/execution/engine/continuation.rs b/crates/texrra-tex-core/src/execution/engine/continuation.rs index f1a5b7a..a888498 100644 --- a/crates/texrra-tex-core/src/execution/engine/continuation.rs +++ b/crates/texrra-tex-core/src/execution/engine/continuation.rs @@ -1,9 +1,11 @@ +use super::super::source_relocation::SourceRelocation; use super::*; mod material; +mod relocate; use material::MaterialReuse; impl InputFrame { - fn same_at_shipout(&self, other: &Self) -> bool { + fn same_at_shipout(&self, other: &Self, relocation: Option<&SourceRelocation>) -> bool { match (self, other) { ( Self::Source { @@ -22,7 +24,11 @@ impl InputFrame { group_boundary: bg, conditional_boundary: bc, }, - ) => (a, ae, at, ag, ac) == (b, be, bt, bg, bc) && am.same_unread_input(bm), + ) => (a, ae, at, ag, ac) == (b, be, bt, bg, bc) + && match relocation.filter(|map| map.source() == *a) { + Some(map) => am.same_unread_input_relocated(bm, map), + None => am.same_unread_input(bm), + }, ( Self::Tokens { tokens: a, @@ -90,7 +96,6 @@ impl EntryCheckpoint { || self.entry != prior.entry || self.initial_depth != prior.initial_depth || self.incoming_state != prior.incoming_state - || self.frontier != prior.frontier || self.pages_processed != prior.pages_processed || completed.incoming_state != prior.incoming_state || completed.reads_event_history @@ -101,9 +106,6 @@ impl EntryCheckpoint { } let current = &self.executor; let old = &prior.executor; - if !same_kernel_continuation(current, old) { - return None; - } if current.sources.len() != old.sources.len() || current .sources @@ -112,7 +114,7 @@ impl EntryCheckpoint { .enumerate() .any(|(id, (new, old))| { if id == self.entry { - new.name != old.name || new.data.len() != old.data.len() + new.name != old.name } else { new != old } @@ -121,6 +123,24 @@ impl EntryCheckpoint { { return None; } + let previous_bytes = &old.sources[self.entry].data; + let current_bytes = ¤t.sources[self.entry].data; + let entry_sizes = (previous_bytes.len() != current_bytes.len()) + .then_some((previous_bytes.len(), current_bytes.len())); + let relocation = match entry_sizes { + Some(_) => { + let map = SourceRelocation::new(self.entry, previous_bytes, current_bytes)?; + if map.relocate_offset(prior.frontier) != Some(self.frontier) { + return None; + } + Some(map) + } + None if self.frontier == prior.frontier => None, + None => return None, + }; + if !same_kernel_continuation(current, old, relocation.as_ref()) { + return None; + } let offset = StepOffset::new(old.steps, current.steps); let steps = offset.apply(completed.steps)?; // Kernel work only advances the step counter. A successful suffix @@ -131,20 +151,14 @@ impl EntryCheckpoint { let mut sources = completed.sources.clone(); sources[self.entry] = current.sources[self.entry].clone(); let tail = completed.events.get(old.events.len()..)?; - if completed.accounts_event_history && !current.equivalent_accounting_history(old) { + if completed.accounts_event_history + && !current.equivalent_accounting_history_with_entry_sizes(old, entry_sizes) + { return None; } // The joined events are published results. Resumption always starts // from a live checkpoint, whose original shared allocations stay intact. - let mut events = current.events.clone().into_vec(); - if offset.is_identity() { - events.extend_from_slice(tail); - } else { - for event in tail { - events.push(offset_event_steps(event, offset)?); - } - } - Some(Execution { + let mut execution = Execution { format_dumped: completed.format_dumped, format_pdf_images: completed.format_pdf_images.clone(), job_name: completed.job_name.clone(), @@ -152,7 +166,7 @@ impl EntryCheckpoint { native_page: completed.native_page.clone(), split_discards: completed.split_discards.clone(), after_assignment: completed.after_assignment.clone(), - events, + events: current.events.clone().into_vec(), state: completed.state.clone(), io: completed.io.clone(), input_position: completed.input_position, @@ -166,7 +180,17 @@ impl EntryCheckpoint { steps, reads_event_history: false, accounts_event_history: completed.accounts_event_history, - }) + }; + if let Some((map, sizes)) = relocation.as_ref().zip(entry_sizes) { + relocate::append_suffix(&mut execution, tail, offset, map, sizes, old.sources.len())?; + } else if offset.is_identity() { + execution.events.extend_from_slice(tail); + } else { + for event in tail { + execution.events.push(offset_event_steps(event, offset)?); + } + } + Some(execution) } /// Carry later checkpoints from the suffix accepted by /// splice_settled_suffix into this revision. The host must still replay @@ -176,6 +200,12 @@ impl EntryCheckpoint { prior: &'a Self, completed: &Execution, ) -> Option Option + 'a> { + // A carried executor still contains scanner positions from the old source. + if self.executor.sources[self.entry].data.len() + != prior.executor.sources[prior.entry].data.len() + { + return None; + } // A restored checkpoint may later be asked to account for its // history, even if the job that furnished the suffix did not. if !completed.accounts_event_history @@ -306,7 +336,11 @@ fn is_idle_continuation(e: &Executor) -> bool { && !e.reads_event_history } -fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { +fn same_kernel_continuation( + current: &Executor, + prior: &Executor, + relocation: Option<&SourceRelocation>, +) -> bool { // Every field belongs to one of these checks. Adding kernel state requires // an explicit decision here before a later execution may be skipped. macro_rules! same_values { @@ -321,20 +355,19 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { true $(&& *$value == prior.$value)+ }}; } + if !is_idle_continuation(current) || !is_idle_continuation(prior) { + return false; + } if !same_values!( [ - state, limits, interaction_mode, stream_sources, - generated_inputs, reads, reads_tracing_macros, - conditionals, in_csname, command_trace_mode, ligature_carry, - current, expression_depth, scanner_depth, scanner_status, @@ -347,25 +380,17 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { pdf_space_font, pdf_loaded_space_font, pdf_virtual_fonts, - pdf_catalog_tokens, - pdf_outlines, pdf_outline_payload, - pdf_info_tokens, restored_pdf_image_count, format_image_warnings, pdf_force_pagebox_warned, input_position, - vertical, box_nodes_created, material_charge, mark_cells_created, diagnostic_bytes, - after_assignment, after_group_tokens, math_tokens_processed, - native_page, - split_discards, - pending_shipouts, shipped_pages, job_ended, fresh_job, @@ -378,6 +403,18 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { accounts_event_history, ], [ + state, + generated_inputs, + conditionals, + current, + pdf_catalog_tokens, + pdf_outlines, + pdf_info_tokens, + vertical, + after_assignment, + native_page, + split_discards, + pending_shipouts, inputs, sources, steps, @@ -402,30 +439,49 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool { ) { return false; } - if !is_idle_continuation(current) || !is_idle_continuation(prior) { - return false; - } #[cfg(all(target_os = "linux", target_env = "gnu"))] if current.pdf_last_match.as_deref() != prior.pdf_last_match.as_deref() { return false; } - current - .xdv_annotations - .same_idle_state(&prior.xdv_annotations) + if current.events.len() != prior.events.len() + || current.meaning_reads.len() != prior.meaning_reads.len() + || !current.meaning_reads.keys().all(|name| prior.meaning_reads.contains_key(name)) + || current.inputs.len() != prior.inputs.len() + { + return false; + } + let relocated; + let prior = if let Some(map) = relocation { + relocated = match relocate::kernel_continuation(prior, map) { + Some(executor) => executor, + None => return false, + }; + &relocated + } else { + prior + }; + current.state == prior.state + && current.generated_inputs == prior.generated_inputs + && current.conditionals == prior.conditionals + && current.current == prior.current + && current.pdf_catalog_tokens == prior.pdf_catalog_tokens + && current.pdf_outlines == prior.pdf_outlines + && current.pdf_info_tokens == prior.pdf_info_tokens + && current.vertical == prior.vertical + && current.after_assignment == prior.after_assignment + && current.native_page == prior.native_page + && current.split_discards == prior.split_discards + && current.pending_shipouts == prior.pending_shipouts + && current + .xdv_annotations + .same_idle_state(&prior.xdv_annotations) && current.xdv_text.same_state(&prior.xdv_text) && current .pdf_navigation_geometry .same_state(&prior.pdf_navigation_geometry) - && current.events.len() == prior.events.len() - && current.meaning_reads.len() == prior.meaning_reads.len() - && current - .meaning_reads - .keys() - .all(|name| prior.meaning_reads.contains_key(name)) - && current.inputs.len() == prior.inputs.len() && current .inputs .iter() .zip(&prior.inputs) - .all(|(a, b)| a.same_at_shipout(b)) + .all(|(a, b)| a.same_at_shipout(b, relocation)) } diff --git a/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs new file mode 100644 index 0000000..cbc1a4e --- /dev/null +++ b/crates/texrra-tex-core/src/execution/engine/continuation/relocate.rs @@ -0,0 +1,148 @@ +use super::*; +use crate::execution::{ + source_relocation_events::EventRelocation, state::source_relocation::relocate_macro, +}; + +pub(super) fn kernel_continuation(prior: &Executor, map: &SourceRelocation) -> Option { + let mut prior = prior.clone(); + let mut relocation = EventRelocation::new(map); + prior.current = map.relocate_span(prior.current)?; + prior.state = prior.state.relocate_source(&mut relocation)?; + relocate_generated(&mut prior.generated_inputs, map)?; + for conditional in &mut prior.conditionals { + conditional.span = map.relocate_span(conditional.span)?; + } + + let mut macros = std::collections::HashMap::new(); + for frame in &mut prior.inputs { + match frame { + InputFrame::Tokens { tokens, .. } => match tokens { + InputTokens::One(token) => token.token = relocation.relocate_token(&token.token)?, + InputTokens::Many(tokens) => { + for token in tokens { + token.token = relocation.relocate_token(&token.token)?; + } + } + }, + InputFrame::Macro { + definition, + arguments, + call, + .. + } => { + *definition = relocate_macro(definition, &mut relocation, &mut macros)?; + for tokens in arguments { + *tokens = relocation.relocate_tokens(tokens)?; + } + *call = map.relocate_span(*call)?; + } + InputFrame::Argument { tokens, call, .. } => { + *tokens = relocation.relocate_tokens(tokens)?; + *call = map.relocate_span(*call)?; + } + InputFrame::Hook { tokens, .. } => *tokens = relocation.relocate_tokens(tokens)?, + // Keep the old raw scanners for the byte and decoder comparison. + InputFrame::Source { .. } | InputFrame::Boundary => {} + } + } + relocate_tokens(&mut prior.pdf_catalog_tokens, &mut relocation)?; + relocate_tokens(&mut prior.pdf_info_tokens, &mut relocation)?; + for outline in &mut prior.pdf_outlines { + relocate_tokens(&mut outline.attributes, &mut relocation)?; + } + if let Some(token) = &mut prior.after_assignment { + *token = relocation.relocate_token(token)?; + } + relocate_vertical(&mut prior.vertical.nodes, &mut relocation)?; + relocate_vertical(&mut prior.split_discards, &mut relocation)?; + relocate_page(&mut prior.native_page, &mut relocation)?; + for value in &mut prior.pending_shipouts { + *value = relocation.relocate_box(value)?; + } + Some(prior) +} + +pub(super) fn append_suffix( + execution: &mut Execution, + tail: &[Event], + offset: StepOffset, + map: &SourceRelocation, + (previous_bytes, current_bytes): (usize, usize), + source_count: usize, +) -> Option<()> { + let mut relocation = EventRelocation::new(map); + for event in tail { + if let Event::Statistics(report) = event { + if let StatisticsPhase::Shipout { before, after } = &report.phase { + // The active entry was the only source frame at convergence. + // If a report follows any later input open, its mouth payload + // alone cannot prove whether that frame is still present. + if before.source_files != source_count || after.source_files != source_count { + return None; + } + } + let mut report = report + .with_step_offset(offset)? + .with_suffix_entry_resize(previous_bytes, current_bytes)?; + report.span = map.relocate_span(report.span)?; + execution.events.push(Event::Statistics(Box::new(report))); + } else { + execution.events.push(relocation.relocate_event(event)?); + } + } + let state = execution.state.relocate_source(&mut relocation)?; + if state != execution.state { + execution.outgoing_state = state.fingerprint(); + } + execution.state = state; + relocate_page(&mut execution.native_page, &mut relocation)?; + relocate_vertical(&mut execution.split_discards, &mut relocation)?; + if let Some(token) = &mut execution.after_assignment { + *token = relocation.relocate_token(token)?; + } + relocate_generated(&mut execution.generated_inputs, map)?; + for image in &mut execution.format_pdf_images { + relocate_tokens(&mut image.attributes, &mut relocation)?; + } + Some(()) +} + +fn relocate_generated( + generated: &mut BTreeMap, + map: &SourceRelocation, +) -> Option<()> { + for input in generated.values_mut() { + input.origin = map.relocate_span(input.origin)?; + } + Some(()) +} + +fn relocate_page( + page: &mut Option, + relocation: &mut EventRelocation<'_>, +) -> Option<()> { + if let Some(page) = page { + relocate_vertical(&mut page.nodes, relocation)?; + relocate_vertical(page.contributions.make_contiguous(), relocation)?; + relocate_vertical(&mut page.discards, relocation)?; + relocate_vertical(&mut page.insertions.held, relocation)?; + } + Some(()) +} + +fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> { + for token in tokens { + *token = relocation.relocate_token(token)?; + } + Some(()) +} + +fn relocate_vertical( + nodes: &mut [NativeVerticalNode], + relocation: &mut EventRelocation<'_>, +) -> Option<()> { + for node in nodes { + *node = relocation.relocate_vertical(node)?; + } + Some(()) +} diff --git a/crates/texrra-tex-core/src/execution/engine/statistics.rs b/crates/texrra-tex-core/src/execution/engine/statistics.rs index 87d8b64..232b8aa 100644 --- a/crates/texrra-tex-core/src/execution/engine/statistics.rs +++ b/crates/texrra-tex-core/src/execution/engine/statistics.rs @@ -200,6 +200,14 @@ impl Executor { } pub(super) fn equivalent_accounting_history(&self, old: &Self) -> bool { + self.equivalent_accounting_history_with_entry_sizes(old, None) + } + + pub(super) fn equivalent_accounting_history_with_entry_sizes( + &self, + old: &Self, + entry_sizes: Option<(usize, usize)>, + ) -> bool { // These containers may reintroduce previously retained allocations // that are outside the accounting walk at this boundary. let fully_visited = |engine: &Self| { @@ -219,6 +227,13 @@ impl Executor { let old_live = old.collect_live_usage(None, None, collector().tracking_aliases()); // The splice translates steps separately and checks the job limit. live.usage.steps = old_live.usage.steps; + if let Some((previous, current)) = entry_sizes { + let restore = |bytes: usize| bytes.checked_sub(current)?.checked_add(previous); + let Some(source) = restore(live.usage.source_payload_bytes) else { return false; }; + let Some(mouth) = restore(live.usage.mouth_payload_bytes) else { return false; }; + live.usage.source_payload_bytes = source; + live.usage.mouth_payload_bytes = mouth; + } live.has_equivalent_history(&old_live, &history, &old_history) }) } diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index f3abe94..66c0501 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -48,6 +48,8 @@ mod reconstitute; mod registers; mod rule; mod session; +mod source_relocation; +mod source_relocation_events; mod state; mod statistics; mod vertical_break; diff --git a/crates/texrra-tex-core/src/execution/mouth.rs b/crates/texrra-tex-core/src/execution/mouth.rs index c2e6258..6bd6d9f 100644 --- a/crates/texrra-tex-core/src/execution/mouth.rs +++ b/crates/texrra-tex-core/src/execution/mouth.rs @@ -1,7 +1,10 @@ use super::{CatCode, CommandName, Dependency, DependencyReads, Span, State, Token, TokenKind}; use std::sync::Arc; -use super::xe_encoding::{Character, Encoding}; +use super::{ + source_relocation::SourceRelocation, + xe_encoding::{Character, Encoding}, +}; #[derive(Clone, PartialEq, Eq)] struct XePhysical { @@ -252,6 +255,38 @@ mod tests { assert!(!first_line.matches_loaded_prefix(b"\r\0A\0")); } + #[test] + fn relocated_mouth_requires_an_unchanged_loaded_line() { + use super::super::InputProfile; + + for profile in [InputProfile::TeX8Bit, InputProfile::UnicodeScalar, InputProfile::XeTeX] { + for (old_data, current_data) in [ + (b"alpha\r\nsame\r\nnext\r\n".as_slice(), b"alfa\r\nsame\r\nnext\r\n".as_slice()), + (b"alfa\r\nsame\r\nnext\r\n".as_slice(), b"alpha\r\nsame\r\nnext\r\n".as_slice()), + ] { + let relocation = SourceRelocation::new(4, old_data, current_data).unwrap(); + let mut old = Mouth::new(4, old_data.to_vec(), profile); + let mut current = Mouth::new(4, current_data.to_vec(), profile); + let state = State::default().with_input_profile(profile); + let mut reads = DependencyReads::default(); + assert!(old.load_line(&state, &mut reads).unwrap()); + assert!(current.load_line(&state, &mut reads).unwrap()); + assert!(!current.same_unread_input_relocated(&old, &relocation)); + + assert!(old.load_line(&state, &mut reads).unwrap()); + assert!(current.load_line(&state, &mut reads).unwrap()); + assert!(current.same_unread_input_relocated(&old, &relocation)); + + if profile == InputProfile::XeTeX { + current.change_encoding(Encoding::Bytes); + assert!(!current.same_unread_input_relocated(&old, &relocation)); + } + assert!(current.load_line(&state, &mut reads).unwrap()); + assert!(!current.same_unread_input_relocated(&old, &relocation)); + } + } + } + #[test] fn physical_line_endings_and_utf8_byte_offsets_are_preserved() { let result = tokens("é界 \r\nB\rC"); @@ -297,21 +332,83 @@ pub(super) struct Mouth { } impl Mouth { - pub(super) fn same_unread_input(&self, other: &Self) -> bool { + fn same_unread_state(&self, other: &Self) -> bool { self.source == other.source && self.profile == other.profile - && self.offset == other.offset - && self.line == other.line && self.cursor == other.cursor && 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.xe == other.xe && self.invalid_utf8 == other.invalid_utf8 + } + + pub(super) fn same_unread_input(&self, other: &Self) -> bool { + self.same_unread_state(other) + && self.offset == other.offset + && self.line == other.line + && self.xe == other.xe && self.data[self.offset..] == other.data[other.offset..] } + pub(super) fn same_unread_input_relocated( + &self, + old: &Self, + relocation: &SourceRelocation, + ) -> bool { + if self.source != relocation.source() + || !self.same_unread_state(old) + || self.physical_frontier().is_none() + || old.physical_frontier().is_none() + || relocation.relocate_offset(old.offset) != Some(self.offset) + { + return false; + } + + 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 + && current.autodetected == previous.autodetected + && current.skip_lf == previous.skip_lf + && current.terminated + && previous.terminated => + { + (current.line_start, previous.line_start) + } + (None, None) => { + let Some(start) = self.byte_line_start() else { + return false; + }; + let Some(old_start) = old.byte_line_start() else { + return false; + }; + (start, old_start) + } + _ => return false, + }; + + // 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) + && 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) + }) + } + + fn byte_line_start(&self) -> Option { + let prefix = &self.data[..self.offset]; + let content = prefix + .strip_suffix(b"\r\n") + .or_else(|| prefix.strip_suffix(b"\n")) + .or_else(|| prefix.strip_suffix(b"\r"))?; + Some(content.iter().rposition(|b| matches!(b, b'\r' | b'\n')).map_or(0, |i| i + 1)) + } + pub(super) fn physical_frontier(&self) -> Option { (matches!(self.line_breaks, LineBreaks::Physical) && !self.end_after_line && self.offset > 0) .then_some(self.offset) diff --git a/crates/texrra-tex-core/src/execution/source_relocation.rs b/crates/texrra-tex-core/src/execution/source_relocation.rs new file mode 100644 index 0000000..52d1b3c --- /dev/null +++ b/crates/texrra-tex-core/src/execution/source_relocation.rs @@ -0,0 +1,169 @@ +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. +pub(super) struct SourceRelocation { + source: usize, + unchanged_prefix: usize, + old_suffix: usize, + current_suffix: usize, + old_len: usize, + first_unchanged_line: usize, +} + +impl SourceRelocation { + pub(super) fn new(source: usize, old: &[u8], current: &[u8]) -> Option { + if old.len() == current.len() { + return None; + } + let unchanged_prefix = old.iter().zip(current).take_while(|(a, b)| a == b).count(); + let unchanged_suffix = old[unchanged_prefix..] + .iter() + .rev() + .zip(current[unchanged_prefix..].iter().rev()) + .take_while(|(a, b)| a == b) + .count(); + 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) + // 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 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 + }; + Some(Self { + source, + unchanged_prefix, + old_suffix, + current_suffix, + old_len: old.len(), + first_unchanged_line: next_break + delimiter_width, + }) + } + + pub(super) fn source(&self) -> usize { + self.source + } + + pub(super) fn relocate_offset(&self, old_offset: usize) -> Option { + let one_side_is_empty = self.unchanged_prefix == self.old_suffix + || self.unchanged_prefix == self.current_suffix; + if one_side_is_empty + && (old_offset == self.unchanged_prefix || old_offset == self.old_suffix) + { + // At an insertion, a point could belong to either side. At a + // deletion, two distinct points would map to the same position. + return None; + } + if old_offset <= self.unchanged_prefix { + Some(old_offset) + } else { + self.relocate_suffix_offset(old_offset) + } + } + + pub(super) fn relocate_span(&self, span: Span) -> Option { + if span.source != self.source { + return Some(span); + } + if span.start == span.end { + let offset = self.relocate_offset(span.start)?; + return Some(Span { + start: offset, + end: offset, + ..span + }); + } + if span.start > span.end { + return None; + } + if span.end <= self.unchanged_prefix { + return Some(span); + } + Some(Span { + start: self.relocate_suffix_offset(span.start)?, + end: self.relocate_suffix_offset(span.end)?, + ..span + }) + } + + pub(super) fn relocate_loaded_line(&self, old_start: usize) -> Option { + if old_start < self.first_unchanged_line { + return None; + } + self.relocate_suffix_offset(old_start) + } + + fn relocate_suffix_offset(&self, old_offset: usize) -> Option { + if old_offset > self.old_len { + return None; + } + self.current_suffix + .checked_add(old_offset.checked_sub(self.old_suffix)?) + } +} + +fn is_line_break(byte: u8) -> bool { + matches!(byte, b'\r' | b'\n') +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relocation_distinguishes_both_sides_of_an_insertion() { + let map = SourceRelocation::new(4, b"abde\r\nnext\r\n", b"abcde\r\nnext\r\n").unwrap(); + let span = |start, end| Span { + source: 4, + start, + end, + }; + assert_eq!(map.relocate_span(span(0, 2)), Some(span(0, 2))); + 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)); + } + + #[test] + fn relocation_rejects_deleted_bytes_and_changed_line_boundaries() { + let map = SourceRelocation::new(4, b"abcde\nnext\n", b"abe\nnext\n").unwrap(); + let span = |start, end| Span { + source: 4, + start, + end, + }; + assert_eq!(map.relocate_span(span(2, 4)), None); + assert_eq!(map.relocate_span(span(2, 2)), None); + assert_eq!(map.relocate_span(span(4, 4)), None); + assert_eq!(map.relocate_span(span(4, 5)), Some(span(2, 3))); + let other = Span { + source: 9, + start: 2, + end: 4, + }; + assert_eq!(map.relocate_span(other), Some(other)); + for (old, current) in [ + (b"abcde\nnext\n".as_slice(), b"abc\nde\nnext\n".as_slice()), + (b"a\r\nnext\n".as_slice(), b"a\rX\nnext\n".as_slice()), + (b"a\rX\nnext\n".as_slice(), b"a\r\nnext\n".as_slice()), + ] { + assert!(SourceRelocation::new(4, old, current).is_none()); + } + } +} diff --git a/crates/texrra-tex-core/src/execution/source_relocation_events.rs b/crates/texrra-tex-core/src/execution/source_relocation_events.rs new file mode 100644 index 0000000..03882ea --- /dev/null +++ b/crates/texrra-tex-core/src/execution/source_relocation_events.rs @@ -0,0 +1,638 @@ +//! Checked relocation of source-bearing objects retained by native execution. +use super::{source_relocation::SourceRelocation, *}; +use crate::{ + HorizontalBox, HorizontalItem, Paragraph, + math_engine_tex::{MathGeometry, MathItem, PositionedItem}, + opentype::OpenTypeRun, + pdf_device::{ + PdfGraphics, + forms::ShippedForm, + links::{DestinationId, LinkAction, LinkNode, LinkStart}, + }, + provenance::PaintSource, +}; +use std::{collections::HashMap, sync::Arc}; + +type Shared = HashMap<*const T, Arc>; + +pub(super) struct EventRelocation<'a> { + map: &'a SourceRelocation, + text_lists: Shared>, + vertical_lists: Shared>, + diagnostic_lists: Shared<[DiagnosticNode]>, + token_lists: Shared<[Token]>, + opentype_runs: Shared, +} + +impl<'a> EventRelocation<'a> { + pub(super) fn new(map: &'a SourceRelocation) -> Self { + Self { + map, + text_lists: HashMap::new(), + vertical_lists: HashMap::new(), + diagnostic_lists: HashMap::new(), + token_lists: HashMap::new(), + opentype_runs: HashMap::new(), + } + } + + pub(super) fn relocate_event(&mut self, event: &Event) -> Option { + self.relocated(event) + } + + pub(super) fn relocate_box(&mut self, packed: &NativeBox) -> Option { + self.relocated(packed) + } + + pub(super) fn relocate_vertical( + &mut self, + node: &NativeVerticalNode, + ) -> Option { + self.relocated(node) + } + + pub(super) fn relocate_token(&mut self, token: &Token) -> Option { + self.relocated(token) + } + + pub(super) fn relocate_tokens(&mut self, tokens: &Arc<[Token]>) -> Option> { + self.relocated(tokens) + } + + fn relocated(&mut self, value: &T) -> Option { + let mut updated = value.clone(); + updated.relocate(self)?; + Some(updated) + } +} + +trait Relocate { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()>; +} + +impl Relocate for Box { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + self.as_mut().relocate(context) + } +} +impl Relocate for Option { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + if let Some(value) = self { + value.relocate(context)?; + } + Some(()) + } +} +impl Relocate for Vec { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + self.as_mut_slice().relocate(context) + } +} +impl Relocate for [T] { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + self.iter_mut().try_for_each(|node| node.relocate(context)) + } +} + +impl Relocate for Span { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + *self = context.map.relocate_span(*self)?; + Some(()) + } +} + +// The retained input event/state graphs own the original allocations for the +// whole relocation. Cache by that identity to keep aliases shared across the +// shipped lists, paragraph views and diagnostics. Reuse an original allocation +// when every retained location in it is unchanged. +macro_rules! relocate_shared { + ($ty:ty, $cache:ident, $copy:expr) => { + impl Relocate for Arc<$ty> { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + let original = Arc::as_ptr(self); + if let Some(updated) = context.$cache.get(&original) { + *self = updated.clone(); + } else { + let mut updated = $copy(self.as_ref()); + updated.relocate(context)?; + if updated != **self { + *self = Arc::from(updated); + } + context.$cache.insert(original, self.clone()); + } + Some(()) + } + } + }; +} +relocate_shared!(Vec, text_lists, Clone::clone); +relocate_shared!(Vec, vertical_lists, Clone::clone); +relocate_shared!( + [DiagnosticNode], + diagnostic_lists, + <[DiagnosticNode]>::to_vec +); +relocate_shared!([Token], token_lists, <[Token]>::to_vec); +relocate_shared!(OpenTypeRun, opentype_runs, Clone::clone); + +// List fields without provenance explicitly so added fields in these structs +// have to be reviewed before reuse can compile. +macro_rules! relocate_fields { + ($ty:ty { $($field:ident),+ ; $($unchanged:ident),* $(,)? }) => { + impl Relocate for $ty { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + let Self { $($field,)+ $($unchanged: _,)* } = self; + $($field.relocate(context)?;)+ + Some(()) + } + } + }; +} + +relocate_fields!(Token { span, invocation; kind }); +relocate_fields!(TokenOrigin { span, invocation; }); +relocate_fields!(PaintSource { tokens; derivations }); +relocate_fields!(NativeRule { span, origin; derivation, width, height, depth }); +relocate_fields!(NativeMark { span, tokens; class }); +relocate_fields!(NativeAdjustment { nodes; pre }); +relocate_fields!(NativeInsertion { + span, nodes; class, natural_size, split_top, split_depth, float_cost +}); +relocate_fields!(LeaderGlue { pattern; glue, mode }); +relocate_fields!(OutputNode { span, operation; }); +relocate_fields!(LinkStart { attributes, action; object_number, width, height, depth }); +relocate_fields!(PositionedItem { source, item; x, y }); +relocate_fields!(MathGeometry { items; metrics }); +relocate_fields!(HorizontalBox { + native_box, math_geometry; width, height, depth, character, italic, font, + math, link, size, raise, color, background, frame +}); +relocate_fields!(MissingGlyph { span; font, slot, tracing, destination, message }); +relocate_fields!(ShipoutSpecial { span; position, bytes }); +relocate_fields!(ShippedForm { canvas; form, resource_number, attributes }); +relocate_fields!(DiagnosticBox { nodes; kind, display, width, height, depth, shift, setting }); +relocate_fields!(PageTraceReport { span; trace, text, destination }); +relocate_fields!(ParagraphTraceReport { span; records, text, destination }); + +impl Relocate for Event { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Character(value) => value.relocate(context), + Self::Paragraph(span) | Self::Message { span, .. } | Self::Write { span, .. } => { + span.relocate(context) + } + Self::DeferredOutput(value) => value.relocate(context), + Self::MissingGlyph(value) => value.relocate(context), + Self::BuiltParagraph(value) => value.relocate(context), + Self::BuiltMath(value) => value.relocate(context), + Self::BuiltDisplay(value) => value.relocate(context), + Self::VerticalMaterial(value) => value.relocate(context), + Self::Shipout(value) => value.relocate(context), + Self::PdfForm(value) => value.relocate(context), + Self::PageTrace(value) => value.relocate(context), + Self::ParagraphTrace(value) => value.relocate(context), + // The caller handles typed resource statistics separately. Show + // events retain a scanner transcript that needs its own proof. + Self::Statistics(_) + | Self::Show(_) + | Self::ShowBox(_) + | Self::ShowRedirected { .. } => None, + Self::PdfImageObject(_) + | Self::ShipoutTrace { .. } + | Self::AssignmentTrace { .. } + | Self::RestoreTrace { .. } + | Self::CommandTrace { .. } + | Self::MacroTrace { .. } + | Self::PseudoInput { .. } + | Self::ConditionalTrace { .. } + | Self::GroupTrace { .. } => Some(()), + } + } +} + +impl Relocate for NativeShipout { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + let Self { + box_node, + specials, + pdf_special_images, + device: _, + dvi: _, + pdf_objects: _, + font_overrides: _, + virtual_glyphs: _, + pdf_font_bindings: _, + pdf_color_start: _, + pdf_color_steps: _, + pdf_graphics_steps, + xdv_color_steps: _, + pdf_background: _, + pdf_text_spaces: _, + pdf_resource_entries: _, + pdf_page_attributes: _, + pdf_links: _, + } = self; + box_node.relocate(context)?; + specials.relocate(context)?; + pdf_graphics_steps.relocate(context)?; + for (_, origin) in pdf_special_images.values_mut() { + origin.relocate(context)?; + } + Some(()) + } +} + +impl Relocate for PdfGraphics { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::XdvFormUse { source, .. } => source.relocate(context), + Self::Save + | Self::Matrix(_) + | Self::Restore { .. } + | Self::Literal { .. } + | Self::SaveMatrix(_) + | Self::TextBoundary + | Self::XdvFormBegin(_) + | Self::XdvFormEnd(_) => Some(()), + } + } +} + +impl Relocate for NativeBox { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + let Self { + span, + content, + diagnostic, + interword_runs, + kind: _, + display: _, + width: _, + shift: _, + height: _, + depth: _, + setting: _, + badness: _, + diagnostic_eligible: _, + excess: _, + } = self; + span.relocate(context)?; + match content { + BoxContent::Horizontal(nodes) => nodes.relocate(context)?, + BoxContent::Vertical(nodes) => nodes.relocate(context)?, + } + diagnostic.relocate(context)?; + for run in interword_runs { + run.word.relocate(context)?; + } + Some(()) + } +} + +impl Relocate for OpenTypeRun { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + // Clusters and the positions of provenance records index this run's + // text, so only the causal locations inside each PaintSource move. + for (_, source) in &mut self.sources { + source.relocate(context)?; + } + Some(()) + } +} + +impl Relocate for TextNode { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Glyph { + glyph, + origins, + component_sources, + .. + } => { + glyph.relocate(context)?; + origins.relocate(context)?; + component_sources.relocate(context) + } + Self::OpenType(run) | Self::ExplicitOpenTypeGlyph(run) => run.relocate(context), + Self::Box(value) | Self::MathChar(value) => value.relocate(context), + Self::Rule(value) => value.relocate(context), + Self::Mark(value) => value.relocate(context), + Self::Adjustment(value) => value.relocate(context), + Self::Insertion(value) => value.relocate(context), + Self::Output(value) => value.relocate(context), + Self::Leaders(value) => value.relocate(context), + Self::FontSpace(_, _, origin) => origin.relocate(context), + Self::Discretionary { + pre_break, + post_break, + .. + } => { + pre_break.relocate(context)?; + post_break.relocate(context) + } + Self::Language(_) + | Self::MathBoundary { .. } + | Self::Glue(_) + | Self::NamedGlue(_, _) + | Self::ConditionalMathGlue + | Self::Kern { .. } + | Self::Indent(_) + | Self::Penalty(_) + | Self::AccentKern(_) + | Self::AutoKern(_) + | Self::MarginKern { .. } + | Self::Direction(_) + | Self::SpaceAdjustment(_) => Some(()), + } + } +} + +impl Relocate for NativeVerticalNode { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Box(value) | Self::Line(value) => value.relocate(context), + Self::Leaders(value) => value.relocate(context), + Self::Rule(value) => value.relocate(context), + Self::Mark(value) => value.relocate(context), + Self::Insertion(value) => value.relocate(context), + Self::Output(value) => value.relocate(context), + Self::Glue(_) + | Self::NamedGlue(_, _) + | Self::Kern(_) + | Self::ImplicitKern(_) + | Self::Penalty(_) => Some(()), + } + } +} + +impl Relocate for LeaderPattern { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Box(value) => value.relocate(context), + Self::Rule(value) => value.relocate(context), + } + } +} + +impl Relocate for DiagnosticNode { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Box(value) => value.relocate(context), + Self::Rule(value) => value.relocate(context), + Self::Mark(value) => value.relocate(context), + Self::Output(value) => value.relocate(context), + Self::Leaders { pattern, .. } => pattern.relocate(context), + Self::Adjustment { nodes, .. } | Self::Insertion { nodes, .. } => { + nodes.relocate(context) + } + Self::Discretionary { pre, post, .. } => { + pre.relocate(context)?; + post.relocate(context) + } + Self::Language(_) + | Self::Character { .. } + | Self::OpenType { .. } + | Self::EmptyBox(_) + | Self::Glue { .. } + | Self::ConditionalMathGlue + | Self::Kern { .. } + | Self::Math { .. } + | Self::Penalty(_) + | Self::Unsupported(_) + | Self::AccentKern(_) + | Self::AutoKern(_) + | Self::SpaceAdjustment(_) + | Self::MarginKern { .. } + | Self::Direction(_) + | Self::OpenTypeGlyph { .. } => Some(()), + } + } +} + +impl Relocate for OutputOperation { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Write { tokens, .. } + | Self::PdfSetMatrix(tokens) + | Self::PdfLiteral { tokens, .. } => tokens.relocate(context), + Self::PdfForm { origin, .. } | Self::PdfImage { origin, .. } => { + origin.relocate(context) + } + Self::Special { tokens, origin, .. } => { + tokens.relocate(context)?; + origin.relocate(context) + } + Self::PdfLink(link) => link.relocate(context), + Self::Open { .. } + | Self::Close { .. } + | Self::PdfColor { .. } + | Self::PdfObject(_) + | Self::PdfSave + | Self::PdfRestore + | Self::PdfTextSpace(_) + | Self::PdfSavePosition => Some(()), + } + } +} + +impl Relocate for DestinationId> { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Name(tokens) => tokens.relocate(context), + Self::Number(_) => Some(()), + } + } +} + +impl Relocate for LinkAction { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::User(tokens) | Self::GotoName(tokens) => tokens.relocate(context), + Self::Catalog(_) => Some(()), + } + } +} + +impl Relocate for LinkNode { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Annotation { entries, .. } => entries.relocate(context), + Self::Thread { + destination, + attributes, + .. + } => { + destination.relocate(context)?; + attributes.relocate(context) + } + Self::Destination { destination, .. } => destination.relocate(context), + Self::Start(start) => start.relocate(context), + Self::EndThread | Self::End | Self::Running(_) => Some(()), + } + } +} + +impl Relocate for NativeParagraph { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + let Self { + span, + nodes, + lines, + line_boxes, + line_adjustments, + line_pre_adjustments, + diagnostic_lines, + missing_glyphs, + initial_language: _, + previous_lines: _, + final_widow: _, + pre_display_size: _, + parameters: _, + discretionary_breaks: _, + interline_penalties: _, + badness: _, + packed_badness: _, + packed_excess: _, + packed_diagnostic: _, + packed_shrinking: _, + pass: _, + parskip: _, + hyphen_min: _, + } = self; + span.relocate(context)?; + nodes.relocate(context)?; + for Paragraph { lines, .. } in lines { + for item in lines.iter_mut().flatten() { + match item { + HorizontalItem::Box(value) => value.relocate(context)?, + HorizontalItem::Glue { .. } + | HorizontalItem::Penalty { .. } + | HorizontalItem::Discretionary { .. } => {} + } + } + } + line_boxes.relocate(context)?; + line_adjustments.relocate(context)?; + line_pre_adjustments.relocate(context)?; + diagnostic_lines.relocate(context)?; + for (_, _, span) in missing_glyphs { + span.relocate(context)?; + } + Some(()) + } +} + +relocate_fields!(NativeMath { + noads, horizontal, span; effective_classes, parameters, penalties_enabled, display, + horizontal_packs, last_pack_badness +}); +relocate_fields!(NativeDisplay { box_, span; parameters, short_skips, previous_lines }); +relocate_fields!(Noad { + source, nucleus, sub, sup, span; class, limits, accent, accent_style, rule, vcenter +}); +relocate_fields!(NoadSource { nucleus, sub, sup, operator; }); +relocate_fields!(FieldSource { paint, radical; }); +relocate_fields!(FractionSpec { left_source, right_source; thickness, left, right }); + +impl Relocate for MathItem { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::OpenType(run) => run.relocate(context), + Self::PdfImage(_) + | Self::PdfForm(_) + | Self::NativeGlyph { .. } + | Self::Glyph { .. } + | Self::Rule { .. } => Some(()), + } + } +} + +impl Relocate for MathField { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::List(list) => list.relocate(context), + Self::Box(value) => value.relocate(context), + Self::Radical(_, field) => field.relocate(context), + Self::Empty | Self::Char(_) | Self::TextChar(_) => Some(()), + } + } +} + +impl Relocate for MathNode { + fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> { + match self { + Self::Noad(noad) => noad.relocate(context), + Self::Delimiter { source, .. } | Self::MiddleDelimiter { source, .. } => { + source.relocate(context) + } + Self::Choice(lists) => lists.as_mut_slice().relocate(context), + Self::Leaders(value) => value.relocate(context), + Self::Discretionary(value) => value.relocate(context), + Self::Rule(value) => value.relocate(context), + Self::Mark(value) => value.relocate(context), + Self::Adjustment(value) => value.relocate(context), + Self::Insertion(value) => value.relocate(context), + Self::Output(value) => value.relocate(context), + Self::Fraction { + numerator, + denominator, + specification, + span, + source, + } => { + numerator.relocate(context)?; + denominator.relocate(context)?; + specification.relocate(context)?; + span.relocate(context)?; + source.relocate(context) + } + Self::Style(_) + | Self::Glue(_) + | Self::ConditionalMathGlue + | Self::ExplicitSpace(_, _) + | Self::Kern { .. } + | Self::Penalty(_) => Some(()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relocation_preserves_shared_tokens_and_moves_only_entry_provenance() { + let map = SourceRelocation::new(2, b"a\nsecond\n", b"ab\nsecond\n").unwrap(); + let definition = Span { + source: 1, + start: 2, + end: 3, + }; + let invocation = Span { + source: 2, + start: 2, + end: 8, + }; + let original: Arc<[Token]> = Arc::from([Token { + kind: TokenKind::Character('x', CatCode::Letter), + span: definition, + invocation: Some(invocation), + }]); + let mut relocation = EventRelocation::new(&map); + let first = relocation.relocate_tokens(&original).unwrap(); + let second = relocation.relocate_tokens(&original).unwrap(); + + assert!(Arc::ptr_eq(&first, &second)); + assert!(!Arc::ptr_eq(&first, &original)); + assert_eq!(first[0].span, definition); + assert_eq!( + first[0].invocation, + Some(Span { + source: 2, + start: 3, + end: 9 + }) + ); + assert_eq!(original[0].invocation, Some(invocation)); + } +} diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index d3fa44d..86d5e0b 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -1,3 +1,5 @@ +pub(super) mod source_relocation; + use hashbrown::HashMap; use std::collections::BTreeMap; use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState}; diff --git a/crates/texrra-tex-core/src/execution/state/source_relocation.rs b/crates/texrra-tex-core/src/execution/state/source_relocation.rs new file mode 100644 index 0000000..85c37b4 --- /dev/null +++ b/crates/texrra-tex-core/src/execution/state/source_relocation.rs @@ -0,0 +1,132 @@ +use super::*; +use crate::execution::source_relocation_events::EventRelocation; +use crate::pdf_device::forms::FormContents; +use std::collections::HashMap; + +impl State { + /// Relocate the provenance stored in persistent kernel assignments. A + /// command shard or macro shared by aliases keeps its ownership structure. + pub(in crate::execution) fn relocate_source( + &self, + relocation: &mut EventRelocation<'_>, + ) -> Option { + let mut state = self.clone(); + let mut macros = HashMap::new(); + // Copy only shards with a relocated macro. Ordinary format macros + // and macros from the byte-identical prefix keep their allocations. + for (index, shard) in self.commands.shards.iter().enumerate() { + for (name, meaning) in shard.iter() { + if let Meaning::Macro(body) = meaning { + let relocated = relocate_macro(body, relocation, &mut macros)?; + if !Arc::ptr_eq(body, &relocated) { + let shard = &mut Arc::make_mut(&mut state.commands).shards[index]; + Arc::make_mut(shard).insert(name.clone(), Meaning::Macro(relocated)); + } + } + } + } + for tokens in state.toks.values_mut() { + relocate_tokens(tokens, relocation)?; + } + for tokens in state + .token_parameters + .values_mut() + .chain(state.xe_inter_char_tokens.values_mut()) + { + *tokens = relocation.relocate_tokens(tokens)?; + } + for value in state.boxes.values_mut() { + *value = relocation.relocate_box(value)?; + } + for marks in state.page_marks.values_mut() { + for tokens in [&mut marks.top, &mut marks.first, &mut marks.bottom] + .into_iter() + .flatten() + { + *tokens = relocation.relocate_tokens(tokens)?; + } + } + for marks in state.split_marks.values_mut() { + marks.first = relocation.relocate_tokens(&marks.first)?; + marks.bottom = relocation.relocate_tokens(&marks.bottom)?; + } + for form in state.pdf_forms.values_mut() { + if let FormContents::Pending(body) = &mut form.contents { + let mut mapped = body.as_ref().clone(); + mapped.box_node = relocation.relocate_box(&mapped.box_node)?; + relocate_tokens(&mut mapped.attributes, relocation)?; + relocate_tokens(&mut mapped.resources, relocation)?; + if mapped != **body { + *body = Arc::new(mapped); + } + } + } + for group in &mut state.groups { + relocate_tokens(&mut group.after, relocation)?; + for saved in group.saved.values_mut() { + match saved { + Saved::Command(Some(Meaning::Macro(body))) => { + *body = relocate_macro(body, relocation, &mut macros)?; + } + Saved::Tokens(Some(tokens)) => relocate_tokens(tokens, relocation)?, + Saved::Hook(Some(tokens)) | Saved::XeInterCharTokens(Some(tokens)) => { + *tokens = relocation.relocate_tokens(tokens)?; + } + Saved::Box(Some(value)) => *value = relocation.relocate_box(value)?, + Saved::Command(_) + | Saved::Tokens(None) + | Saved::Hook(None) + | Saved::XeInterCharTokens(None) + | Saved::Box(None) + | Saved::Catcode(_) + | Saved::Integer(_) + | Saved::Job(_) + | Saved::Register(_) + | Saved::Parameter(_) + | Saved::ParagraphShape(_) + | Saved::LinePenalties(_) + | Saved::Font(_) + | Saved::Mathcode(_) + | Saved::Delcode(_) + | Saved::Sfcode(_, _) + | Saved::CaseCode(_) + | Saved::Mathfont(_) => {} + } + } + } + Some(state) + } +} + +fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> { + for token in tokens { + *token = relocation.relocate_token(token)?; + } + Some(()) +} + +pub(in crate::execution) fn relocate_macro( + body: &Arc, + relocation: &mut EventRelocation<'_>, + cached: &mut HashMap<*const Macro, Arc>, +) -> Option> { + use std::collections::hash_map::Entry; + match cached.entry(Arc::as_ptr(body)) { + Entry::Occupied(entry) => Some(entry.get().clone()), + Entry::Vacant(entry) => { + let mut mapped = None; + for (index, part) in body.replacement.iter().enumerate() { + if let Replacement::Token(token) = part { + let next = relocation.relocate_token(token)?; + if next != *token { + mapped + .get_or_insert_with(|| body.as_ref().clone()) + .replacement[index] = Replacement::Token(next); + } + } + } + let mapped = mapped.map_or_else(|| body.clone(), Arc::new); + Some(entry.insert(mapped).clone()) + } + } +} diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index 8d50366..dfa5848 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -189,20 +189,40 @@ impl StatisticsReport { return None; }; for usage in [before, after] { - usage.source_payload_bytes = usage.source_payload_bytes.checked_sub(previous)?.checked_add(current)?; - usage.mouth_payload_bytes = usage.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?; - if let Some(host) = &mut usage.host { - let size = u64::try_from(current).ok()?; - if replayed_entry_bytes != Some(size) { - return None; - } - host.rebind_entry_bytes(u64::try_from(previous).ok()?, size)?; + if usage.host.is_some() && replayed_entry_bytes != u64::try_from(current).ok() { + return None; } + usage.resize_entry_payload(previous, current, true)?; } debug_assert_eq!(self.text, self.phase.text()); Some(()) } + /// Recompute a report for a verified suffix after the initial entry read + /// changed size. The caller authenticates the entry scanner's lifetime. + pub fn with_suffix_entry_resize(&self, previous: usize, current: usize) -> Option { + let mut phase = self.phase.clone(); + match &mut phase { + StatisticsPhase::Shipout { before, after } => { + for usage in [before, after] { + let active = usage.mouth_payload_bytes == previous; + if !active && usage.mouth_payload_bytes != 0 { + return None; + } + usage.resize_entry_payload(previous, current, active)?; + } + } + StatisticsPhase::End { usage, .. } => { + if usage.stacks.input_frames != 0 || usage.mouth_payload_bytes != 0 { + return None; + } + usage.resize_entry_payload(previous, current, false)?; + } + } + let report = Self::new(phase, self.destination, self.span); + report.within_diagnostic_budget().then_some(report) + } + pub fn with_step_offset(&self, offset: StepOffset) -> Option { let mut phase = self.phase.clone(); match &mut phase { @@ -213,12 +233,35 @@ impl StatisticsReport { StatisticsPhase::End { usage, .. } => usage.steps = offset.apply(usage.steps)?, } let report = Self::new(phase, self.destination, self.span); - if let StatisticsPhase::End { usage, .. } = &report.phase - && usage.diagnostic_bytes_generated.checked_add(report.text.len())? > usage.token_limit - { - return None; + report.within_diagnostic_budget().then_some(report) + } + + fn within_diagnostic_budget(&self) -> bool { + match &self.phase { + StatisticsPhase::End { usage, .. } => usage + .diagnostic_bytes_generated + .checked_add(self.text.len()) + .is_some_and(|bytes| bytes <= usage.token_limit), + StatisticsPhase::Shipout { .. } => true, } - Some(report) + } +} + +impl ResourceUsage { + fn resize_entry_payload( + &mut self, + previous: usize, + current: usize, + active: bool, + ) -> Option<()> { + self.source_payload_bytes = self.source_payload_bytes.checked_sub(previous)?.checked_add(current)?; + if active { + self.mouth_payload_bytes = self.mouth_payload_bytes.checked_sub(previous)?.checked_add(current)?; + } + if let Some(host) = &mut self.host { + host.rebind_entry_bytes(u64::try_from(previous).ok()?, u64::try_from(current).ok()?)?; + } + Some(()) } } diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index eaf9144..106eb65 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,35 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-12-01 单行增删后复用未变化的后缀 + +同一物理行内增删后,扫描器须在后续字节一致的物理行会合。 +入口的既有前缀坐标保持,已核对的后缀坐标按字节差换算。重叠 +改动区的来源、增删接缝上有歧义的零宽来源,以及无法核验的扫描 +状态都继续执行。会合时比较换算后的原生状态,复用时同步迁移 +段落、数学、glyph、盒子、延迟输出、宏定义等持久化来源。 + +宿主只放宽经认证的首次入口读取的长度比较。显式读取入口长度、 +其他资源和流轨迹仍按原规则逐项验证。出页及收尾统计按当前入口 +和逻辑步数计算,诊断上限仍在重放前检查。复用时保留当前修订的 +活检查点,旧坐标下的后续检查点须重新生成。 + +最终代码通过构建、四项内核单测和八项管线回归。管线覆盖位移后的 +字形和宏来源、出页与收尾日志、文件大小查询的失效与已有复用路径。 +最终项目对照使用 release 模式,对两个本地包设 `opt-level=1`。 + +原样 12 页 NeurIPS 在第 3 页同一行改标点并增减 1 字节。删除从 +只缓存较长版本的新会话开始,以验证实际后缀复用。两个方向均从 +第 272 行恢复,运行 646,780 步(全量的 3.3%),跳过 4,634,847 +步未变后缀。第 4 页对应 glyph 的来源区间双向移动 1 字节。 +两次都只发布第 3 页预览更新,仍有 10 页重新生成绘制列表。 +完整执行、PDF、SVG、显示列表、来源映射、资源轨迹和 aux、out、log +逐项等同独立全量。证据在 `target/p4-relocated-suffix/`。 + +后续优先利用已验证的后缀和其原执行身份,复用未改变页面的 +绘制列表,并以当前坐标重新验证来源映射。正式延迟与内存仍按 +总目标的固定机器和语料门槛验收。 + ## 2026-12-01 源码增删后复用已执行的前缀 原生会话校验入口已装载的物理行和前缀字节。改动留在未读部分时, diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 6db8bf6..13226fd 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -414,13 +414,20 @@ impl<'a> CapturedEntries<'a> { cancellation: &Cancellation, ) -> Result<(), String> { let project = self.request.project.as_deref().expect("settled replay uses a project"); - let bytes = project.file(&completed.guard.entry).expect("settled entry").data.len(); + let path = &completed.guard.entry; + let bytes = project.file(path).expect("settled entry").data.len(); + let previous_bytes = completed.guard.project.file(path).expect("prior settled entry").data.len(); + let resize = (previous_bytes != bytes).then_some((previous_bytes, bytes)); let stride = bytes.div_ceil(SOURCE_INTERVALS).max(1); let offset = texrra_tex_core::execution::StepOffset::new( prior.entry.completed_steps(), current.completed_steps(), ); let mut later = [const { None }; SOURCE_INTERVALS]; - if let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution) { + // Untranslated live continuations and their source intervals still + // refer to the old entry when its length changed. + if resize.is_none() + && let Some(mut rebase) = current.prepare_suffix_rebase(&prior.entry, &completed.result.execution) + { // Keep the deepest compatible settled continuation per source interval. for (&page, anchor) in completed.settled.range((std::ops::Bound::Excluded(page), std::ops::Bound::Unbounded)).rev() { let interval = (anchor.entry.frontier() - 1) / stride; @@ -441,7 +448,7 @@ impl<'a> CapturedEntries<'a> { let Some(calls) = completed.calls.get(replayed..anchor.call_count) else { continue; }; - host.replay_suffix(calls, offset, cancellation)?; + host.replay_suffix(calls, offset, None, cancellation)?; replayed = anchor.call_count; if anchor.host == host.files().replay_boundary() { let regular = CaptureSlots { @@ -454,7 +461,7 @@ impl<'a> CapturedEntries<'a> { self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host); } } - host.replay_suffix(&completed.calls[replayed..], offset, cancellation)?; + host.replay_suffix(&completed.calls[replayed..], offset, resize, cancellation)?; completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string()) } @@ -970,7 +977,8 @@ impl SelectedCheckpoint { }; let Some((completed, old, execution)) = suffixes.clone().find_map(|completed| { let old = completed.settled.get(&page)?; - if old.call_count != new.call_count || old.host != new.host + if old.call_count != new.call_count + || !new.host.matches_for_suffix(&old.host) || !can_replay_completed_suffix(completed, request, host.files()) { return None; diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 1a458be..777eeb7 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -178,6 +178,7 @@ impl<'a> RecordingHost<'a> { &mut self, calls: &[Call], offset: StepOffset, + resize: Option<(usize, usize)>, cancellation: &Cancellation, ) -> Result<(), String> { let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?; @@ -187,9 +188,16 @@ impl<'a> RecordingHost<'a> { for call in calls { check(cancellation).map_err(|error| error.to_string())?; let call = match call { - Call::EndStatistics(report) if !offset.is_identity() => Call::EndStatistics( - Arc::new(report.with_step_offset(offset).ok_or("invalid replayed statistics")?), - ), + Call::EndStatistics(report) if !offset.is_identity() || resize.is_some() => { + let report = report.with_step_offset(offset).ok_or("invalid replayed statistics")?; + let report = if let Some((previous, current)) = resize { + report.with_suffix_entry_resize(previous, current) + .ok_or("invalid replayed entry size in statistics")? + } else { + report + }; + Call::EndStatistics(Arc::new(report)) + } call => call.clone(), }; call.replay(self.files, None)?; diff --git a/src/native_job.rs b/src/native_job.rs index 7bd516e..a45263a 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -159,6 +159,20 @@ struct DraftLedger { #[derive(PartialEq, Eq)] pub(super) struct ReplayBoundary { + entry_bytes: Option, + state: ReplayState, +} + +impl ReplayBoundary { + /// Ignore only the first entry read's length. The caller authenticates + /// that read and checks all later observations of the entry path. + pub(super) fn matches_for_suffix(&self, prior: &Self) -> bool { + self.entry_bytes.is_some() && prior.entry_bytes.is_some() && self.state == prior.state + } +} + +#[derive(PartialEq, Eq)] +struct ReplayState { inputs: Vec<(u8, u64, PathBuf, u64, std::collections::VecDeque)>, outputs: Vec<(u8, u64, PathBuf, u64)>, next_handle: u64, @@ -671,11 +685,13 @@ impl Files { pub(super) fn replay_boundary(&self) -> ReplayBoundary { let mut trace = self.resource_trace().clone(); trace.project_version = None; - // The caller compared the live scanner bytes and validates later - // whole-file reads separately. Keep this entry's path and length. - if let Some(entry) = trace.reads.first_mut() { + // The entry scanner verifies source bytes separately. Retain the + // first read's path in the comparison and store its length apart, + // since later live checkpoints still require exact lengths. + let entry_bytes = trace.reads.first_mut().map(|entry| { entry.sha256.clear(); - } + std::mem::take(&mut entry.bytes) + }); let mut stream_events = self.stream_io.events().to_vec(); for event in &mut stream_events { if let crate::native_stream::StreamEffect::OutputOpened { @@ -687,7 +703,7 @@ impl Files { identity.unix_identity = None; } } - ReplayBoundary { + let state = ReplayState { inputs: self.inputs.iter().map(|(&index, input)| { (index, input.handle, input.path.clone(), input.offset, input.xe_lookahead.clone()) }).collect(), @@ -702,7 +718,8 @@ impl Files { generated_written: self.generated_written.clone(), trace, stream_events, - } + }; + ReplayBoundary { entry_bytes, state } } pub(super) fn replay_world(&self) -> &FileWorld { diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index ed1c822..a07b20f 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1847,6 +1847,70 @@ fn resized_entry_prefix_invalidates_an_executed_file_size_query() { fs::remove_dir_all(cwd).unwrap(); } +#[test] +fn settled_suffix_relocates_source_spans_after_insertions_and_deletions() { + let cwd = directory("settled-resized-suffix"); + let entry = cwd.join("main.tex"); + let body = |letter, note, tail_query| format!(r" +\tracingstats=2 +\shipout\hbox{{Cover ABC}} +\setbox3=\hbox{{{letter}}}\relax%{note} +\shipout\box3 +\relax +\shipout\hbox{{Checkpoint}} +\relax +{tail_query} +\gdef\saved{{Suffix glyphs}} +\shipout\hbox{{\saved}} +\relax +\shipout\hbox{{Final}} +\end +"); + for tail_query in ["", r"\count42=\pdffilesize{main.tex}\relax"] { + let mut project = ProjectSnapshot::new( + atomic_definition(&cwd, 1, &body('A', "medium", tail_query)), + ).unwrap(); + let mut request = request(&cwd).observe_generated_initial(); + request.world = project.configuration(); + let session = NativeCompiler::default().with_automatic_entry_checkpoints(); + let mut previous = session.compile(request.clone().with_project(project.clone())).unwrap(); + + for (revision, letter, note) in [(2, 'B', "expanded comment"), (3, 'C', "x")] { + let source = format!("{HEADER}{}", body(letter, note, tail_query)); + let tail_offset = source.find("Suffix glyphs").unwrap(); + let bytes = i32::try_from(source.len()).unwrap(); + project = project.with_file_edits( + revision, [(entry.clone(), Arc::from(source.into_bytes()))].into(), + ).unwrap(); + let job = request.clone().with_project(project.clone()); + let updated = session.compile(job.clone()).unwrap(); + let work = &updated.entry_checkpoint_work; + assert_eq!(work.reused_suffix_steps > 0, tail_query.is_empty(), "{work:?}"); + if !tail_query.is_empty() { + assert_eq!(updated.execution.execution.state.count(42), bytes); + } + let preview = updated.preview_since(Some(previous.revision())).unwrap(); + assert_eq!(preview.pages.iter().map(|page| page.index).collect::>(), [1]); + assert!(updated.source_map.pages[3].entries.iter().any(|glyph| { + glyph.source.tokens.iter().any(|origin| origin.span.start == tail_offset) + })); + + let log = fs::read(cwd.join("job.log")).unwrap(); + let full = NativeCompiler::default().compile(job).unwrap(); + assert_eq!(updated.execution.execution, full.execution.execution); + assert_eq!(updated.resources.trace, full.resources.trace); + assert_eq!(updated.pdf, full.pdf); + assert_eq!(updated.pages, full.pages); + assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages); + assert_eq!(updated.source_map.pages, full.source_map.pages); + assert_eq!(updated.source_map.sources, full.source_map.sources); + assert_eq!(log, fs::read(cwd.join("job.log")).unwrap()); + previous = updated; + } + } + fs::remove_dir_all(cwd).unwrap(); +} + #[test] fn settled_suffix_translates_step_counts_and_enforces_the_limit() { let cwd = directory("settled-step-counts");