Relocate source provenance when native suffixes move

This commit is contained in:
gloamxun committed 2026-12-01 22:17:10 +08:00
1 parent 6acd82dbfa
commit 41a459b4ca
16 files changed
+1507 -79

No files matched your search

@@ -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<usize>,
pub(super) word: Arc<OpenTypeRun>,
pub(in crate::execution) word: Arc<OpenTypeRun>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub(super) effects: Vec<usize>,
}
@@ -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 = &current.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<impl FnMut(&Self) -> Option<Self> + '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))
}
@@ -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<Executor> {
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<usize, GeneratedInput>,
map: &SourceRelocation,
) -> Option<()> {
for input in generated.values_mut() {
input.origin = map.relocate_span(input.origin)?;
}
Some(())
}
fn relocate_page(
page: &mut Option<NativePageState>,
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(())
}
@@ -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)
})
}
@@ -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;
+102 -5
View File
@@ -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<usize> {
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<usize> {
(matches!(self.line_breaks, LineBreaks::Physical) && !self.end_after_line && self.offset > 0)
.then_some(self.offset)
@@ -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<Self> {
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(&current[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<usize> {
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<Span> {
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<usize> {
if old_start < self.first_unchanged_line {
return None;
}
self.relocate_suffix_offset(old_start)
}
fn relocate_suffix_offset(&self, old_offset: usize) -> Option<usize> {
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());
}
}
}
@@ -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<T> = HashMap<*const T, Arc<T>>;
pub(super) struct EventRelocation<'a> {
map: &'a SourceRelocation,
text_lists: Shared<Vec<TextNode>>,
vertical_lists: Shared<Vec<NativeVerticalNode>>,
diagnostic_lists: Shared<[DiagnosticNode]>,
token_lists: Shared<[Token]>,
opentype_runs: Shared<OpenTypeRun>,
}
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<Event> {
self.relocated(event)
}
pub(super) fn relocate_box(&mut self, packed: &NativeBox) -> Option<NativeBox> {
self.relocated(packed)
}
pub(super) fn relocate_vertical(
&mut self,
node: &NativeVerticalNode,
) -> Option<NativeVerticalNode> {
self.relocated(node)
}
pub(super) fn relocate_token(&mut self, token: &Token) -> Option<Token> {
self.relocated(token)
}
pub(super) fn relocate_tokens(&mut self, tokens: &Arc<[Token]>) -> Option<Arc<[Token]>> {
self.relocated(tokens)
}
fn relocated<T: Clone + Relocate>(&mut self, value: &T) -> Option<T> {
let mut updated = value.clone();
updated.relocate(self)?;
Some(updated)
}
}
trait Relocate {
fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()>;
}
impl<T: Relocate> Relocate for Box<T> {
fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> {
self.as_mut().relocate(context)
}
}
impl<T: Relocate> Relocate for Option<T> {
fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> {
if let Some(value) = self {
value.relocate(context)?;
}
Some(())
}
}
impl<T: Relocate> Relocate for Vec<T> {
fn relocate(&mut self, context: &mut EventRelocation<'_>) -> Option<()> {
self.as_mut_slice().relocate(context)
}
}
impl<T: Relocate> 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<TextNode>, text_lists, Clone::clone);
relocate_shared!(Vec<NativeVerticalNode>, 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<Vec<Token>> {
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));
}
}
@@ -1,3 +1,5 @@
pub(super) mod source_relocation;
use hashbrown::HashMap;
use std::collections::BTreeMap;
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
@@ -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<Self> {
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<Macro>,
relocation: &mut EventRelocation<'_>,
cached: &mut HashMap<*const Macro, Arc<Macro>>,
) -> Option<Arc<Macro>> {
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())
}
}
}
@@ -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<Self> {
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<Self> {
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(())
}
}