Compare commits
19
Commits
8b6dab8d52
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f78aff25c5 | ||
|
|
473b3beace | ||
|
|
bf42a88dff | ||
|
|
0b4aa49a71 | ||
|
|
ac5f691a48 | ||
|
|
5b86a7ac7e | ||
|
|
5b9eca1d60 | ||
|
|
aed7010cba | ||
|
|
b081c951af | ||
|
|
c008c52964 | ||
|
|
57c05d9635 | ||
|
|
41a459b4ca | ||
|
|
6acd82dbfa | ||
|
|
465a574124 | ||
|
|
9a6c162b46 | ||
|
|
c42a1a72aa | ||
|
|
1cf985469c | ||
|
|
a5dba52acb | ||
|
|
fe86163767 |
No files matched your search
@@ -172,7 +172,7 @@ pub(super) enum BoxPaint<'a> {
|
||||
RowStart(BoxLayout),
|
||||
ScopeStart(usize),
|
||||
ScopeEnd(usize),
|
||||
PdfLink(&'a OutputNode, BoxLayout),
|
||||
PdfLink(&'a OutputNode, BoxLayout, Option<usize>),
|
||||
Output(&'a OutputNode),
|
||||
}
|
||||
|
||||
@@ -180,6 +180,7 @@ struct WalkBudget<'a> {
|
||||
remaining: usize,
|
||||
cancellation: Option<&'a Cancellation>,
|
||||
leader_depth: usize,
|
||||
next_leader_link: usize,
|
||||
xdv_scopes: bool,
|
||||
}
|
||||
|
||||
@@ -189,6 +190,7 @@ impl WalkBudget<'_> {
|
||||
remaining: usize::MAX,
|
||||
cancellation: None,
|
||||
leader_depth: 0,
|
||||
next_leader_link: 0,
|
||||
xdv_scopes: false,
|
||||
}
|
||||
}
|
||||
@@ -296,6 +298,7 @@ impl NativeBox {
|
||||
remaining: limit,
|
||||
cancellation,
|
||||
leader_depth: 0,
|
||||
next_leader_link: 0,
|
||||
xdv_scopes: false,
|
||||
};
|
||||
self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, item| {
|
||||
@@ -890,7 +893,7 @@ impl NativeBox {
|
||||
return;
|
||||
}
|
||||
BoxPaint::RowStart(_) | BoxPaint::ScopeStart(_) | BoxPaint::ScopeEnd(_)
|
||||
| BoxPaint::PdfLink(_, _) => return,
|
||||
| BoxPaint::PdfLink(..) => return,
|
||||
};
|
||||
if let Some(child) = &b.math_geometry {
|
||||
for p in &child.items {
|
||||
@@ -1078,12 +1081,14 @@ impl NativeBox {
|
||||
+ self.setting.adjustment(g, &mut cumulative, &mut previous);
|
||||
match &leader.pattern {
|
||||
LeaderPattern::Box(b) => {
|
||||
let first_link = budget.next_leader_link;
|
||||
for pos in leader.positions(
|
||||
y - self.height,
|
||||
cursor,
|
||||
length,
|
||||
b.height + b.depth,
|
||||
) {
|
||||
budget.next_leader_link = first_link;
|
||||
b.walk_leader(
|
||||
if rtl { edge - b.shift - b.width } else { x + b.shift },
|
||||
pos + b.height,
|
||||
@@ -1118,7 +1123,7 @@ impl NativeBox {
|
||||
cursor += b.depth;
|
||||
}
|
||||
NativeVerticalNode::Output(node) => {
|
||||
walk_output(node, edge, cursor, container, links, emit);
|
||||
walk_output(node, edge, cursor, container, links, budget, emit);
|
||||
if let Some(image) = node.image_box() {
|
||||
cursor += image.height;
|
||||
emit(if rtl { edge - image.width } else { x }, cursor, BoxPaint::Box(&image));
|
||||
@@ -1151,7 +1156,7 @@ impl NativeBox {
|
||||
let result = self.walk_at(x, y, level, rtl, links, budget, &mut |x, y, paint| {
|
||||
if !matches!(paint, BoxPaint::Output(o) if matches!(o.operation,
|
||||
OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. }))
|
||||
&& !matches!(paint, BoxPaint::PdfLink(node, _) if matches!(
|
||||
&& !matches!(paint, BoxPaint::PdfLink(node, ..) if matches!(
|
||||
node.operation,
|
||||
OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Destination { .. }
|
||||
| crate::pdf_device::links::LinkNode::Annotation { .. }
|
||||
@@ -1207,7 +1212,9 @@ fn walk_row(
|
||||
PackedHorizontal::Leaders(leader, width) => {
|
||||
match &leader.pattern {
|
||||
LeaderPattern::Box(b) => {
|
||||
let first_link = budget.next_leader_link;
|
||||
for pos in leader.positions(row.left, x, *width, b.width) {
|
||||
budget.next_leader_link = first_link;
|
||||
b.walk_leader(pos, y + b.shift, row.level + 1, *rtl, links, budget, emit)?;
|
||||
}
|
||||
}
|
||||
@@ -1224,7 +1231,7 @@ fn walk_row(
|
||||
x += width;
|
||||
}
|
||||
PackedHorizontal::Output(node) => {
|
||||
walk_output(node, x, y, row, links, emit);
|
||||
walk_output(node, x, y, row, links, budget, emit);
|
||||
if let Some(image) = node.image_box() {
|
||||
emit(x, y, BoxPaint::Box(&image));
|
||||
x += image.width;
|
||||
@@ -1242,6 +1249,7 @@ fn walk_output(
|
||||
y: i64,
|
||||
container: BoxLayout,
|
||||
links: bool,
|
||||
budget: &mut WalkBudget<'_>,
|
||||
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
|
||||
) {
|
||||
emit(x, y, BoxPaint::Output(node));
|
||||
@@ -1252,7 +1260,16 @@ fn walk_output(
|
||||
} else if let OutputOperation::PdfTextSpace(operation) = node.operation {
|
||||
emit(x, y, BoxPaint::PdfTextSpace(operation));
|
||||
} else if links && node.is_pdf_link() {
|
||||
emit(x, y, BoxPaint::PdfLink(node, container));
|
||||
// Repeated tiles revisit the same node slots. Separate copies of a
|
||||
// box get separate slots even when Rust shares their backing list.
|
||||
let leader_link = (budget.leader_depth > 0 && matches!(
|
||||
node.operation, OutputOperation::PdfLink(crate::pdf_device::links::LinkNode::Start(_))
|
||||
)).then(|| {
|
||||
let slot = budget.next_leader_link;
|
||||
budget.next_leader_link += 1;
|
||||
slot
|
||||
});
|
||||
emit(x, y, BoxPaint::PdfLink(node, container, leader_link));
|
||||
}
|
||||
}
|
||||
pub(super) fn box_paragraph(mut b: NativeBox) -> Paragraph {
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
|
||||
@@ -30,15 +30,42 @@ impl DependencyReads {
|
||||
self.other.contains(&Dependency::ResourceStatistics)
|
||||
}
|
||||
|
||||
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
|
||||
let byte_catcodes = (0..=u8::MAX)
|
||||
.filter(|&index| {
|
||||
let index = usize::from(index);
|
||||
self.byte_catcodes[index / 64] & (1 << (index % 64)) != 0
|
||||
})
|
||||
.map(|index| Dependency::CatCode(char::from(index)));
|
||||
self.other.into_iter().chain(byte_catcodes).collect()
|
||||
pub(super) fn is_subset(&self, other: &Self) -> bool {
|
||||
self.byte_catcodes
|
||||
.iter()
|
||||
.zip(other.byte_catcodes)
|
||||
.all(|(&bits, permitted)| bits & !permitted == 0)
|
||||
&& self.other.is_subset(&other.other)
|
||||
}
|
||||
|
||||
/// Extend a completed execution with observations made only in the new prefix.
|
||||
/// The caller has already checked that the prefix keeps all old observations.
|
||||
pub(super) fn extend_ordered_delta(&self, prior: &Self, into: &mut BTreeSet<Dependency>) {
|
||||
if self.byte_catcodes != prior.byte_catcodes {
|
||||
into.extend(byte_catcode_dependencies(std::array::from_fn(|index| {
|
||||
self.byte_catcodes[index] & !prior.byte_catcodes[index]
|
||||
})));
|
||||
}
|
||||
if self.other.len() != prior.other.len() {
|
||||
into.extend(self.other.difference(&prior.other).cloned());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn into_ordered(self) -> BTreeSet<Dependency> {
|
||||
self.other
|
||||
.into_iter()
|
||||
.chain(byte_catcode_dependencies(self.byte_catcodes))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
fn byte_catcode_dependencies(bits: [u64; 4]) -> impl Iterator<Item = Dependency> {
|
||||
(0..=u8::MAX)
|
||||
.filter(move |&index| {
|
||||
let index = usize::from(index);
|
||||
bits[index / 64] & (1 << (index % 64)) != 0
|
||||
})
|
||||
.map(|index| Dependency::CatCode(char::from(index)))
|
||||
}
|
||||
|
||||
impl Extend<Dependency> for DependencyReads {
|
||||
@@ -53,6 +80,28 @@ impl Extend<Dependency> for DependencyReads {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prefix_delta_keeps_old_suffix_observations() {
|
||||
let mut prior = DependencyReads::default();
|
||||
prior.extend([Dependency::CatCode('A'), Dependency::EndLineChar]);
|
||||
let mut current = prior.clone();
|
||||
current.extend([
|
||||
Dependency::CatCode('ÿ'),
|
||||
Dependency::CatCode('文'),
|
||||
Dependency::ParagraphToken,
|
||||
]);
|
||||
|
||||
assert!(prior.is_subset(¤t));
|
||||
assert!(!current.is_subset(&prior));
|
||||
let mut reads = prior.clone().into_ordered();
|
||||
reads.insert(Dependency::EscapeChar);
|
||||
current.extend_ordered_delta(&prior, &mut reads);
|
||||
|
||||
let mut expected = current.into_ordered();
|
||||
expected.insert(Dependency::EscapeChar);
|
||||
assert_eq!(reads, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloned_record_preserves_byte_and_unicode_dependencies() {
|
||||
let mut read = DependencyReads::default();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::collections::{BTreeSet, VecDeque};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::hash::{BuildHasher, RandomState};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -43,6 +43,7 @@ mod scheduling;
|
||||
mod specials;
|
||||
mod statistics;
|
||||
mod continuation;
|
||||
pub use continuation::{RelocatedShipoutSuffix, SuffixKernelTimings};
|
||||
mod xdv_annotation;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -281,6 +282,7 @@ pub struct Executor {
|
||||
format_image_warnings: Vec<String>,
|
||||
pdf_force_pagebox_warned: bool,
|
||||
input_position: Option<(usize, usize)>,
|
||||
line_observations: BTreeMap<usize, usize>,
|
||||
paragraph: Option<super::paragraph::Builder>,
|
||||
vertical: super::boxes::VerticalBuilder,
|
||||
box_frames: Vec<boxes::BoxFrame>,
|
||||
@@ -366,8 +368,8 @@ impl EntryCheckpoint {
|
||||
&& self.executor.sources[self.entry].name == earlier.executor.sources[earlier.entry].name
|
||||
&& self.source_mouth(self.entry)
|
||||
.same_loaded_prefix_constraint(earlier.source_mouth(earlier.entry))
|
||||
&& (!self.executor.reads.observed_statistics()
|
||||
|| (earlier.executor.reads.observed_statistics()
|
||||
&& (self.can_resize_entry()
|
||||
|| (!earlier.can_resize_entry()
|
||||
&& self.executor.sources[self.entry].data.len()
|
||||
== earlier.executor.sources[earlier.entry].data.len()))
|
||||
}
|
||||
@@ -380,7 +382,20 @@ impl EntryCheckpoint {
|
||||
let entry = &self.executor.sources[self.entry];
|
||||
// A suspended scanner may only accept unchanged bytes when its
|
||||
// boundary cannot be authenticated as a physical line.
|
||||
entry.name == name && (entry.data == data || self.matches_scanned_source(self.entry, data))
|
||||
entry.name == name
|
||||
&& (entry.data == data
|
||||
|| ((entry.data.len() == data.len() || self.can_resize_entry())
|
||||
&& self.source_mouth(self.entry).matches_loaded_prefix(data)))
|
||||
}
|
||||
|
||||
fn can_resize_entry(&self) -> bool {
|
||||
// At each retained shipout, the original entry is still the bottom
|
||||
// source frame. Reject ambiguous accounting if it also opened as
|
||||
// another source before this checkpoint.
|
||||
!self.executor.reads.observed_statistics()
|
||||
|| self.executor.sources.iter().filter(|source| {
|
||||
source.name == self.executor.sources[self.entry].name
|
||||
}).take(2).count() == 1
|
||||
}
|
||||
|
||||
pub fn entry_frontier(&self) -> usize {
|
||||
@@ -487,6 +502,14 @@ impl EntryCheckpoint {
|
||||
}
|
||||
let mut executor = self.executor.clone().with_cancellation(cancellation);
|
||||
executor.line_break_cache = line_break_cache;
|
||||
let previous_len = self.executor.sources[self.entry].data.len();
|
||||
let current_len = source.data.len();
|
||||
if previous_len != current_len
|
||||
&& self.executor.reads.observed_statistics()
|
||||
&& executor.resize_entry_statistics(previous_len, current_len, files.replayed_entry_bytes()).is_none()
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
executor.rebind_checkpoint_source(self.entry, source);
|
||||
if let Some(nested) = nested {
|
||||
executor.rebind_checkpoint_source(self.active_source, nested);
|
||||
@@ -595,6 +618,7 @@ impl Executor {
|
||||
format_image_warnings: Vec::new(),
|
||||
pdf_force_pagebox_warned: false,
|
||||
input_position: None,
|
||||
line_observations: BTreeMap::new(),
|
||||
paragraph: None,
|
||||
vertical,
|
||||
box_frames: Vec::new(),
|
||||
@@ -680,6 +704,10 @@ impl Executor {
|
||||
self.state.page_marks.clear();
|
||||
self
|
||||
}
|
||||
/// Keep every observation even when its source was already read in the prefix.
|
||||
fn observe_line_number(&mut self, source: usize) {
|
||||
*self.line_observations.entry(source).or_default() += 1;
|
||||
}
|
||||
fn error(&self, message: impl Into<String>, span: Span) -> Error {
|
||||
let mut error = Error::at(&self.sources, self.state.input_profile(), message, span);
|
||||
if let Some(generated) = self.generated_inputs.get(&span.source) {
|
||||
@@ -2759,6 +2787,7 @@ impl Executor {
|
||||
self.error("no native input position available", self.current)
|
||||
})?;
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
i32::try_from(line)
|
||||
.map_err(|_| self.error("input line number overflow", self.current))
|
||||
}
|
||||
@@ -3231,10 +3260,10 @@ impl Executor {
|
||||
.decode_line(&line[bom..bom + length], base + bom, &self.state, &mut self.reads)
|
||||
.map_err(|e| self.error(e, Span { source, start: base + bom, end }))?;
|
||||
if warnings > 0 {
|
||||
self.observe_xe_utf8_warnings(
|
||||
vec![(self.input_position.map_or(1, |(_, line)| line), warnings)],
|
||||
files,
|
||||
)?;
|
||||
let (line_source, line) = self
|
||||
.input_position
|
||||
.map_or((None, 1), |(source, line)| (Some(source), line));
|
||||
self.observe_xe_utf8_warnings(line_source, vec![(line, warnings)], files)?;
|
||||
}
|
||||
chars
|
||||
} else {
|
||||
@@ -3330,7 +3359,7 @@ impl Executor {
|
||||
return self.fail("native read token limit exceeded");
|
||||
}
|
||||
}
|
||||
self.observe_xe_utf8_warnings(mouth.take_utf8_warnings(), files)?;
|
||||
self.observe_xe_utf8_warnings(Some(source), mouth.take_utf8_warnings(), files)?;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
@@ -3562,8 +3591,10 @@ impl Executor {
|
||||
stream_sources: self.stream_sources,
|
||||
generated_inputs: self.generated_inputs,
|
||||
reads,
|
||||
line_observations: Some(self.line_observations),
|
||||
events: self.events.into_vec(),
|
||||
steps: self.steps,
|
||||
box_nodes_created: Some(self.box_nodes_created),
|
||||
reads_event_history: self.reads_event_history,
|
||||
accounts_event_history: self.accounts_event_history,
|
||||
})
|
||||
@@ -4067,8 +4098,10 @@ impl Executor {
|
||||
stream_sources: self.stream_sources,
|
||||
generated_inputs: self.generated_inputs,
|
||||
reads,
|
||||
line_observations: Some(self.line_observations),
|
||||
incoming_state,
|
||||
steps: self.steps,
|
||||
box_nodes_created: Some(self.box_nodes_created),
|
||||
reads_event_history: self.reads_event_history,
|
||||
accounts_event_history: self.accounts_event_history,
|
||||
})
|
||||
@@ -4165,11 +4198,12 @@ impl Executor {
|
||||
let Some(InputFrame::Source { source, mouth, .. }) = self.inputs.last_mut() else {
|
||||
unreachable!("new job starts with its entry source");
|
||||
};
|
||||
let source = *source;
|
||||
let line = mouth
|
||||
.load_line(&self.state, &mut self.reads)
|
||||
.map(|_| (*source, mouth.line_number()));
|
||||
.map(|_| (source, mouth.line_number()));
|
||||
let warnings = mouth.take_utf8_warnings();
|
||||
self.observe_xe_utf8_warnings(warnings, files)?;
|
||||
self.observe_xe_utf8_warnings(Some(source), warnings, files)?;
|
||||
self.input_position =
|
||||
Some(line.map_err(|(span, message)| self.error(message, span))?);
|
||||
self.push_mode_hook(TokenParameter::Everyjob)?;
|
||||
|
||||
@@ -811,6 +811,7 @@ impl Executor {
|
||||
};
|
||||
let (b, (missing, extra)) = result.map_err(|e| self.error(e, frame.span))?;
|
||||
if missing != 0 || extra != 0 {
|
||||
self.observe_line_number(self.current.source);
|
||||
let line = self.error("", self.current).line;
|
||||
files
|
||||
.observe_message(&format!(
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
use super::super::{
|
||||
source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
|
||||
statistics::BoxNodeOffset,
|
||||
};
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
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 {
|
||||
@@ -20,7 +28,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,
|
||||
@@ -79,16 +91,67 @@ impl InputFrame {
|
||||
}
|
||||
}
|
||||
|
||||
/// Work done inside an observed suffix splice. A rejected candidate can
|
||||
/// contribute to the checks it reached.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct SuffixKernelTimings {
|
||||
pub state_comparison: Duration,
|
||||
pub retained_accounting: Duration,
|
||||
pub suffix_assembly: Duration,
|
||||
}
|
||||
|
||||
/// Source coordinates for the shipouts copied from a moved execution suffix.
|
||||
pub struct RelocatedShipoutSuffix {
|
||||
first_page: usize,
|
||||
map: SourceRelocation,
|
||||
}
|
||||
|
||||
impl RelocatedShipoutSuffix {
|
||||
/// Relocate a raw local layout from the exact donor execution at the
|
||||
/// given zero-based shipout index. The host must match that execution
|
||||
/// before supplying a cached list.
|
||||
pub fn relocate_layout(
|
||||
&self,
|
||||
index: usize,
|
||||
layout: &crate::render::DisplayList,
|
||||
) -> Option<crate::render::DisplayList> {
|
||||
if index < self.first_page {
|
||||
return None;
|
||||
}
|
||||
layout.relocate_sources(|span| self.map.relocate_span(span))
|
||||
}
|
||||
}
|
||||
|
||||
impl EntryCheckpoint {
|
||||
/// Construct an execution with the current prefix and a previously
|
||||
/// completed suffix. The host must still validate and replay that suffix.
|
||||
pub fn splice_settled_suffix(&self, prior: &Self, completed: &Execution) -> Option<Execution> {
|
||||
self.splice_settled_suffix_with_layout(prior, completed)
|
||||
.map(|(execution, _)| execution)
|
||||
}
|
||||
|
||||
/// Also return the coordinate mapping for copied shipouts whose cached
|
||||
/// local layouts belong to the supplied completed execution.
|
||||
pub fn splice_settled_suffix_with_layout(
|
||||
&self,
|
||||
prior: &Self,
|
||||
completed: &Execution,
|
||||
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
|
||||
self.splice_settled_suffix_observed(prior, completed, None)
|
||||
}
|
||||
|
||||
/// Splice a completed suffix and optionally record its kernel checks.
|
||||
pub fn splice_settled_suffix_observed(
|
||||
&self,
|
||||
prior: &Self,
|
||||
completed: &Execution,
|
||||
mut timings: Option<&mut SuffixKernelTimings>,
|
||||
) -> Option<(Execution, Option<RelocatedShipoutSuffix>)> {
|
||||
if self.entry != self.active_source
|
||||
|| prior.entry != prior.active_source
|
||||
|| 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
|
||||
@@ -99,9 +162,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
|
||||
@@ -110,7 +170,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
|
||||
}
|
||||
@@ -119,43 +179,350 @@ impl EntryCheckpoint {
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let box_offset = BoxNodeOffset::new(old.box_nodes_created, current.box_nodes_created);
|
||||
let box_nodes_created = match completed.box_nodes_created {
|
||||
Some(donor) => Some(box_offset.apply(donor)?),
|
||||
None if box_offset.is_identity() => None,
|
||||
None => return None,
|
||||
};
|
||||
if current.material_charge != old.material_charge {
|
||||
// A capacity recount can lower the running charge and change
|
||||
// which storage TeX counts. Bound every future charge on both
|
||||
// histories so neither can enter that path.
|
||||
let donor = completed.box_nodes_created?;
|
||||
if donor == usize::MAX {
|
||||
return None;
|
||||
}
|
||||
let remaining = donor.checked_sub(old.box_nodes_created)?;
|
||||
let largest = current.material_charge.max(old.material_charge);
|
||||
if largest.checked_add(remaining)? > current.limits.tokens {
|
||||
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 = self.source_mouth(self.entry)
|
||||
.relocation_from(prior.source_mouth(prior.entry))?;
|
||||
if map.relocate_offset(prior.frontier) != Some(self.frontier) {
|
||||
return None;
|
||||
}
|
||||
Some(map)
|
||||
}
|
||||
None if self.frontier == prior.frontier => None,
|
||||
None => return None,
|
||||
};
|
||||
let observes_entry_line = completed.line_observations.as_ref().is_none_or(|observations| {
|
||||
observations.get(&self.entry) != old.line_observations.get(&self.entry)
|
||||
});
|
||||
if observes_entry_line
|
||||
&& relocation.as_ref().map_or_else(
|
||||
|| !SourceRelocation::same_line_breaks(previous_bytes, current_bytes),
|
||||
|map| map.changes_line_numbers() || map.physical_framing().0.unit_width() != 1,
|
||||
)
|
||||
{
|
||||
// The old line number can be embedded in outputs. Equal byte
|
||||
// offsets can also mean different lines if a newline moved.
|
||||
// In wide encodings even a same-line edit can change the number
|
||||
// of raw CR/LF bytes counted by byte-based diagnostic fallbacks.
|
||||
return None;
|
||||
}
|
||||
let line_observations = match &completed.line_observations {
|
||||
Some(later) => Some(splice_line_observations(
|
||||
¤t.line_observations, &old.line_observations, later,
|
||||
)?),
|
||||
None => None,
|
||||
};
|
||||
// Comparison and publication visit some of the same original
|
||||
// allocations. Keep the checked relocations for this donor only.
|
||||
let mut moved = relocation.as_ref().map(EventRelocation::new);
|
||||
if !measure(timings.as_deref_mut().map(|timings| &mut timings.state_comparison), || {
|
||||
same_kernel_continuation(current, old, moved.as_mut())
|
||||
}) {
|
||||
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
|
||||
// remains within budget if its translated final count does.
|
||||
if steps > current.limits.steps {
|
||||
return None;
|
||||
}
|
||||
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
|
||||
&& !measure(timings.as_deref_mut().map(|timings| &mut timings.retained_accounting), || {
|
||||
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();
|
||||
events.extend_from_slice(tail);
|
||||
Some(Execution {
|
||||
format_dumped: completed.format_dumped,
|
||||
format_pdf_images: completed.format_pdf_images.clone(),
|
||||
job_name: completed.job_name.clone(),
|
||||
interaction_mode: completed.interaction_mode,
|
||||
native_page: completed.native_page.clone(),
|
||||
split_discards: completed.split_discards.clone(),
|
||||
after_assignment: completed.after_assignment.clone(),
|
||||
events,
|
||||
state: completed.state.clone(),
|
||||
io: completed.io.clone(),
|
||||
input_position: completed.input_position,
|
||||
paragraph_mode: completed.paragraph_mode,
|
||||
sources,
|
||||
stream_sources: completed.stream_sources.clone(),
|
||||
generated_inputs: completed.generated_inputs.clone(),
|
||||
reads: completed.reads.clone(),
|
||||
incoming_state: completed.incoming_state,
|
||||
outgoing_state: completed.outgoing_state,
|
||||
steps: completed.steps,
|
||||
reads_event_history: false,
|
||||
accounts_event_history: completed.accounts_event_history,
|
||||
let execution = measure(timings.map(|timings| &mut timings.suffix_assembly), || {
|
||||
let mut events = Vec::with_capacity(completed.events.len());
|
||||
events.extend(current.events.iter().cloned());
|
||||
let mut reads = completed.reads.clone();
|
||||
current.reads.extend_ordered_delta(&old.reads, &mut reads);
|
||||
if current.meaning_reads.len() != old.meaning_reads.len() {
|
||||
reads.extend(
|
||||
current.meaning_reads.keys()
|
||||
.filter(|name| !old.meaning_reads.contains_key(*name))
|
||||
.cloned()
|
||||
.map(Dependency::Meaning),
|
||||
);
|
||||
}
|
||||
let mut execution = Execution {
|
||||
format_dumped: completed.format_dumped,
|
||||
format_pdf_images: completed.format_pdf_images.clone(),
|
||||
job_name: completed.job_name.clone(),
|
||||
interaction_mode: completed.interaction_mode,
|
||||
native_page: completed.native_page.clone(),
|
||||
split_discards: completed.split_discards.clone(),
|
||||
after_assignment: completed.after_assignment.clone(),
|
||||
events,
|
||||
state: completed.state.clone(),
|
||||
io: completed.io.clone(),
|
||||
input_position: completed.input_position,
|
||||
paragraph_mode: completed.paragraph_mode,
|
||||
sources,
|
||||
stream_sources: completed.stream_sources.clone(),
|
||||
generated_inputs: completed.generated_inputs.clone(),
|
||||
reads,
|
||||
line_observations,
|
||||
incoming_state: completed.incoming_state,
|
||||
outgoing_state: completed.outgoing_state,
|
||||
steps,
|
||||
box_nodes_created,
|
||||
reads_event_history: false,
|
||||
accounts_event_history: completed.accounts_event_history,
|
||||
};
|
||||
if let Some((moved, sizes)) = moved.as_mut().zip(entry_sizes) {
|
||||
relocate::append_suffix(
|
||||
&mut execution, tail, offset, box_offset, moved, sizes, old.sources.len(),
|
||||
)?;
|
||||
if execution.state != completed.state {
|
||||
execution.outgoing_state = execution.state.fingerprint();
|
||||
}
|
||||
} else if offset.is_identity() && box_offset.is_identity() {
|
||||
execution.events.extend_from_slice(tail);
|
||||
} else {
|
||||
for event in tail {
|
||||
execution.events.push(match event {
|
||||
Event::Statistics(report) => Event::Statistics(Box::new(
|
||||
report.with_execution_offsets(offset, box_offset)?,
|
||||
)),
|
||||
_ => event.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(execution)
|
||||
})?;
|
||||
let layout = relocation.map(|map| RelocatedShipoutSuffix {
|
||||
// The executor records one top-level shipout event whenever
|
||||
// this count advances. Form canvases do not enter this sequence.
|
||||
first_page: old.shipped_pages,
|
||||
map,
|
||||
});
|
||||
Some((execution, layout))
|
||||
}
|
||||
/// Carry later checkpoints from the suffix accepted by
|
||||
/// splice_settled_suffix into this revision. The host must still replay
|
||||
/// each prefix and verify the resulting I/O boundary before keeping it.
|
||||
pub fn prepare_suffix_rebase<'a>(
|
||||
&'a self,
|
||||
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;
|
||||
}
|
||||
let current = &self.executor;
|
||||
let old = &prior.executor;
|
||||
// Later snapshots retain the donor's meaning cache and read history.
|
||||
// A successful splice proved key inclusion, so equal lengths prove
|
||||
// that no new meaning lookup would be lost by carrying the snapshot.
|
||||
if current.reads != old.reads
|
||||
|| current.meaning_reads.len() != old.meaning_reads.len()
|
||||
|| current.box_nodes_created != old.box_nodes_created
|
||||
|| current.material_charge != old.material_charge
|
||||
{
|
||||
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
|
||||
&& !self.executor.equivalent_accounting_history(&prior.executor)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Keep the old allocations of unchanged material, including inside
|
||||
// edited events, since later snapshots can still refer to them.
|
||||
let mut prefix = prior.executor.events.clone();
|
||||
let mut current = self.executor.events.iter();
|
||||
let mut material = MaterialReuse::default();
|
||||
for chunk in &mut prefix.prefix {
|
||||
let changes: Vec<_> = chunk.iter().zip(current.by_ref()).enumerate()
|
||||
.filter(|(_, (old, new))| !std::ptr::eq(*old, *new) && old != new)
|
||||
.map(|(index, (old, new))| {
|
||||
let mut new = new.clone();
|
||||
material.event(old, &mut new);
|
||||
(index, new)
|
||||
})
|
||||
.collect();
|
||||
if !changes.is_empty() {
|
||||
let events = Arc::make_mut(chunk);
|
||||
for (index, event) in changes {
|
||||
events[index] = event;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut adjusted_chunks = BTreeMap::new();
|
||||
Some(move |later: &Self| self.rebase_verified_suffix(prior, later, &prefix, &mut adjusted_chunks))
|
||||
}
|
||||
|
||||
fn rebase_verified_suffix(
|
||||
&self,
|
||||
prior: &Self,
|
||||
later: &Self,
|
||||
prefix: &ExecutionEvents,
|
||||
adjusted_chunks: &mut BTreeMap<usize, Arc<Vec<Event>>>,
|
||||
) -> Option<Self> {
|
||||
let old = &prior.executor;
|
||||
let next = &later.executor;
|
||||
let current = &self.executor;
|
||||
let offset = StepOffset::new(old.steps, current.steps);
|
||||
let steps = offset.apply(next.steps)?;
|
||||
if later.entry != self.entry
|
||||
|| later.active_source != self.entry
|
||||
|| later.frontier < self.frontier
|
||||
|| steps <= current.steps
|
||||
|| steps > current.limits.steps
|
||||
// An active builder can hold a budget established before
|
||||
// capture. Its limit cannot be translated by changing steps.
|
||||
|| (!offset.is_identity() && !is_idle_continuation(next))
|
||||
|| later.incoming_state != self.incoming_state
|
||||
|| next.reads_event_history
|
||||
|| !Arc::ptr_eq(&next.sources[later.entry], &old.sources[prior.entry])
|
||||
|| old.events.prefix.len() > next.events.prefix.len()
|
||||
|| !old.events.prefix.iter().zip(&next.events.prefix).all(|(a, b)| Arc::ptr_eq(a, b))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut executor = next.clone();
|
||||
executor.line_observations = splice_line_observations(
|
||||
¤t.line_observations, &old.line_observations, &next.line_observations,
|
||||
)?;
|
||||
let mut events = prefix.clone();
|
||||
// Checkpoint capture seals the event log. Share the old suffix
|
||||
// chunks so all carried checkpoints keep the same allocation graph.
|
||||
for chunk in &next.events.prefix[old.events.prefix.len()..] {
|
||||
if offset.is_identity() || !chunk.iter().any(|event| matches!(event, Event::Statistics(_))) {
|
||||
events.prefix.push(chunk.clone());
|
||||
continue;
|
||||
}
|
||||
let address = Arc::as_ptr(chunk) as usize;
|
||||
let adjusted = match adjusted_chunks.entry(address) {
|
||||
std::collections::btree_map::Entry::Occupied(entry) => entry.get().clone(),
|
||||
std::collections::btree_map::Entry::Vacant(entry) => {
|
||||
let events = chunk.iter().map(|event| offset_event_steps(event, offset))
|
||||
.collect::<Option<Vec<_>>>()?;
|
||||
entry.insert(Arc::new(events)).clone()
|
||||
}
|
||||
};
|
||||
events.prefix.push(adjusted);
|
||||
}
|
||||
events.prefix_len += next.events.prefix_len - old.events.prefix_len;
|
||||
executor.events = events;
|
||||
executor.steps = steps;
|
||||
executor.sources[self.entry] = current.sources[self.entry].clone();
|
||||
let InputFrame::Source { source, mouth, .. } = executor.inputs.first_mut()? else {
|
||||
return None;
|
||||
};
|
||||
if *source != self.entry || !mouth.rebind_after_convergence(self.source_mouth(self.entry)) {
|
||||
return None;
|
||||
}
|
||||
// A later edit can turn on tracing or force a capacity recount.
|
||||
// Keep a live checkpoint only if the merged history preserves
|
||||
// the sharing relationships needed by either accounting path.
|
||||
if !executor.equivalent_accounting_history(next) {
|
||||
return None;
|
||||
}
|
||||
Some(Self {
|
||||
executor,
|
||||
entry: later.entry,
|
||||
active_source: later.active_source,
|
||||
initial_depth: later.initial_depth,
|
||||
incoming_state: later.incoming_state,
|
||||
frontier: later.frontier,
|
||||
pages_processed: later.pages_processed,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
|
||||
fn measure<T>(elapsed: Option<&mut Duration>, action: impl FnOnce() -> T) -> T {
|
||||
let started = elapsed.is_some().then(Instant::now);
|
||||
let value = action();
|
||||
if let (Some(elapsed), Some(started)) = (elapsed, started) {
|
||||
*elapsed += started.elapsed();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
// Counts describe reads observed on a particular execution history.
|
||||
fn splice_line_observations(
|
||||
current: &BTreeMap<usize, usize>,
|
||||
prior: &BTreeMap<usize, usize>,
|
||||
later: &BTreeMap<usize, usize>,
|
||||
) -> Option<BTreeMap<usize, usize>> {
|
||||
if prior.keys().any(|source| !later.contains_key(source)) {
|
||||
return None;
|
||||
}
|
||||
let mut combined = current.clone();
|
||||
for (&source, &count) in later {
|
||||
let suffix = count.checked_sub(prior.get(&source).copied().unwrap_or_default())?;
|
||||
if suffix != 0 {
|
||||
let total = combined.entry(source).or_default();
|
||||
*total = total.checked_add(suffix)?;
|
||||
}
|
||||
}
|
||||
Some(combined)
|
||||
}
|
||||
|
||||
fn offset_event_steps(event: &Event, offset: StepOffset) -> Option<Event> {
|
||||
match event {
|
||||
Event::Statistics(report) => Some(Event::Statistics(Box::new(report.with_step_offset(offset)?))),
|
||||
_ => Some(event.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_idle_continuation(e: &Executor) -> bool {
|
||||
e.output_frame.is_none()
|
||||
&& e.paragraph.is_none()
|
||||
&& e.box_frames.is_empty()
|
||||
&& e.math.is_empty()
|
||||
&& e.display.is_none()
|
||||
&& e.alignments.is_empty()
|
||||
&& e.pdf_link_stack.is_empty()
|
||||
&& e.pdf_active_thread.is_none()
|
||||
&& e.pdf_space_probe.is_none()
|
||||
&& e.pdf_images.is_empty()
|
||||
&& !e.reads_event_history
|
||||
}
|
||||
|
||||
fn same_kernel_continuation(
|
||||
current: &Executor,
|
||||
prior: &Executor,
|
||||
relocation: Option<&mut EventRelocation<'_>>,
|
||||
) -> 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 {
|
||||
@@ -170,21 +537,18 @@ 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,
|
||||
steps,
|
||||
ligature_carry,
|
||||
current,
|
||||
expression_depth,
|
||||
scanner_depth,
|
||||
scanner_status,
|
||||
@@ -197,25 +561,14 @@ 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,
|
||||
@@ -228,8 +581,26 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
|
||||
accounts_event_history,
|
||||
],
|
||||
[
|
||||
state,
|
||||
generated_inputs,
|
||||
conditionals,
|
||||
current,
|
||||
input_position,
|
||||
line_observations,
|
||||
pdf_catalog_tokens,
|
||||
pdf_outlines,
|
||||
pdf_info_tokens,
|
||||
vertical,
|
||||
after_assignment,
|
||||
native_page,
|
||||
split_discards,
|
||||
pending_shipouts,
|
||||
inputs,
|
||||
sources,
|
||||
steps,
|
||||
box_nodes_created,
|
||||
material_charge,
|
||||
reads,
|
||||
meaning_reads,
|
||||
events,
|
||||
reads_event_history,
|
||||
@@ -251,43 +622,45 @@ fn same_kernel_continuation(current: &Executor, prior: &Executor) -> bool {
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let idle = |e: &Executor| {
|
||||
e.output_frame.is_none()
|
||||
&& e.paragraph.is_none()
|
||||
&& e.box_frames.is_empty()
|
||||
&& e.math.is_empty()
|
||||
&& e.display.is_none()
|
||||
&& e.alignments.is_empty()
|
||||
&& e.pdf_link_stack.is_empty()
|
||||
&& e.pdf_active_thread.is_none()
|
||||
&& e.pdf_space_probe.is_none()
|
||||
&& e.pdf_images.is_empty()
|
||||
&& !e.reads_event_history
|
||||
};
|
||||
if !idle(current) || !idle(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)
|
||||
&& 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()
|
||||
if current.events.len() != prior.events.len()
|
||||
|| current.inputs.len() != prior.inputs.len()
|
||||
// Statistics membership also constrains source rebinding.
|
||||
|| current.reads.observed_statistics() != prior.reads.observed_statistics()
|
||||
|| !prior.reads.is_subset(¤t.reads)
|
||||
|| prior.meaning_reads.len() > current.meaning_reads.len()
|
||||
|| !prior.meaning_reads.keys().all(|name| current.meaning_reads.contains_key(name))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if !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)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if let Some(relocation) = relocation {
|
||||
return relocate::same_kernel_provenance(current, prior, relocation).unwrap_or(false);
|
||||
}
|
||||
current.state == prior.state
|
||||
&& current.generated_inputs == prior.generated_inputs
|
||||
&& current.conditionals == prior.conditionals
|
||||
&& current.current == prior.current
|
||||
&& current.input_position == prior.input_position
|
||||
&& current.pdf_catalog_tokens == prior.pdf_catalog_tokens
|
||||
&& current.pdf_outlines == prior.pdf_outlines
|
||||
&& current.pdf_info_tokens == prior.pdf_info_tokens
|
||||
&& 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
|
||||
.inputs
|
||||
.iter()
|
||||
.zip(&prior.inputs)
|
||||
.all(|(a, b)| a.same_at_shipout(b))
|
||||
.all(|(a, b)| a.same_at_shipout(b, None))
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! Reuse equal child allocations in changed events. The accounting check
|
||||
//! still decides whether these events can accompany a carried checkpoint.
|
||||
use super::*;
|
||||
use crate::HorizontalItem;
|
||||
use crate::execution::diagnostics::DiagnosticNode;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct MaterialReuse {
|
||||
horizontal: BTreeMap<usize, Arc<Vec<TextNode>>>,
|
||||
vertical: BTreeMap<usize, Arc<Vec<NativeVerticalNode>>>,
|
||||
diagnostic: BTreeMap<usize, Arc<[DiagnosticNode]>>,
|
||||
marks: BTreeMap<usize, Arc<[Token]>>,
|
||||
}
|
||||
|
||||
fn reuse_list<T: Eq + ?Sized>(
|
||||
old: &Arc<T>,
|
||||
new: &mut Arc<T>,
|
||||
reused: &mut BTreeMap<usize, Arc<T>>,
|
||||
) -> Option<usize> {
|
||||
// The original events outlive this pass, so the input addresses stay
|
||||
// valid even after modifying a cloned event.
|
||||
let address = Arc::as_ptr(new).cast::<()>() as usize;
|
||||
if let Some(material) = reused.get(&address) {
|
||||
*new = material.clone();
|
||||
return None;
|
||||
}
|
||||
if old == new {
|
||||
*new = old.clone();
|
||||
reused.insert(address, old.clone());
|
||||
return None;
|
||||
}
|
||||
Some(address)
|
||||
}
|
||||
|
||||
impl MaterialReuse {
|
||||
pub(super) fn event(&mut self, old: &Event, new: &mut Event) {
|
||||
match (old, new) {
|
||||
(Event::Shipout(a), Event::Shipout(b)) => self.native_box(&a.box_node, &mut b.box_node),
|
||||
(Event::VerticalMaterial(a), Event::VerticalMaterial(b)) => self.vertical_nodes(a, b),
|
||||
(Event::BuiltDisplay(a), Event::BuiltDisplay(b)) => {
|
||||
self.native_box(&a.box_, &mut b.box_)
|
||||
}
|
||||
(Event::BuiltParagraph(a), Event::BuiltParagraph(b)) => {
|
||||
self.text(&a.nodes, &mut b.nodes);
|
||||
for (old, new) in a.line_boxes.iter().zip(&mut b.line_boxes) {
|
||||
self.native_box(old, new);
|
||||
}
|
||||
for (old, new) in a.line_adjustments.iter().zip(&mut b.line_adjustments) {
|
||||
self.vertical_nodes(old, new);
|
||||
}
|
||||
for (old, new) in a.diagnostic_lines.iter().zip(&mut b.diagnostic_lines) {
|
||||
self.diagnostic_nodes(&old.nodes, &mut new.nodes);
|
||||
}
|
||||
for (old, new) in a.lines.iter().zip(&mut b.lines) {
|
||||
for (old, new) in old.lines.iter().zip(&mut new.lines) {
|
||||
for (old, new) in old.iter().zip(new) {
|
||||
if let (HorizontalItem::Box(old), HorizontalItem::Box(new)) = (old, new)
|
||||
{
|
||||
self.horizontal_box(old, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn native_box(&mut self, old: &NativeBox, new: &mut NativeBox) {
|
||||
match (&old.content, &mut new.content) {
|
||||
(BoxContent::Horizontal(a), BoxContent::Horizontal(b)) => {
|
||||
if let Some(address) = reuse_list(a, b, &mut self.horizontal) {
|
||||
self.text(a.as_slice(), Arc::make_mut(b).as_mut_slice());
|
||||
self.horizontal.insert(address, b.clone());
|
||||
}
|
||||
}
|
||||
(BoxContent::Vertical(a), BoxContent::Vertical(b)) => {
|
||||
if let Some(address) = reuse_list(a, b, &mut self.vertical) {
|
||||
self.vertical_nodes(a.as_slice(), Arc::make_mut(b).as_mut_slice());
|
||||
self.vertical.insert(address, b.clone());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
self.diagnostic_nodes(&old.diagnostic, &mut new.diagnostic);
|
||||
}
|
||||
|
||||
fn horizontal_box(&mut self, old: &crate::HorizontalBox, new: &mut crate::HorizontalBox) {
|
||||
if let (Some(old), Some(new)) = (&old.native_box, &mut new.native_box) {
|
||||
self.native_box(old, new);
|
||||
}
|
||||
}
|
||||
|
||||
fn vertical_nodes(&mut self, old: &[NativeVerticalNode], new: &mut [NativeVerticalNode]) {
|
||||
use NativeVerticalNode as V;
|
||||
for (a, b) in old.iter().zip(new) {
|
||||
match (a, b) {
|
||||
(V::Box(a), V::Box(b)) | (V::Line(a), V::Line(b)) => self.native_box(a, b),
|
||||
(V::Mark(a), V::Mark(b)) => self.mark(a, b),
|
||||
(V::Insertion(a), V::Insertion(b)) => self.vertical_nodes(&a.nodes, &mut b.nodes),
|
||||
(V::Leaders(a), V::Leaders(b)) => self.leaders(a, b),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&mut self, old: &[TextNode], new: &mut [TextNode]) {
|
||||
use TextNode as T;
|
||||
for (a, b) in old.iter().zip(new) {
|
||||
match (a, b) {
|
||||
(T::Glyph { glyph: a, .. }, T::Glyph { glyph: b, .. })
|
||||
| (T::Box(a), T::Box(b))
|
||||
| (T::MathChar(a), T::MathChar(b)) => self.horizontal_box(a, b),
|
||||
(
|
||||
T::Discretionary {
|
||||
pre_break: pre_a,
|
||||
post_break: post_a,
|
||||
..
|
||||
},
|
||||
T::Discretionary {
|
||||
pre_break: pre_b,
|
||||
post_break: post_b,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
self.text(pre_a, pre_b);
|
||||
self.text(post_a, post_b);
|
||||
}
|
||||
(T::Mark(a), T::Mark(b)) => self.mark(a, b),
|
||||
(T::Adjustment(a), T::Adjustment(b)) => self.vertical_nodes(&a.nodes, &mut b.nodes),
|
||||
(T::Insertion(a), T::Insertion(b)) => self.vertical_nodes(&a.nodes, &mut b.nodes),
|
||||
(T::Leaders(a), T::Leaders(b)) => self.leaders(a, b),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn diagnostic_nodes(&mut self, old: &Arc<[DiagnosticNode]>, new: &mut Arc<[DiagnosticNode]>) {
|
||||
if let Some(address) = reuse_list(old, new, &mut self.diagnostic) {
|
||||
self.diagnostics(old, Arc::make_mut(new));
|
||||
self.diagnostic.insert(address, new.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn diagnostics(&mut self, old: &[DiagnosticNode], new: &mut [DiagnosticNode]) {
|
||||
use DiagnosticNode as D;
|
||||
for (a, b) in old.iter().zip(new) {
|
||||
match (a, b) {
|
||||
(D::Box(a), D::Box(b)) => self.diagnostic_nodes(&a.nodes, &mut b.nodes),
|
||||
(D::Leaders { pattern: a, .. }, D::Leaders { pattern: b, .. }) => {
|
||||
self.diagnostics(
|
||||
std::slice::from_ref(a.as_ref()),
|
||||
std::slice::from_mut(b.as_mut()),
|
||||
);
|
||||
}
|
||||
(
|
||||
D::Discretionary {
|
||||
pre: pre_a,
|
||||
post: post_a,
|
||||
..
|
||||
},
|
||||
D::Discretionary {
|
||||
pre: pre_b,
|
||||
post: post_b,
|
||||
..
|
||||
},
|
||||
) => {
|
||||
self.diagnostics(pre_a, pre_b);
|
||||
self.diagnostics(post_a, post_b);
|
||||
}
|
||||
(D::Mark(a), D::Mark(b)) => self.mark(a, b),
|
||||
(D::Adjustment { nodes: a, .. }, D::Adjustment { nodes: b, .. })
|
||||
| (D::Insertion { nodes: a, .. }, D::Insertion { nodes: b, .. }) => {
|
||||
self.diagnostics(a, b)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mark(&mut self, old: &NativeMark, new: &mut NativeMark) {
|
||||
let _ = reuse_list(&old.tokens, &mut new.tokens, &mut self.marks);
|
||||
}
|
||||
|
||||
fn leaders(&mut self, old: &LeaderGlue, new: &mut LeaderGlue) {
|
||||
if let (LeaderPattern::Box(old), LeaderPattern::Box(new)) = (&old.pattern, &mut new.pattern)
|
||||
{
|
||||
self.native_box(old, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
use super::*;
|
||||
use crate::execution::{source_relocation_events::EventRelocation, statistics::BoxNodeOffset};
|
||||
|
||||
pub(super) fn same_kernel_provenance(
|
||||
current: &Executor,
|
||||
prior: &Executor,
|
||||
relocation: &mut EventRelocation<'_>,
|
||||
) -> Option<bool> {
|
||||
let map = relocation.map();
|
||||
if current.current != map.relocate_span(prior.current)?
|
||||
|| current.input_position != map.relocate_position(prior.input_position)?
|
||||
{
|
||||
return Some(false);
|
||||
}
|
||||
for (current, prior) in current.inputs.iter().zip(&prior.inputs) {
|
||||
if matches!(prior, InputFrame::Source { .. } | InputFrame::Boundary) {
|
||||
if !current.same_at_shipout(prior, Some(map)) {
|
||||
return Some(false);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let mut frame = prior.clone();
|
||||
match &mut frame {
|
||||
InputFrame::Tokens { tokens, .. } => match tokens {
|
||||
InputTokens::One(token) => relocation.relocate_token(&mut token.token)?,
|
||||
InputTokens::Many(tokens) => {
|
||||
for token in tokens {
|
||||
relocation.relocate_token(&mut token.token)?;
|
||||
}
|
||||
}
|
||||
},
|
||||
InputFrame::Macro {
|
||||
definition,
|
||||
arguments,
|
||||
call,
|
||||
..
|
||||
} => {
|
||||
*definition = relocation.relocate_macro(definition)?;
|
||||
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)?,
|
||||
InputFrame::Source { .. } | InputFrame::Boundary => unreachable!(),
|
||||
}
|
||||
if !current.same_at_shipout(&frame, None) {
|
||||
return Some(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Compare only the fields that can hold changed source coordinates.
|
||||
// The unchanged caches and counters never need an owned copy.
|
||||
let mut generated = prior.generated_inputs.clone();
|
||||
relocate_generated(&mut generated, map)?;
|
||||
let mut conditionals = prior.conditionals.clone();
|
||||
for conditional in &mut conditionals {
|
||||
conditional.span = map.relocate_span(conditional.span)?;
|
||||
conditional.origin = map.relocate_position(conditional.origin)?;
|
||||
}
|
||||
let mut catalog = prior.pdf_catalog_tokens.clone();
|
||||
let mut info = prior.pdf_info_tokens.clone();
|
||||
let mut outlines = prior.pdf_outlines.clone();
|
||||
relocate_tokens(&mut catalog, relocation)?;
|
||||
relocate_tokens(&mut info, relocation)?;
|
||||
for outline in &mut outlines {
|
||||
relocate_tokens(&mut outline.attributes, relocation)?;
|
||||
}
|
||||
let mut after_assignment = prior.after_assignment.clone();
|
||||
if let Some(token) = &mut after_assignment {
|
||||
relocation.relocate_token(token)?;
|
||||
}
|
||||
let mut vertical = prior.vertical.clone();
|
||||
let mut discards = prior.split_discards.clone();
|
||||
let mut native_page = prior.native_page.clone();
|
||||
let mut pending_shipouts = prior.pending_shipouts.clone();
|
||||
relocation.relocate_vertical(&mut vertical.nodes)?;
|
||||
relocation.relocate_vertical(&mut discards)?;
|
||||
relocate_page(&mut native_page, relocation)?;
|
||||
for value in &mut pending_shipouts {
|
||||
relocation.relocate_box(value)?;
|
||||
}
|
||||
if current.generated_inputs != generated
|
||||
|| current.conditionals != conditionals
|
||||
|| current.pdf_catalog_tokens != catalog
|
||||
|| current.pdf_info_tokens != info
|
||||
|| current.pdf_outlines != outlines
|
||||
|| current.after_assignment != after_assignment
|
||||
|| current.vertical != vertical
|
||||
|| current.split_discards != discards
|
||||
|| current.native_page != native_page
|
||||
|| current.pending_shipouts != pending_shipouts
|
||||
{
|
||||
return Some(false);
|
||||
}
|
||||
|
||||
let mut state = prior.state.clone();
|
||||
state.relocate_source(relocation)?;
|
||||
Some(current.state == state)
|
||||
}
|
||||
|
||||
pub(super) fn append_suffix(
|
||||
execution: &mut Execution,
|
||||
tail: &[Event],
|
||||
offset: StepOffset,
|
||||
boxes: BoxNodeOffset,
|
||||
relocation: &mut EventRelocation<'_>,
|
||||
(previous_bytes, current_bytes): (usize, usize),
|
||||
source_count: usize,
|
||||
) -> Option<()> {
|
||||
let map = relocation.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_execution_offsets(offset, boxes)?
|
||||
.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)?);
|
||||
}
|
||||
}
|
||||
execution.input_position = map.relocate_position(execution.input_position)?;
|
||||
execution.state.relocate_source(relocation)?;
|
||||
relocate_page(&mut execution.native_page, relocation)?;
|
||||
relocation.relocate_vertical(&mut execution.split_discards)?;
|
||||
if let Some(token) = &mut execution.after_assignment {
|
||||
relocation.relocate_token(token)?;
|
||||
}
|
||||
relocate_generated(&mut execution.generated_inputs, map)?;
|
||||
for image in &mut execution.format_pdf_images {
|
||||
relocate_tokens(&mut image.attributes, 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 {
|
||||
relocation.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)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> {
|
||||
for token in tokens {
|
||||
relocation.relocate_token(token)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
@@ -43,6 +43,7 @@ impl Executor {
|
||||
record.push_str(&format!("(level {level})"));
|
||||
if let Some((source, line)) = origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
record.push_str(&format!(" entered on line {line}"));
|
||||
}
|
||||
@@ -208,6 +209,11 @@ impl Executor {
|
||||
self.reads.insert(Dependency::EscapeChar);
|
||||
self.reads.insert(Dependency::NewLineChar);
|
||||
let context = self.input_context();
|
||||
for frame in &context.frames {
|
||||
if let ContextKind::Source { source, .. } = frame.kind {
|
||||
self.observe_line_number(source);
|
||||
}
|
||||
}
|
||||
self.reads.extend(context.reads.iter().cloned());
|
||||
context
|
||||
}
|
||||
@@ -457,6 +463,11 @@ impl Executor {
|
||||
let (body, dependencies) = self
|
||||
.activity_lists(breadth, depth, wrap)
|
||||
.map_err(|message| self.error(message, span))?;
|
||||
for dependency in &dependencies {
|
||||
if let Dependency::InputPosition(source) = dependency {
|
||||
self.observe_line_number(*source);
|
||||
}
|
||||
}
|
||||
self.reads.extend(dependencies);
|
||||
body
|
||||
}
|
||||
@@ -523,6 +534,7 @@ impl Executor {
|
||||
}
|
||||
if let Some((source, line)) = frame.origin.filter(|(_, line)| *line != 0) {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
description.push_str(&format!(" entered on line {line}"));
|
||||
}
|
||||
format!("### level {}: {description}", index + 1)
|
||||
@@ -547,6 +559,7 @@ impl Executor {
|
||||
);
|
||||
if let Some((source, line)) = origin.filter(|(_, line)| *line != 0) {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
*self.line_observations.entry(source).or_default() += 1;
|
||||
text.push_str(&format!(" entered at line {line}"));
|
||||
}
|
||||
let detail = if let Some(frame) =
|
||||
|
||||
@@ -124,7 +124,8 @@ impl Executor {
|
||||
Err((span, text)) => Next::Error(span, text),
|
||||
};
|
||||
if !warnings.is_empty() {
|
||||
self.observe_xe_utf8_warnings(warnings, files)?;
|
||||
let source = *source;
|
||||
self.observe_xe_utf8_warnings(Some(source), warnings, files)?;
|
||||
}
|
||||
next
|
||||
}
|
||||
@@ -252,9 +253,13 @@ impl Executor {
|
||||
|
||||
pub(super) fn observe_xe_utf8_warnings(
|
||||
&mut self,
|
||||
source: Option<usize>,
|
||||
warnings: Vec<(usize, usize)>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
if !warnings.is_empty() && let Some(source) = source {
|
||||
self.observe_line_number(source);
|
||||
}
|
||||
for (line, count) in warnings {
|
||||
self.observe_xe_input_warning(
|
||||
&format!("\nInvalid UTF-8 byte or sequence at line {line} replaced by U+FFFD.\n"),
|
||||
|
||||
@@ -121,6 +121,7 @@ impl Executor {
|
||||
);
|
||||
if let Some((source, line)) = origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
name.push_str(&format!(" entered at line {line}"));
|
||||
}
|
||||
@@ -146,6 +147,7 @@ impl Executor {
|
||||
}
|
||||
if let Some((source, line)) = frame.origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
name.push_str(&format!(" entered on line {line}"));
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use crate::pdf_device::{
|
||||
Affine, PdfGraphics,
|
||||
catalog::{CatalogAction, CatalogTarget, StructureTarget},
|
||||
@@ -43,7 +44,7 @@ pub(super) struct ActiveThread {
|
||||
enum LinkPaint {
|
||||
Graphics,
|
||||
RowStart(BoxLayout),
|
||||
Node(BoxLayout),
|
||||
Node(BoxLayout, Option<usize>),
|
||||
}
|
||||
|
||||
pub(super) struct PdfLinkShipout {
|
||||
@@ -57,6 +58,7 @@ pub(super) struct PdfLinkShipout {
|
||||
graphics_index: usize,
|
||||
output: PageLinks,
|
||||
direct_annotations: Vec<LinkAnnotation>,
|
||||
leader_links: BTreeMap<usize, Vec<usize>>,
|
||||
origin: [i64; 2],
|
||||
margin: i64,
|
||||
numbered: bool,
|
||||
@@ -400,7 +402,9 @@ impl Executor {
|
||||
BoxPaint::Box(_) => paint_count += 1,
|
||||
BoxPaint::RowStart(row) if row.horizontal || thread_rows =>
|
||||
events.push(((output_count, paint_count), x, y, LinkPaint::RowStart(row))),
|
||||
BoxPaint::PdfLink(_, row) => events.push(((output_count, paint_count), x, y, LinkPaint::Node(row))),
|
||||
BoxPaint::PdfLink(_, row, leader_link) => events.push((
|
||||
(output_count, paint_count), x, y, LinkPaint::Node(row, leader_link),
|
||||
)),
|
||||
BoxPaint::PdfGraphics => events.push(((output_count, paint_count), x, y, LinkPaint::Graphics)),
|
||||
_ => {}
|
||||
});
|
||||
@@ -416,6 +420,7 @@ impl Executor {
|
||||
graphics_index: 0,
|
||||
output: PageLinks::default(),
|
||||
direct_annotations: Vec::new(),
|
||||
leader_links: BTreeMap::new(),
|
||||
origin: [device.horizontal_origin, device.vertical_origin + b.height],
|
||||
margin: i64::from(self.read_parameter(Parameter::Pdflinkmargin).width()),
|
||||
numbered,
|
||||
@@ -503,7 +508,7 @@ impl PdfLinkShipout {
|
||||
self.output.annotations.last_mut().unwrap().object_number = number;
|
||||
}
|
||||
}
|
||||
LinkPaint::Node(container) => {
|
||||
LinkPaint::Node(container, leader_link) => {
|
||||
let node = outputs[output_index - 1];
|
||||
let OutputOperation::PdfLink(link) = &node.operation else {
|
||||
return executor.fail("PDF navigation and output traversal diverged");
|
||||
@@ -570,6 +575,22 @@ impl PdfLinkShipout {
|
||||
};
|
||||
let mut start = ActiveLink { layout: layout.clone(), attributes,
|
||||
action, level: container.level, segment: None };
|
||||
if self.numbered && let Some(slot) = leader_link {
|
||||
let annotations = self.leader_links.entry(slot).or_default();
|
||||
if let Some(&previous) = annotations.last() {
|
||||
// pdfTeX stores the rectangle in the same words as
|
||||
// the declared width, height and depth.
|
||||
let [left, top, right, _] = self.output.annotations[previous].rect;
|
||||
let [width, height, depth] = [left, top, right].map(|value| {
|
||||
let value = value as i32;
|
||||
(value != -(1 << 30)).then_some(value)
|
||||
});
|
||||
start.layout.width = width;
|
||||
start.layout.height = height;
|
||||
start.layout.depth = depth;
|
||||
}
|
||||
annotations.push(self.output.annotations.len());
|
||||
}
|
||||
start.start_segment(&mut self.output, container, [x, y], &mut self.geometry,
|
||||
self.page_height, self.margin);
|
||||
self.output.annotations.last_mut().unwrap().object_number = number;
|
||||
@@ -648,6 +669,14 @@ impl PdfLinkShipout {
|
||||
if self.numbered {
|
||||
executor.pdf_navigation_geometry = self.geometry;
|
||||
}
|
||||
// Every scheduled object for this node reads its final rectangle.
|
||||
for annotations in self.leader_links.values() {
|
||||
let (&last, earlier) = annotations.split_last().unwrap();
|
||||
let rect = self.output.annotations[last].rect;
|
||||
for &index in earlier {
|
||||
self.output.annotations[index].rect = rect;
|
||||
}
|
||||
}
|
||||
if !self.direct_annotations.is_empty() {
|
||||
self.direct_annotations.append(&mut self.output.annotations);
|
||||
self.output.annotations = self.direct_annotations;
|
||||
|
||||
@@ -108,6 +108,7 @@ impl Executor {
|
||||
let mut message = format!("{{{action} {name} group (level {level})");
|
||||
if let Some((source, line)) = origin {
|
||||
self.reads.insert(Dependency::InputPosition(source));
|
||||
self.observe_line_number(source);
|
||||
if line != 0 {
|
||||
let location = if entering {
|
||||
"at line"
|
||||
|
||||
@@ -181,7 +181,64 @@ impl Executor {
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_event_usage_pair(
|
||||
current: &ExecutionEvents,
|
||||
prior: &ExecutionEvents,
|
||||
mut history: Collector,
|
||||
) -> (Collector, Collector) {
|
||||
// Identical sealed chunks also own the same allocations. Copy the
|
||||
// accounting state at this boundary so each tail still deduplicates
|
||||
// its references against the whole prefix.
|
||||
let shared = current
|
||||
.prefix
|
||||
.iter()
|
||||
.zip(&prior.prefix)
|
||||
.take_while(|(a, b)| Arc::ptr_eq(a, b))
|
||||
.count();
|
||||
Self::collect_event_usage(
|
||||
current.prefix[..shared].iter().flat_map(|chunk| chunk.iter()),
|
||||
&mut history,
|
||||
);
|
||||
let mut old_history = history.clone();
|
||||
for (events, counts) in [(current, &mut history), (prior, &mut old_history)] {
|
||||
Self::collect_event_usage(
|
||||
events.prefix[shared..]
|
||||
.iter()
|
||||
.flat_map(|chunk| chunk.iter())
|
||||
.chain(&events.tail),
|
||||
counts,
|
||||
);
|
||||
}
|
||||
(history, old_history)
|
||||
}
|
||||
|
||||
pub(super) fn resize_entry_statistics(
|
||||
&mut self,
|
||||
previous: usize,
|
||||
current: usize,
|
||||
replayed_entry_bytes: Option<u64>,
|
||||
) -> Option<()> {
|
||||
let events = self.events.prefix.iter_mut()
|
||||
.filter(|chunk| chunk.iter().any(|event| matches!(event, Event::Statistics(_))))
|
||||
.flat_map(|chunk| Arc::make_mut(chunk).iter_mut())
|
||||
.chain(&mut self.events.tail);
|
||||
for event in events {
|
||||
if let Event::Statistics(report) = event {
|
||||
report.resize_entry_payload(previous, current, replayed_entry_bytes)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
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| {
|
||||
@@ -193,12 +250,20 @@ impl Executor {
|
||||
}
|
||||
|
||||
[Collector::for_capacity, Collector::default].into_iter().all(|collector| {
|
||||
let mut history = collector();
|
||||
let mut old_history = collector();
|
||||
Self::collect_event_usage(self.events.iter(), &mut history);
|
||||
Self::collect_event_usage(old.events.iter(), &mut old_history);
|
||||
let live = self.collect_live_usage(None, None, collector().tracking_aliases());
|
||||
let (history, old_history) =
|
||||
Self::collect_event_usage_pair(&self.events, &old.events, collector());
|
||||
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases());
|
||||
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
|
||||
// The splice translates the cumulative counters separately.
|
||||
live.usage.steps = old_live.usage.steps;
|
||||
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -229,20 +294,9 @@ impl Executor {
|
||||
.resource_usage()
|
||||
.map_err(|e| self.error(e, self.current))?;
|
||||
let after = self.resource_usage(None, host);
|
||||
let text = format!(
|
||||
"Route-D resources at shipout: active records {} -> {}; retained records {} -> {}; token cells {} -> {}; retained pages {}.\n",
|
||||
before.active_material.records(),
|
||||
after.active_material.records(),
|
||||
before.retained_material.records(),
|
||||
after.retained_material.records(),
|
||||
before.macro_token_cells + before.token_list_cells,
|
||||
after.macro_token_cells + after.token_list_cells,
|
||||
after.retained_shipouts
|
||||
);
|
||||
self.emit_statistics(
|
||||
StatisticsPhase::Shipout { before, after },
|
||||
WriteDestination::TerminalAndLog,
|
||||
text,
|
||||
files,
|
||||
)
|
||||
}
|
||||
@@ -259,46 +313,9 @@ impl Executor {
|
||||
.resource_usage()
|
||||
.map_err(|e| self.error(e, self.current))?;
|
||||
let usage = self.resource_usage(None, host);
|
||||
let mut text = format!(
|
||||
"Route-D resource usage at core execution end ({}):\n {} steps out of {}\n {} source files, {} source payload bytes, {} active mouth payload bytes\n {} command entries, {} control-name bytes\n {} macro bindings, {} unique macro bodies, {} macro token cells\n {} token-list cells, {} saved entries\n {} active material records, {} retained material records, {} retained pages\n {} font instances, {} font parameter cells, {} TFM resources / {} source bytes\n {} hyphenation exceptions\n stack peaks: {} input, {} group, {} box, {} math, {} conditional, {} scanner, {} expansion\n",
|
||||
if success { "success" } else { "failure" },
|
||||
usage.steps,
|
||||
usage.step_limit,
|
||||
usage.source_files,
|
||||
usage.source_payload_bytes,
|
||||
usage.mouth_payload_bytes,
|
||||
usage.state.command_entries,
|
||||
usage.state.control_name_bytes,
|
||||
usage.state.macro_bindings,
|
||||
usage.unique_macro_bodies,
|
||||
usage.macro_token_cells,
|
||||
usage.token_list_cells,
|
||||
usage.state.save_entries,
|
||||
usage.active_material.records(),
|
||||
usage.retained_material.records(),
|
||||
usage.retained_shipouts,
|
||||
usage.state.font_instances,
|
||||
usage.state.font_parameter_cells,
|
||||
usage.state.tfm_resources,
|
||||
usage.state.tfm_resource_bytes,
|
||||
usage.state.hyphenation_exceptions,
|
||||
usage.stack_peaks.input_frames,
|
||||
usage.stack_peaks.groups,
|
||||
usage.stack_peaks.box_frames,
|
||||
usage.stack_peaks.math_frames,
|
||||
usage.stack_peaks.conditionals,
|
||||
usage.stack_peaks.scanner_depth,
|
||||
usage.stack_peaks.expansion_depth
|
||||
);
|
||||
if let Some(h) = &usage.host {
|
||||
text.push_str(&format!(" host resources: {} reads / {} bytes; {} lookups / {} misses / {} errors; {} stream reads / {} bytes\n",h.resource_reads,h.resource_bytes_read,h.lookups,h.negative_lookups,h.failed_lookups,h.stream_read_calls,h.stream_bytes_read));
|
||||
} else {
|
||||
text.push_str(" host resource telemetry unavailable\n");
|
||||
}
|
||||
self.emit_statistics(
|
||||
StatisticsPhase::End { success, usage },
|
||||
WriteDestination::Log,
|
||||
text,
|
||||
files,
|
||||
)
|
||||
}
|
||||
@@ -306,23 +323,59 @@ impl Executor {
|
||||
&mut self,
|
||||
phase: StatisticsPhase,
|
||||
destination: WriteDestination,
|
||||
text: String,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(text.len());
|
||||
let report = StatisticsReport::new(phase, destination, self.current);
|
||||
self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(report.text.len());
|
||||
if self.diagnostic_bytes > self.limits.tokens {
|
||||
return self.fail("native diagnostic output limit exceeded");
|
||||
}
|
||||
files
|
||||
.observe_diagnostic(destination, &text)
|
||||
.observe_statistics(&report)
|
||||
.map_err(|e| self.error(e, self.current))?;
|
||||
self.events
|
||||
.push(Event::Statistics(Box::new(StatisticsReport {
|
||||
phase,
|
||||
destination,
|
||||
text,
|
||||
span: self.current,
|
||||
})));
|
||||
self.events.push(Event::Statistics(Box::new(report)));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn shared_event_prefix_keeps_tail_deduplication_and_membership() {
|
||||
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
|
||||
let shared: Arc<[Token]> = Arc::from([token.clone()]);
|
||||
let independent: Arc<[Token]> = Arc::from([token]);
|
||||
let mark = |tokens| {
|
||||
Event::VerticalMaterial(vec![NativeVerticalNode::Mark(NativeMark {
|
||||
class: 0,
|
||||
tokens,
|
||||
span: Span::default(),
|
||||
})])
|
||||
};
|
||||
|
||||
let mut current = ExecutionEvents::default();
|
||||
current.push(mark(shared.clone()));
|
||||
current.seal_prefix();
|
||||
let mut prior = current.clone();
|
||||
current.push(mark(shared.clone()));
|
||||
prior.push(mark(independent.clone()));
|
||||
|
||||
for collector in [Collector::for_capacity, Collector::default] {
|
||||
let (history, old_history) =
|
||||
Executor::collect_event_usage_pair(¤t, &prior, collector());
|
||||
assert_eq!(history.usage.token_list_cells, 1);
|
||||
assert_eq!(old_history.usage.token_list_cells, 2);
|
||||
|
||||
let mut live = collector().tracking_aliases();
|
||||
live.shared_tokens(&shared);
|
||||
live.shared_tokens(&independent);
|
||||
for (events, paired) in [(¤t, history), (&prior, old_history)] {
|
||||
let mut full = collector();
|
||||
Executor::collect_event_usage(events.iter(), &mut full);
|
||||
assert!(live.has_equivalent_history(&live, &paired, &full));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -55,6 +57,7 @@ mod vertical_break;
|
||||
pub use statistics::{
|
||||
HostResourceUsage, MaterialUsage, ResourceUsage, StackUsage, StateUsage, StatisticsPhase,
|
||||
StatisticsReport,
|
||||
StepOffset,
|
||||
};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt;
|
||||
@@ -68,7 +71,10 @@ pub use case::CaseCode;
|
||||
pub use context::{ContextFrame, ContextKind, InputContext};
|
||||
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
|
||||
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
|
||||
pub use engine::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits};
|
||||
pub use engine::{
|
||||
CheckpointDecision, CheckpointSource, EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix,
|
||||
SuffixKernelTimings,
|
||||
};
|
||||
pub use font_catalog::{
|
||||
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
|
||||
};
|
||||
@@ -375,6 +381,15 @@ pub trait SourceProvider {
|
||||
) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
/// Size of the entry read already validated by the host's prefix replay.
|
||||
/// Hosts that report resource telemetry can opt in to resizing that read.
|
||||
fn replayed_entry_bytes(&self) -> Option<u64> {
|
||||
None
|
||||
}
|
||||
/// Observe resource accounting while preserving the typed report for replay.
|
||||
fn observe_statistics(&mut self, report: &StatisticsReport) -> Result<(), String> {
|
||||
self.observe_diagnostic(report.destination, &report.text)
|
||||
}
|
||||
/// Observe a diagnostic that starts at the current output column.
|
||||
fn observe_inline_diagnostic(
|
||||
&mut self,
|
||||
@@ -666,9 +681,15 @@ pub struct Execution {
|
||||
/// Reads made during this execution, not a license to reuse output after
|
||||
/// state changes. Incremental execution/cache reuse is a later milestone.
|
||||
pub reads: BTreeSet<Dependency>,
|
||||
/// Per-source observations distinguish suffix reads from identical prefix reads.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
line_observations: Option<BTreeMap<usize, usize>>,
|
||||
pub incoming_state: u64,
|
||||
pub outgoing_state: u64,
|
||||
pub steps: usize,
|
||||
/// Completed charge count for proving remaining box capacity at a splice.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
box_nodes_created: Option<usize>,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
reads_event_history: bool,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
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, XeLineFraming},
|
||||
};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct XePhysical {
|
||||
encoding: Encoding,
|
||||
autodetected: Option<(Encoding, usize)>,
|
||||
// A decoder can change without changing which code units end a line.
|
||||
// Once framing varies, the prefix cannot be counted in one mode.
|
||||
framing_history: Option<XeLineFraming>,
|
||||
skip_lf: bool,
|
||||
terminated: bool,
|
||||
line_start: usize,
|
||||
@@ -252,6 +258,133 @@ 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 relocated_mouth_maps_whole_lines_only_under_static_framing() {
|
||||
use super::super::InputProfile;
|
||||
|
||||
let shorter = b"cover\r\nunchanged\r\nlater\r\n";
|
||||
let longer = b"cover\r\n% note\r\nunchanged\r\nlater\r\n";
|
||||
let insert = SourceRelocation::new(4, shorter, longer).unwrap();
|
||||
let delete = SourceRelocation::new(4, longer, shorter).unwrap();
|
||||
for profile in [InputProfile::TeX8Bit, InputProfile::UnicodeScalar, InputProfile::XeTeX] {
|
||||
let state = State::default().with_input_profile(profile);
|
||||
let mut reads = DependencyReads::default();
|
||||
let mut old = Mouth::new(4, shorter.to_vec(), profile);
|
||||
let mut current = Mouth::new(4, longer.to_vec(), profile);
|
||||
assert!(old.load_line(&state, &mut reads).unwrap());
|
||||
assert!(current.load_line(&state, &mut reads).unwrap());
|
||||
assert!(!current.same_unread_input_relocated(&old, &insert));
|
||||
if profile == InputProfile::XeTeX {
|
||||
assert!(old.change_encoding(Encoding::Bytes));
|
||||
assert!(current.change_encoding(Encoding::Bytes));
|
||||
}
|
||||
assert!(old.load_line(&state, &mut reads).unwrap());
|
||||
assert!(current.load_line(&state, &mut reads).unwrap());
|
||||
assert!(!current.same_unread_input_relocated(&old, &insert));
|
||||
assert!(current.load_line(&state, &mut reads).unwrap());
|
||||
assert!(current.same_unread_input_relocated(&old, &insert));
|
||||
assert!(old.same_unread_input_relocated(¤t, &delete));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocated_xetex_lines_use_the_loaded_utf16_framing() {
|
||||
use super::super::InputProfile;
|
||||
let state = State::default().with_input_profile(InputProfile::XeTeX);
|
||||
for (bom, encode) in [
|
||||
([0xff, 0xfe], u16::to_le_bytes as fn(u16) -> [u8; 2]),
|
||||
([0xfe, 0xff], u16::to_be_bytes),
|
||||
] {
|
||||
let physical = |text: &str| {
|
||||
bom.into_iter().chain(text.encode_utf16().flat_map(encode)).collect()
|
||||
};
|
||||
let mut previous = Mouth::new(
|
||||
4, physical("cover\r\n\u{010a} next"), InputProfile::XeTeX,
|
||||
);
|
||||
let mut current = Mouth::new(
|
||||
4, physical("cover\r\n% note\r\n\u{010a} next"), InputProfile::XeTeX,
|
||||
);
|
||||
let mut reads = DependencyReads::default();
|
||||
for _ in 0..2 {
|
||||
assert!(previous.load_line(&state, &mut reads).unwrap());
|
||||
assert!(current.load_line(&state, &mut reads).unwrap());
|
||||
}
|
||||
let insert = current.relocation_from(&previous).unwrap();
|
||||
assert!(!current.same_unread_input_relocated(&previous, &insert));
|
||||
assert!(current.load_line(&state, &mut reads).unwrap());
|
||||
assert!(current.same_unread_input_relocated(&previous, &insert));
|
||||
|
||||
let delete = previous.relocation_from(¤t).unwrap();
|
||||
assert!(previous.same_unread_input_relocated(¤t, &delete));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matching_current_decoder_cannot_prove_a_mixed_prefix() {
|
||||
use super::super::InputProfile;
|
||||
let source = |comment: &[u8]| {
|
||||
b"head\n".iter().copied()
|
||||
.chain("\u{050a}\n".encode_utf16().flat_map(u16::to_le_bytes))
|
||||
.chain(b"before\n".iter().copied())
|
||||
.chain(comment.iter().copied())
|
||||
.chain(b"entry\nanchor\nend\n".iter().copied())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let previous = source(b"");
|
||||
let current = source(b"% note\n");
|
||||
let raw_map = SourceRelocation::new(4, &previous, ¤t).unwrap();
|
||||
let mut previous = Mouth::new(4, previous, InputProfile::XeTeX);
|
||||
let mut current = Mouth::new(4, current, InputProfile::XeTeX);
|
||||
let state = State::default().with_input_profile(InputProfile::XeTeX);
|
||||
let mut reads = DependencyReads::default();
|
||||
for mouth in [&mut previous, &mut current] {
|
||||
assert!(mouth.load_line(&state, &mut reads).unwrap());
|
||||
assert!(mouth.change_encoding(Encoding::Utf16Le));
|
||||
assert!(mouth.load_line(&state, &mut reads).unwrap());
|
||||
assert!(mouth.change_encoding(Encoding::Utf8));
|
||||
for _ in 0..3 {
|
||||
assert!(mouth.load_line(&state, &mut reads).unwrap());
|
||||
}
|
||||
}
|
||||
assert!(current.load_line(&state, &mut reads).unwrap());
|
||||
assert_eq!(raw_map.relocate_line(previous.line_number), Some(current.line_number));
|
||||
assert_eq!(raw_map.relocate_offset(previous.offset), Some(current.offset));
|
||||
assert!(current.relocation_from(&previous).is_none());
|
||||
assert!(!current.same_unread_input_relocated(&previous, &raw_map));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn physical_line_endings_and_utf8_byte_offsets_are_preserved() {
|
||||
let result = tokens("é界 \r\nB\rC");
|
||||
@@ -297,21 +430,114 @@ 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.line_number == other.line_number
|
||||
&& self.offset == other.offset
|
||||
&& self.line == other.line
|
||||
&& self.xe == other.xe
|
||||
&& self.data[self.offset..] == other.data[other.offset..]
|
||||
}
|
||||
|
||||
pub(super) fn relocation_from(&self, old: &Self) -> Option<SourceRelocation> {
|
||||
let (framing, content_start) = self.physical_framing()?;
|
||||
if self.source != old.source || old.physical_framing() != Some((framing, content_start)) {
|
||||
return None;
|
||||
}
|
||||
if framing == XeLineFraming::Bytes && content_start == 0 {
|
||||
SourceRelocation::new(self.source, &old.data, &self.data)
|
||||
} else {
|
||||
SourceRelocation::with_framing(
|
||||
self.source, &old.data, &self.data, framing, content_start,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn physical_framing(&self) -> Option<(XeLineFraming, usize)> {
|
||||
if !matches!(self.line_breaks, LineBreaks::Physical) {
|
||||
return None;
|
||||
}
|
||||
match &self.xe {
|
||||
Some(xe) => Some((
|
||||
xe.framing_history?,
|
||||
xe.autodetected.as_ref().map_or(0, |(_, bom)| *bom),
|
||||
)),
|
||||
None => Some((XeLineFraming::Bytes, 0)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn same_unread_input_relocated(
|
||||
&self,
|
||||
old: &Self,
|
||||
relocation: &SourceRelocation,
|
||||
) -> bool {
|
||||
if self.source != relocation.source()
|
||||
|| !self.same_unread_state(old)
|
||||
|| self.physical_framing() != Some(relocation.physical_framing())
|
||||
|| old.physical_framing() != Some(relocation.physical_framing())
|
||||
|| relocation.relocate_line(old.line_number) != Some(self.line_number)
|
||||
|| self.physical_frontier().is_none()
|
||||
|| old.physical_frontier().is_none()
|
||||
|| relocation.relocate_offset(old.offset) != Some(self.offset)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let (start, old_start) = match (&self.xe, &old.xe) {
|
||||
(Some(current), Some(previous))
|
||||
if current.encoding == previous.encoding
|
||||
&& current.autodetected == previous.autodetected
|
||||
&& current.skip_lf == previous.skip_lf
|
||||
&& current.terminated == previous.terminated
|
||||
&& (current.terminated
|
||||
|| (self.offset == self.data.len() && old.offset == old.data.len())) =>
|
||||
{
|
||||
(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_offset(old_start) == Some(start)
|
||||
&& self.data[start..] == old.data[old_start..]
|
||||
&& self.line.len() == old.line.len()
|
||||
&& self.line.iter().zip(&old.line).all(|(new, old)| {
|
||||
new.value == old.value
|
||||
&& relocation.relocate_loaded_offset(old.start) == Some(new.start)
|
||||
&& relocation.relocate_loaded_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"))
|
||||
.or_else(|| (self.offset == self.data.len()).then_some(prefix))?;
|
||||
Some(content.iter().rposition(|b| matches!(b, b'\r' | b'\n')).map_or(0, |i| i + 1))
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -350,6 +576,15 @@ impl Mouth {
|
||||
debug_assert!(self.matches_loaded_prefix(&data));
|
||||
self.data = Arc::new(data);
|
||||
}
|
||||
pub(super) fn rebind_after_convergence(&mut self, current: &Self) -> bool {
|
||||
if self.offset < current.offset
|
||||
|| self.data.get(current.offset..) != current.data.get(current.offset..)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.data = current.data.clone();
|
||||
true
|
||||
}
|
||||
pub(super) fn payload_bytes(&self) -> usize {
|
||||
self.data.len()
|
||||
}
|
||||
@@ -367,6 +602,7 @@ impl Mouth {
|
||||
let (resolved, bom) = encoding.resolve(&data);
|
||||
let detected = (*encoding == Encoding::Auto).then(|| (resolved.clone(), bom));
|
||||
(Some(XePhysical {
|
||||
framing_history: Some(resolved.framing()),
|
||||
encoding: resolved,
|
||||
autodetected: detected,
|
||||
skip_lf: false,
|
||||
@@ -569,6 +805,9 @@ impl Mouth {
|
||||
) -> Result<bool, (Span, String)> {
|
||||
let xe = self.xe.as_mut().unwrap();
|
||||
let framing = xe.encoding.framing();
|
||||
if xe.framing_history != Some(framing) {
|
||||
xe.framing_history = None;
|
||||
}
|
||||
let width = framing.unit_width();
|
||||
if std::mem::take(&mut xe.skip_lf)
|
||||
&& framing.code_unit(&self.data[self.offset..]) == Some(10)
|
||||
|
||||
@@ -332,12 +332,12 @@ impl RevisionJob {
|
||||
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
|
||||
// Host observations can themselves supersede the revision. Do not
|
||||
// invoke the host while holding the session publication lock.
|
||||
let resources = files.execution_resource_trace().cloned();
|
||||
let mut resources = files.execution_resource_trace().cloned();
|
||||
let result = executed.map(|execution| {
|
||||
Arc::new(RevisionExecution::with_previous_sources(
|
||||
self.revision,
|
||||
execution,
|
||||
resources.clone(),
|
||||
resources.take(),
|
||||
previous,
|
||||
))
|
||||
});
|
||||
@@ -359,13 +359,17 @@ impl RevisionJob {
|
||||
completed_execution: None,
|
||||
resources,
|
||||
}),
|
||||
Ok(result) if cancelled => Err(RevisionFailure {
|
||||
revision: self.revision,
|
||||
error: RevisionError::Cancelled,
|
||||
failed_execution: None,
|
||||
completed_execution: Some(result),
|
||||
resources,
|
||||
}),
|
||||
Ok(result) if cancelled => {
|
||||
drop(state);
|
||||
let resources = result.execution_resources.clone();
|
||||
Err(RevisionFailure {
|
||||
revision: self.revision,
|
||||
error: RevisionError::Cancelled,
|
||||
failed_execution: None,
|
||||
completed_execution: Some(result),
|
||||
resources,
|
||||
})
|
||||
}
|
||||
Ok(result) => {
|
||||
state.latest = Some(Arc::clone(&result));
|
||||
Ok(result)
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
use super::{Span, XeLineFraming};
|
||||
|
||||
/// Coordinates preserved across a length-changing edit within a physical line
|
||||
/// or an insertion or deletion of complete physical lines.
|
||||
pub(super) struct SourceRelocation {
|
||||
source: usize,
|
||||
unchanged_prefix: usize,
|
||||
old_suffix: usize,
|
||||
current_suffix: usize,
|
||||
old_len: usize,
|
||||
first_unchanged_line: usize,
|
||||
physical_framing: (XeLineFraming, usize),
|
||||
line_edit: Option<PhysicalLineEdit>,
|
||||
}
|
||||
|
||||
struct PhysicalLineEdit {
|
||||
prefix_lines: usize,
|
||||
removed: usize,
|
||||
inserted: usize,
|
||||
}
|
||||
|
||||
impl SourceRelocation {
|
||||
pub(super) fn new(source: usize, old: &[u8], current: &[u8]) -> Option<Self> {
|
||||
Self::with_framing(source, old, current, XeLineFraming::Bytes, 0)
|
||||
}
|
||||
|
||||
pub(super) fn with_framing(
|
||||
source: usize,
|
||||
old: &[u8],
|
||||
current: &[u8],
|
||||
framing: XeLineFraming,
|
||||
bom: usize,
|
||||
) -> Option<Self> {
|
||||
if framing == XeLineFraming::Auto
|
||||
|| old.len() == current.len()
|
||||
|| old.get(..bom)? != current.get(..bom)?
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let old = &old[bom..];
|
||||
let current = ¤t[bom..];
|
||||
let width = framing.unit_width();
|
||||
if old.len() % width != 0 || current.len() % width != 0 {
|
||||
return None;
|
||||
}
|
||||
// Align byte matches down to complete units. The matching bytes
|
||||
// within a changed unit do not prove a usable framing boundary.
|
||||
let common_prefix = old.iter().zip(current).take_while(|(a, b)| a == b).count();
|
||||
let unchanged_prefix = common_prefix - common_prefix % width;
|
||||
let common_suffix = old[unchanged_prefix..]
|
||||
.iter()
|
||||
.rev()
|
||||
.zip(current[unchanged_prefix..].iter().rev())
|
||||
.take_while(|(a, b)| a == b)
|
||||
.count();
|
||||
let unchanged_suffix = common_suffix - common_suffix % width;
|
||||
let old_suffix = old.len() - unchanged_suffix;
|
||||
let current_suffix = current.len() - unchanged_suffix;
|
||||
if framing
|
||||
.line_boundary(&old[unchanged_prefix..old_suffix])
|
||||
.1
|
||||
.is_some()
|
||||
|| framing
|
||||
.line_boundary(¤t[unchanged_prefix..current_suffix])
|
||||
.1
|
||||
.is_some()
|
||||
{
|
||||
return Self::whole_line_edit(source, old, current, unchanged_prefix, framing, bom);
|
||||
}
|
||||
// Reject insertion between CR and LF or deletion that joins them.
|
||||
if unchanged_prefix > 0
|
||||
&& framing.code_unit(&old[unchanged_prefix - width..]) == Some(13)
|
||||
&& framing.code_unit(&old[old_suffix..]) == Some(10)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (length, terminator) = framing.line_boundary(&old[old_suffix..]);
|
||||
let terminator = terminator?;
|
||||
let mut end = old_suffix + length + width;
|
||||
if terminator == 13 && framing.code_unit(&old[end..]) == Some(10) {
|
||||
end += width;
|
||||
}
|
||||
Some(Self {
|
||||
source,
|
||||
unchanged_prefix: bom + unchanged_prefix,
|
||||
old_suffix: bom + old_suffix,
|
||||
current_suffix: bom + current_suffix,
|
||||
old_len: bom + old.len(),
|
||||
first_unchanged_line: bom + end,
|
||||
physical_framing: (framing, bom),
|
||||
line_edit: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn whole_line_edit(
|
||||
source: usize,
|
||||
old: &[u8],
|
||||
current: &[u8],
|
||||
common_prefix: usize,
|
||||
framing: XeLineFraming,
|
||||
bom: usize,
|
||||
) -> Option<Self> {
|
||||
let inserting = current.len() > old.len();
|
||||
let (shorter, longer) = if inserting {
|
||||
(old, current)
|
||||
} else {
|
||||
(current, old)
|
||||
};
|
||||
let changed_bytes = longer.len() - shorter.len();
|
||||
let width = framing.unit_width();
|
||||
// Unlike the single-line check, allow the common prefix and suffix
|
||||
// to overlap. Repeated bytes can admit more than one line-aligned
|
||||
// decomposition, so accept only a unique seam.
|
||||
let common_suffix = shorter
|
||||
.iter()
|
||||
.rev()
|
||||
.zip(longer.iter().rev())
|
||||
.take_while(|(a, b)| a == b)
|
||||
.count();
|
||||
let suffix_start = shorter.len() - (common_suffix - common_suffix % width);
|
||||
let mut seams = (suffix_start..=common_prefix)
|
||||
.step_by(width)
|
||||
.filter(|&start| {
|
||||
starts_physical_line(shorter, start, framing)
|
||||
&& starts_physical_line(longer, start, framing)
|
||||
&& starts_physical_line(longer, start + changed_bytes, framing)
|
||||
});
|
||||
let start = seams.next()?;
|
||||
if start == shorter.len() || seams.next().is_some() {
|
||||
return None;
|
||||
}
|
||||
let end = start + changed_bytes;
|
||||
let count = physical_break_count(&longer[start..end], framing);
|
||||
if count == 0 {
|
||||
return None;
|
||||
}
|
||||
let (old_suffix, current_suffix, removed, inserted) = if inserting {
|
||||
(start, end, 0, count)
|
||||
} else {
|
||||
(end, start, count, 0)
|
||||
};
|
||||
Some(Self {
|
||||
source,
|
||||
unchanged_prefix: bom + start,
|
||||
old_suffix: bom + old_suffix,
|
||||
current_suffix: bom + current_suffix,
|
||||
old_len: bom + old.len(),
|
||||
first_unchanged_line: bom + old_suffix,
|
||||
physical_framing: (framing, bom),
|
||||
line_edit: Some(PhysicalLineEdit {
|
||||
prefix_lines: physical_break_count(&shorter[..start], framing),
|
||||
removed,
|
||||
inserted,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn physical_framing(&self) -> (XeLineFraming, usize) {
|
||||
self.physical_framing
|
||||
}
|
||||
|
||||
pub(super) fn source(&self) -> usize {
|
||||
self.source
|
||||
}
|
||||
|
||||
pub(super) fn changes_line_numbers(&self) -> bool {
|
||||
self.line_edit.is_some()
|
||||
}
|
||||
|
||||
/// Byte-aligned diagnostic locations keep their physical line numbers
|
||||
/// when the same CR and LF bytes occupy the same positions.
|
||||
pub(super) fn same_line_breaks(old: &[u8], current: &[u8]) -> bool {
|
||||
old.len() == current.len()
|
||||
&& old.iter().zip(current).all(|(&old, ¤t)| {
|
||||
old == current || !(is_line_break(old) || is_line_break(current))
|
||||
})
|
||||
}
|
||||
|
||||
/// Map a line of this input with static physical framing. Physical lines
|
||||
/// start at one, and zero and any virtual EOF positions remain meaningful.
|
||||
pub(super) fn relocate_line(&self, line: usize) -> Option<usize> {
|
||||
let Some(edit) = &self.line_edit else {
|
||||
return Some(line);
|
||||
};
|
||||
if line <= edit.prefix_lines {
|
||||
return Some(line);
|
||||
}
|
||||
let surviving_line = line.checked_sub(edit.removed)?;
|
||||
(surviving_line > edit.prefix_lines)
|
||||
.then_some(surviving_line)?
|
||||
.checked_add(edit.inserted)
|
||||
}
|
||||
|
||||
pub(super) fn relocate_position(
|
||||
&self,
|
||||
position: Option<(usize, usize)>,
|
||||
) -> Option<Option<(usize, usize)>> {
|
||||
match position {
|
||||
Some((source, line)) if source == self.source => {
|
||||
Some(Some((source, self.relocate_line(line)?)))
|
||||
}
|
||||
_ => Some(position),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn relocate_offset(&self, old_offset: usize) -> Option<usize> {
|
||||
let one_side_is_empty = self.unchanged_prefix == self.old_suffix
|
||||
|| self.unchanged_prefix == self.current_suffix;
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
/// A coordinate in the loaded raw line after its start and full suffix
|
||||
/// have been checked. Unlike a general point, its side of the seam is known.
|
||||
pub(super) fn relocate_loaded_offset(&self, old_offset: usize) -> Option<usize> {
|
||||
if old_offset < self.first_unchanged_line {
|
||||
return None;
|
||||
}
|
||||
self.relocate_suffix_offset(old_offset)
|
||||
}
|
||||
|
||||
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')
|
||||
}
|
||||
|
||||
fn starts_physical_line(bytes: &[u8], offset: usize, framing: XeLineFraming) -> bool {
|
||||
if offset == 0 {
|
||||
return true;
|
||||
}
|
||||
match framing.code_unit(&bytes[offset - framing.unit_width()..offset]) {
|
||||
Some(10) => true,
|
||||
Some(13) => framing.code_unit(&bytes[offset..]) != Some(10),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn physical_break_count(bytes: &[u8], framing: XeLineFraming) -> usize {
|
||||
let mut previous = None;
|
||||
let mut count = 0;
|
||||
for unit in bytes.chunks_exact(framing.unit_width()) {
|
||||
let code = framing.code_unit(unit);
|
||||
if code == Some(13) || (code == Some(10) && previous != Some(13)) {
|
||||
count += 1;
|
||||
}
|
||||
previous = code;
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
#[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_offset(2), None);
|
||||
assert_eq!(map.relocate_loaded_offset(6), Some(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocation_maps_complete_physical_lines_in_both_directions() {
|
||||
for delimiter in ["\n", "\r\n", "\r"] {
|
||||
let prefix = format!("cover{delimiter}");
|
||||
let inserted = format!("% note{delimiter}% second{delimiter}");
|
||||
let suffix = format!("unchanged{delimiter}ending{delimiter}");
|
||||
let shorter = format!("{prefix}{suffix}");
|
||||
let longer = format!("{prefix}{inserted}{suffix}");
|
||||
let insert = SourceRelocation::new(4, shorter.as_bytes(), longer.as_bytes()).unwrap();
|
||||
let delete = SourceRelocation::new(4, longer.as_bytes(), shorter.as_bytes()).unwrap();
|
||||
let point = prefix.len();
|
||||
assert!(insert.changes_line_numbers() && delete.changes_line_numbers());
|
||||
assert_eq!(insert.relocate_offset(point), None);
|
||||
assert_eq!(
|
||||
insert.relocate_loaded_offset(point),
|
||||
Some(point + inserted.len())
|
||||
);
|
||||
assert_eq!(insert.relocate_line(0), Some(0));
|
||||
assert_eq!(insert.relocate_line(1), Some(1));
|
||||
assert_eq!(insert.relocate_line(2), Some(4));
|
||||
assert_eq!(insert.relocate_line(4), Some(6)); // Virtual EOF line.
|
||||
assert_eq!(delete.relocate_position(Some((4, 2))), None);
|
||||
assert_eq!(delete.relocate_position(Some((4, 3))), None);
|
||||
assert_eq!(delete.relocate_position(Some((4, 4))), Some(Some((4, 2))));
|
||||
assert_eq!(delete.relocate_position(Some((7, 3))), Some(Some((7, 3))));
|
||||
assert_eq!(delete.relocate_position(None), Some(None));
|
||||
}
|
||||
}
|
||||
|
||||
fn utf16(text: &str, framing: XeLineFraming) -> Vec<u8> {
|
||||
let encode: fn(u16) -> [u8; 2] = match framing {
|
||||
XeLineFraming::Utf16Le => u16::to_le_bytes,
|
||||
XeLineFraming::Utf16Be => u16::to_be_bytes,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
std::iter::once(0xfeff)
|
||||
.chain(text.encode_utf16())
|
||||
.flat_map(encode)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_relocation_ignores_separator_bytes_inside_other_units() {
|
||||
for framing in [XeLineFraming::Utf16Le, XeLineFraming::Utf16Be] {
|
||||
let old = utf16("aΩb\r\nnext\r\n", framing);
|
||||
let current = utf16("aΩ\u{050a}\u{0d41}b\r\nnext\r\n", framing);
|
||||
let map = SourceRelocation::with_framing(4, &old, ¤t, framing, 2).unwrap();
|
||||
let next = utf16("aΩb\r\n", framing).len();
|
||||
assert_eq!(map.physical_framing(), (framing, 2));
|
||||
assert!(!map.changes_line_numbers());
|
||||
assert_eq!(map.relocate_line(2), Some(2));
|
||||
assert_eq!(map.relocate_loaded_offset(next - 2), None);
|
||||
assert_eq!(map.relocate_loaded_offset(next), Some(next + 4));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_relocation_maps_unique_crlf_seams_from_the_bom() {
|
||||
for framing in [XeLineFraming::Utf16Le, XeLineFraming::Utf16Be] {
|
||||
let old = utf16("first\u{050a}\r\nsecond\r\n", framing);
|
||||
let current = utf16("first\u{050a}\r\nthird\u{0d41}\r\nsecond\r\n", framing);
|
||||
let seam = utf16("first\u{050a}\r\n", framing).len();
|
||||
let insert = SourceRelocation::with_framing(4, &old, ¤t, framing, 2).unwrap();
|
||||
let delete = SourceRelocation::with_framing(4, ¤t, &old, framing, 2).unwrap();
|
||||
assert_eq!(insert.relocate_offset(seam), None);
|
||||
assert_eq!(
|
||||
insert.relocate_loaded_offset(seam),
|
||||
Some(seam + current.len() - old.len())
|
||||
);
|
||||
assert_eq!(insert.relocate_line(1), Some(1));
|
||||
assert_eq!(insert.relocate_line(2), Some(3));
|
||||
assert_eq!(delete.relocate_line(2), None);
|
||||
assert_eq!(delete.relocate_line(3), Some(2));
|
||||
|
||||
let leading = utf16("new\r\nfirst\u{050a}\r\nsecond\r\n", framing);
|
||||
let map = SourceRelocation::with_framing(4, &old, &leading, framing, 2).unwrap();
|
||||
assert_eq!(
|
||||
map.relocate_loaded_offset(2),
|
||||
Some(2 + leading.len() - old.len())
|
||||
);
|
||||
assert_eq!(map.relocate_line(1), Some(2));
|
||||
|
||||
let split = utf16("first\u{050a}\rX\nsecond\r\n", framing);
|
||||
assert!(SourceRelocation::with_framing(4, &old, &split, framing, 2).is_none());
|
||||
assert!(SourceRelocation::with_framing(4, &split, &old, framing, 2).is_none());
|
||||
assert!(
|
||||
SourceRelocation::with_framing(4, &old, ¤t[..current.len() - 1], framing, 2)
|
||||
.is_none()
|
||||
);
|
||||
let mut changed_bom = current;
|
||||
changed_bom[0] = 0;
|
||||
assert!(SourceRelocation::with_framing(4, &old, &changed_bom, framing, 2).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocation_rejects_ambiguous_whole_line_seams() {
|
||||
let shorter = b"cover\nrepeat\nending\n";
|
||||
let longer = b"cover\nrepeat\nrepeat\nending\n";
|
||||
assert!(SourceRelocation::new(4, shorter, longer).is_none());
|
||||
assert!(SourceRelocation::new(4, longer, shorter).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
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,731 @@
|
||||
//! 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, hash_map::Entry},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
type Shared<T> = HashMap<*const T, Arc<T>>;
|
||||
|
||||
pub(super) struct EventRelocation<'a> {
|
||||
map: &'a SourceRelocation,
|
||||
changed: bool,
|
||||
macros: Shared<Macro>,
|
||||
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,
|
||||
changed: false,
|
||||
macros: HashMap::new(),
|
||||
text_lists: HashMap::new(),
|
||||
vertical_lists: HashMap::new(),
|
||||
diagnostic_lists: HashMap::new(),
|
||||
token_lists: HashMap::new(),
|
||||
opentype_runs: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn map(&self) -> &'a SourceRelocation {
|
||||
self.map
|
||||
}
|
||||
|
||||
pub(super) fn relocate_event(&mut self, event: &Event) -> Option<Event> {
|
||||
self.relocated(event)
|
||||
}
|
||||
|
||||
pub(super) fn relocate_box(&mut self, packed: &mut NativeBox) -> Option<()> {
|
||||
packed.relocate(self)
|
||||
}
|
||||
|
||||
pub(super) fn relocate_vertical(&mut self, nodes: &mut [NativeVerticalNode]) -> Option<()> {
|
||||
nodes.relocate(self)
|
||||
}
|
||||
|
||||
pub(super) fn relocate_token(&mut self, token: &mut Token) -> Option<()> {
|
||||
token.relocate(self)
|
||||
}
|
||||
|
||||
pub(super) fn relocate_macro(&mut self, body: &Arc<Macro>) -> Option<Arc<Macro>> {
|
||||
match self.macros.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 previous = TokenOrigin::from(token);
|
||||
let mut next = previous;
|
||||
relocate_origin(&mut next, self.map)?;
|
||||
if next != previous {
|
||||
let replacement = &mut mapped
|
||||
.get_or_insert_with(|| body.as_ref().clone())
|
||||
.replacement[index];
|
||||
let Replacement::Token(token) = replacement else {
|
||||
unreachable!("cloned macro replacement retains its token kind");
|
||||
};
|
||||
token.span = next.span;
|
||||
token.invocation = next.invocation;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mapped = mapped.map_or_else(|| body.clone(), Arc::new);
|
||||
Some(entry.insert(mapped).clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// Track actual coordinate changes only within one shared value. A
|
||||
// nested cache hit contributes its change to the containing value.
|
||||
fn relocate_tracking_changes(&mut self, value: &mut (impl Relocate + ?Sized)) -> Option<bool> {
|
||||
let outer_change = std::mem::take(&mut self.changed);
|
||||
let result = value.relocate(self);
|
||||
let changed = self.changed;
|
||||
self.changed |= outer_change;
|
||||
result.map(|()| changed)
|
||||
}
|
||||
}
|
||||
|
||||
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<()> {
|
||||
let updated = context.map.relocate_span(*self)?;
|
||||
context.changed |= *self != updated;
|
||||
*self = updated;
|
||||
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) {
|
||||
context.changed |= !Arc::ptr_eq(self, updated);
|
||||
*self = updated.clone();
|
||||
} else {
|
||||
let mut updated = $copy(self.as_ref());
|
||||
if context.relocate_tracking_changes(&mut updated)? {
|
||||
*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; });
|
||||
|
||||
fn relocate_origin(origin: &mut TokenOrigin, map: &SourceRelocation) -> Option<()> {
|
||||
let TokenOrigin { span, invocation } = origin;
|
||||
*span = map.relocate_span(*span)?;
|
||||
if let Some(invocation) = invocation {
|
||||
*invocation = map.relocate_span(*invocation)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
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::ConditionalTrace { origin, .. } | Self::GroupTrace { origin, .. } => {
|
||||
*origin = context.map.relocate_position(*origin)?;
|
||||
Some(())
|
||||
}
|
||||
Self::PdfImageObject(_)
|
||||
| Self::ShipoutTrace { .. }
|
||||
| Self::AssignmentTrace { .. }
|
||||
| Self::RestoreTrace { .. }
|
||||
| Self::CommandTrace { .. }
|
||||
| Self::MacroTrace { .. }
|
||||
| Self::PseudoInput { .. } => 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));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_cached_relocation_tracks_changes_per_list() {
|
||||
let map = SourceRelocation::new(2, b"a\nsecond\n", b"ab\nsecond\n").unwrap();
|
||||
let location = Span { source: 2, start: 2, end: 8 };
|
||||
let kind = TokenKind::Character('x', CatCode::Letter);
|
||||
let changed: Arc<[Token]> = Arc::from([Token::new(kind.clone(), location)]);
|
||||
let unchanged: Arc<[Token]> =
|
||||
Arc::from([Token::new(kind, Span { source: 1, ..location })]);
|
||||
let stable_span = Span { source: 1, ..location };
|
||||
let mark = |tokens| TextNode::Mark(NativeMark { class: 0, tokens, span: stable_span });
|
||||
let old_changed = Arc::new(vec![mark(changed.clone())]);
|
||||
let old_unchanged = Arc::new(vec![mark(unchanged)]);
|
||||
let mut relocation = EventRelocation::new(&map);
|
||||
|
||||
// Prime the child cache before mapping its parent. The parent span
|
||||
// is stable and only an Arc returned by the cache has moved.
|
||||
let mapped_child = relocation.relocate_tokens(&changed).unwrap();
|
||||
let mapped_parent = relocation.relocated(&old_changed).unwrap();
|
||||
let TextNode::Mark(mapped_mark) = &mapped_parent[0] else {
|
||||
unreachable!();
|
||||
};
|
||||
assert!(!Arc::ptr_eq(&mapped_parent, &old_changed));
|
||||
assert!(Arc::ptr_eq(&mapped_mark.tokens, &mapped_child));
|
||||
assert_eq!(mapped_mark.tokens[0].span.start, location.start + 1);
|
||||
assert!(Arc::ptr_eq(
|
||||
&relocation.relocated(&old_changed).unwrap(),
|
||||
&mapped_parent,
|
||||
));
|
||||
assert!(Arc::ptr_eq(
|
||||
&relocation.relocated(&old_unchanged).unwrap(),
|
||||
&old_unchanged,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
pub(super) mod source_relocation;
|
||||
|
||||
use hashbrown::HashMap;
|
||||
use std::collections::BTreeMap;
|
||||
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
|
||||
@@ -799,6 +801,7 @@ enum PdftexRevision {
|
||||
|
||||
const COMMAND_SHARDS: usize = 32;
|
||||
type CommandShard = HashMap<Arc<CommandName>, Meaning, RandomState>;
|
||||
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
|
||||
|
||||
pub(super) fn command_hasher() -> &'static RandomState {
|
||||
// Identical hashes feed the binding table and the executor's read cache.
|
||||
@@ -811,6 +814,8 @@ pub(super) fn command_hasher() -> &'static RandomState {
|
||||
struct CommandBindings {
|
||||
shards: [Arc<CommandShard>; COMMAND_SHARDS],
|
||||
revisions: [u64; COMMAND_SHARDS],
|
||||
// Cache names only so redefinitions can share the same order.
|
||||
ordered_names: OrderedCommandNames,
|
||||
}
|
||||
|
||||
impl Default for CommandBindings {
|
||||
@@ -819,6 +824,7 @@ impl Default for CommandBindings {
|
||||
Self {
|
||||
shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hasher.clone()))),
|
||||
revisions: [0; COMMAND_SHARDS],
|
||||
ordered_names: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -855,15 +861,32 @@ impl CommandBindings {
|
||||
}
|
||||
|
||||
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) {
|
||||
self.shard_mut(&name).insert(name, meaning);
|
||||
if self.shard_mut(&name).insert(name, meaning).is_none() {
|
||||
self.invalidate_order();
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) {
|
||||
self.shard_mut(&name).entry(name.into()).or_insert(meaning);
|
||||
if let hashbrown::hash_map::Entry::Vacant(entry) =
|
||||
self.shard_mut(&name).entry(name.into())
|
||||
{
|
||||
entry.insert(meaning);
|
||||
self.invalidate_order();
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, name: &CommandName) {
|
||||
self.shard_mut(name).remove(name);
|
||||
if self.shard_mut(name).remove(name).is_some() {
|
||||
self.invalidate_order();
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_order(&mut self) {
|
||||
if let Some(order) = Arc::get_mut(&mut self.ordered_names) {
|
||||
order.take();
|
||||
} else {
|
||||
self.ordered_names = Arc::default();
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
@@ -874,23 +897,37 @@ impl CommandBindings {
|
||||
self.shards.iter().flat_map(|shard| shard.iter())
|
||||
}
|
||||
|
||||
fn ordered(&self) -> Vec<(&Arc<CommandName>, &Meaning)> {
|
||||
let mut entries = Vec::with_capacity(self.len());
|
||||
entries.extend(self.iter());
|
||||
entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
|
||||
entries
|
||||
fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &Meaning)> {
|
||||
self.ordered_names
|
||||
.get_or_init(|| {
|
||||
let hasher = command_hasher();
|
||||
let mut names = Vec::with_capacity(self.len());
|
||||
names.extend(
|
||||
self.iter()
|
||||
.map(|(name, _)| (name.clone(), hasher.hash_one(name))),
|
||||
);
|
||||
names.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
|
||||
names
|
||||
})
|
||||
.iter()
|
||||
.map(|(name, hash)| {
|
||||
let meaning = self
|
||||
.get_hashed(name, *hash)
|
||||
.expect("ordered command names match the binding table");
|
||||
(name, meaning)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for CommandBindings {
|
||||
fn hash<H: Hasher>(&self, hasher: &mut H) {
|
||||
self.ordered().hash(hasher);
|
||||
self.ordered().collect::<Vec<_>>().hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
impl serde::Serialize for CommandBindings {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serde::Serialize::serialize(&self.ordered(), serializer)
|
||||
serializer.collect_seq(self.ordered())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1064,6 +1101,7 @@ fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
|
||||
let mut state = State::initex().with_etex();
|
||||
let name = CommandName::Control("checkpointbinding".into());
|
||||
state.define(name.clone(), Meaning::Count(3), true);
|
||||
let fingerprint = state.fingerprint();
|
||||
let snapshot = state.clone();
|
||||
state.define(name.clone(), Meaning::Count(7), true);
|
||||
assert_eq!(snapshot.meaning(&name), Meaning::Count(3));
|
||||
@@ -1071,10 +1109,45 @@ fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
|
||||
let shared = state.commands.shards.iter().zip(&snapshot.commands.shards)
|
||||
.filter(|(current, saved)| Arc::ptr_eq(current, saved)).count();
|
||||
assert_eq!(shared, COMMAND_SHARDS - 1);
|
||||
assert!(Arc::ptr_eq(
|
||||
&state.commands.ordered_names,
|
||||
&snapshot.commands.ordered_names,
|
||||
));
|
||||
let (_, redefined) = state
|
||||
.commands
|
||||
.ordered()
|
||||
.find(|(key, _)| key.as_ref() == &name)
|
||||
.unwrap();
|
||||
assert_eq!(*redefined, Meaning::Count(7));
|
||||
|
||||
let added = CommandName::Control("checkpointorderadded".into());
|
||||
let bindings = state.command_bindings_mut();
|
||||
let before_insertion = bindings.clone();
|
||||
bindings.insert_if_absent(name.clone(), Meaning::Count(100));
|
||||
assert!(Arc::ptr_eq(
|
||||
&bindings.ordered_names,
|
||||
&before_insertion.ordered_names,
|
||||
));
|
||||
bindings.insert_if_absent(added.clone(), Meaning::Count(9));
|
||||
assert!(!Arc::ptr_eq(
|
||||
&bindings.ordered_names,
|
||||
&before_insertion.ordered_names,
|
||||
));
|
||||
let ordered: BTreeMap<_, _> = bindings.iter().collect();
|
||||
let expected: Vec<_> = ordered.into_iter().collect();
|
||||
assert!(bindings.ordered().eq(expected.iter().copied()));
|
||||
assert_eq!(
|
||||
serde_json::to_vec(bindings).unwrap(),
|
||||
serde_json::to_vec(&expected).unwrap(),
|
||||
);
|
||||
let with_added = bindings.clone();
|
||||
bindings.remove(&added);
|
||||
assert!(bindings.ordered().eq(before_insertion.ordered()));
|
||||
assert!(with_added.ordered().any(|(key, _)| key.as_ref() == &added));
|
||||
|
||||
state.define(name, Meaning::Count(3), true);
|
||||
assert_eq!(state, snapshot);
|
||||
assert_eq!(state.fingerprint(), snapshot.fingerprint());
|
||||
assert_eq!(state.fingerprint(), fingerprint);
|
||||
assert_eq!(serde_json::to_vec(&state).unwrap(), serde_json::to_vec(&snapshot).unwrap());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
use super::*;
|
||||
use crate::execution::source_relocation_events::EventRelocation;
|
||||
use crate::pdf_device::forms::FormContents;
|
||||
|
||||
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(
|
||||
&mut self,
|
||||
relocation: &mut EventRelocation<'_>,
|
||||
) -> Option<()> {
|
||||
let commands = self.commands.clone();
|
||||
// Copy only shards with a relocated macro. Ordinary format macros
|
||||
// and macros from the byte-identical prefix keep their allocations.
|
||||
for (index, shard) in commands.shards.iter().enumerate() {
|
||||
for (name, meaning) in shard.iter() {
|
||||
if let Meaning::Macro(body) = meaning {
|
||||
let relocated = relocation.relocate_macro(body)?;
|
||||
if !Arc::ptr_eq(body, &relocated) {
|
||||
let shard = &mut Arc::make_mut(&mut self.commands).shards[index];
|
||||
Arc::make_mut(shard).insert(name.clone(), Meaning::Macro(relocated));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for tokens in self.toks.values_mut() {
|
||||
relocate_tokens(tokens, relocation)?;
|
||||
}
|
||||
for tokens in self
|
||||
.token_parameters
|
||||
.values_mut()
|
||||
.chain(self.xe_inter_char_tokens.values_mut())
|
||||
{
|
||||
*tokens = relocation.relocate_tokens(tokens)?;
|
||||
}
|
||||
for value in self.boxes.values_mut() {
|
||||
relocation.relocate_box(value)?;
|
||||
}
|
||||
for marks in self.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 self.split_marks.values_mut() {
|
||||
marks.first = relocation.relocate_tokens(&marks.first)?;
|
||||
marks.bottom = relocation.relocate_tokens(&marks.bottom)?;
|
||||
}
|
||||
for form in self.pdf_forms.values_mut() {
|
||||
if let FormContents::Pending(body) = &mut form.contents {
|
||||
let mut mapped = body.as_ref().clone();
|
||||
relocation.relocate_box(&mut 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 self.groups {
|
||||
group.origin = relocation.map().relocate_position(group.origin)?;
|
||||
relocate_tokens(&mut group.after, relocation)?;
|
||||
for saved in group.saved.values_mut() {
|
||||
match saved {
|
||||
Saved::Command(Some(Meaning::Macro(body))) => {
|
||||
*body = relocation.relocate_macro(body)?;
|
||||
}
|
||||
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)) => 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(())
|
||||
}
|
||||
}
|
||||
|
||||
fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> {
|
||||
for token in tokens {
|
||||
relocation.relocate_token(token)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Measured native storage and execution resources, not invented TeX arena words.
|
||||
use super::*;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
collections::{BTreeMap, BTreeSet, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
@@ -81,6 +81,11 @@ pub struct HostResourceUsage {
|
||||
pub open_outputs: Option<usize>,
|
||||
}
|
||||
impl HostResourceUsage {
|
||||
pub fn rebind_entry_bytes(&mut self, previous: u64, current: u64) -> Option<()> {
|
||||
self.resource_bytes_read = self.resource_bytes_read.checked_sub(previous)?.checked_add(current)?;
|
||||
Some(())
|
||||
}
|
||||
|
||||
pub fn from_trace(trace: &crate::resources::ResourceTrace) -> Self {
|
||||
Self {
|
||||
lookups: trace.lookups.len(),
|
||||
@@ -145,6 +150,218 @@ pub struct StatisticsReport {
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
/// Maps monotone step counts after one command boundary onto another.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct StepOffset {
|
||||
previous: usize,
|
||||
current: usize,
|
||||
}
|
||||
|
||||
impl StepOffset {
|
||||
pub fn new(previous: usize, current: usize) -> Self {
|
||||
Self { previous, current }
|
||||
}
|
||||
|
||||
pub fn is_identity(self) -> bool {
|
||||
self.previous == self.current
|
||||
}
|
||||
|
||||
pub fn apply(self, steps: usize) -> Option<usize> {
|
||||
self.current.checked_add(steps.checked_sub(self.previous)?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate the cumulative, saturating count of box node visits.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct BoxNodeOffset {
|
||||
previous: usize,
|
||||
current: usize,
|
||||
}
|
||||
|
||||
impl BoxNodeOffset {
|
||||
pub(super) fn new(previous: usize, current: usize) -> Self {
|
||||
Self { previous, current }
|
||||
}
|
||||
|
||||
pub(super) fn is_identity(self) -> bool {
|
||||
self.previous == self.current
|
||||
}
|
||||
|
||||
pub(super) fn apply(self, nodes: usize) -> Option<usize> {
|
||||
let suffix_nodes = nodes.checked_sub(self.previous)?;
|
||||
// A saturated donor does not reveal how much work would survive a decrease.
|
||||
if self.current < self.previous && nodes == usize::MAX {
|
||||
return None;
|
||||
}
|
||||
Some(self.current.saturating_add(suffix_nodes))
|
||||
}
|
||||
}
|
||||
|
||||
impl StatisticsReport {
|
||||
pub(super) fn new(phase: StatisticsPhase, destination: WriteDestination, span: Span) -> Self {
|
||||
let text = phase.text();
|
||||
Self { phase, destination, text, span }
|
||||
}
|
||||
|
||||
pub(super) fn resize_entry_payload(
|
||||
&mut self,
|
||||
previous: usize,
|
||||
current: usize,
|
||||
replayed_entry_bytes: Option<u64>,
|
||||
) -> Option<()> {
|
||||
// Closeout reports are produced only after resuming, never captured
|
||||
// in an executable prefix. Shipout text does not print byte totals.
|
||||
let StatisticsPhase::Shipout { before, after } = &mut self.phase else {
|
||||
return None;
|
||||
};
|
||||
for usage in [before, after] {
|
||||
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> {
|
||||
self.with_execution_offsets(offset, BoxNodeOffset::new(0, 0))
|
||||
}
|
||||
|
||||
pub(super) fn with_execution_offsets(
|
||||
&self,
|
||||
steps: StepOffset,
|
||||
boxes: BoxNodeOffset,
|
||||
) -> Option<Self> {
|
||||
let translate = |usage: &mut ResourceUsage| {
|
||||
usage.steps = steps.apply(usage.steps)?;
|
||||
usage.box_nodes_created = boxes.apply(usage.box_nodes_created)?;
|
||||
Some(())
|
||||
};
|
||||
let mut phase = self.phase.clone();
|
||||
match &mut phase {
|
||||
StatisticsPhase::Shipout { before, after } => {
|
||||
translate(before)?;
|
||||
translate(after)?;
|
||||
}
|
||||
StatisticsPhase::End { usage, .. } => translate(usage)?,
|
||||
}
|
||||
let report = Self::new(phase, self.destination, self.span);
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
impl StatisticsPhase {
|
||||
fn text(&self) -> String {
|
||||
match self {
|
||||
Self::Shipout { before, after } => {
|
||||
format!(
|
||||
"Route-D resources at shipout: active records {} -> {}; retained records {} -> {}; token cells {} -> {}; retained pages {}.\n",
|
||||
before.active_material.records(),
|
||||
after.active_material.records(),
|
||||
before.retained_material.records(),
|
||||
after.retained_material.records(),
|
||||
before.macro_token_cells + before.token_list_cells,
|
||||
after.macro_token_cells + after.token_list_cells,
|
||||
after.retained_shipouts
|
||||
)
|
||||
}
|
||||
Self::End { success, usage } => {
|
||||
let mut text = format!(
|
||||
"Route-D resource usage at core execution end ({}):\n {} steps out of {}\n {} source files, {} source payload bytes, {} active mouth payload bytes\n {} command entries, {} control-name bytes\n {} macro bindings, {} unique macro bodies, {} macro token cells\n {} token-list cells, {} saved entries\n {} active material records, {} retained material records, {} retained pages\n {} font instances, {} font parameter cells, {} TFM resources / {} source bytes\n {} hyphenation exceptions\n stack peaks: {} input, {} group, {} box, {} math, {} conditional, {} scanner, {} expansion\n",
|
||||
if *success { "success" } else { "failure" },
|
||||
usage.steps,
|
||||
usage.step_limit,
|
||||
usage.source_files,
|
||||
usage.source_payload_bytes,
|
||||
usage.mouth_payload_bytes,
|
||||
usage.state.command_entries,
|
||||
usage.state.control_name_bytes,
|
||||
usage.state.macro_bindings,
|
||||
usage.unique_macro_bodies,
|
||||
usage.macro_token_cells,
|
||||
usage.token_list_cells,
|
||||
usage.state.save_entries,
|
||||
usage.active_material.records(),
|
||||
usage.retained_material.records(),
|
||||
usage.retained_shipouts,
|
||||
usage.state.font_instances,
|
||||
usage.state.font_parameter_cells,
|
||||
usage.state.tfm_resources,
|
||||
usage.state.tfm_resource_bytes,
|
||||
usage.state.hyphenation_exceptions,
|
||||
usage.stack_peaks.input_frames,
|
||||
usage.stack_peaks.groups,
|
||||
usage.stack_peaks.box_frames,
|
||||
usage.stack_peaks.math_frames,
|
||||
usage.stack_peaks.conditionals,
|
||||
usage.stack_peaks.scanner_depth,
|
||||
usage.stack_peaks.expansion_depth
|
||||
);
|
||||
if let Some(h) = &usage.host {
|
||||
text.push_str(&format!(" host resources: {} reads / {} bytes; {} lookups / {} misses / {} errors; {} stream reads / {} bytes\n",h.resource_reads,h.resource_bytes_read,h.lookups,h.negative_lookups,h.failed_lookups,h.stream_read_calls,h.stream_bytes_read));
|
||||
} else {
|
||||
text.push_str(" host resource telemetry unavailable\n");
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Ownership {
|
||||
Active,
|
||||
@@ -157,7 +374,7 @@ enum Allocation {
|
||||
Material(usize),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[derive(Clone, Default)]
|
||||
struct AliasVisits {
|
||||
ordinals: BTreeMap<Allocation, usize>,
|
||||
visits: Vec<(Allocation, usize)>,
|
||||
@@ -171,10 +388,11 @@ impl AliasVisits {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Collector {
|
||||
pub usage: ResourceUsage,
|
||||
macros: BTreeSet<usize>,
|
||||
// Alias visits keep traversal order separately from this membership index.
|
||||
macros: HashSet<usize>,
|
||||
token_lists: BTreeSet<(usize, usize)>,
|
||||
shared_lists: Option<BTreeSet<usize>>,
|
||||
aliases: Option<AliasVisits>,
|
||||
@@ -437,6 +655,43 @@ impl Collector {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn box_node_offsets_require_an_exact_saturating_count() {
|
||||
let max = usize::MAX;
|
||||
assert_eq!(BoxNodeOffset::new(10, 12).apply(17), Some(19));
|
||||
assert_eq!(BoxNodeOffset::new(12, 10).apply(17), Some(15));
|
||||
assert_eq!(BoxNodeOffset::new(12, 10).apply(11), None);
|
||||
assert_eq!(BoxNodeOffset::new(10, 12).apply(max - 1), Some(max));
|
||||
assert_eq!(BoxNodeOffset::new(10, 12).apply(max), Some(max));
|
||||
assert_eq!(BoxNodeOffset::new(10, 10).apply(max), Some(max));
|
||||
assert_eq!(BoxNodeOffset::new(12, 10).apply(max), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statistics_translate_box_counts_without_changing_the_transcript() {
|
||||
let usage = |box_nodes_created| ResourceUsage {
|
||||
box_nodes_created,
|
||||
token_limit: 4096,
|
||||
..ResourceUsage::default()
|
||||
};
|
||||
let translate = |old, expected| {
|
||||
let report = StatisticsReport::new(old, WriteDestination::Log, Span::default());
|
||||
let updated = report
|
||||
.with_execution_offsets(StepOffset::new(0, 0), BoxNodeOffset::new(2, 7))
|
||||
.unwrap();
|
||||
assert_eq!(updated.phase, expected);
|
||||
assert_eq!(updated.text, report.text);
|
||||
};
|
||||
translate(
|
||||
StatisticsPhase::Shipout { before: usage(5), after: usage(8) },
|
||||
StatisticsPhase::Shipout { before: usage(10), after: usage(13) },
|
||||
);
|
||||
translate(
|
||||
StatisticsPhase::End { success: true, usage: usage(8) },
|
||||
StatisticsPhase::End { success: true, usage: usage(13) },
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_equivalence_keeps_aliases_that_cross_the_boundary() {
|
||||
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! pdfTeX-profile glyph-name mappings. Values retain PDF hex strings, including
|
||||
//! explicitly supplied UTF-16 code units; they are not Rust Unicode labels.
|
||||
use std::collections::BTreeMap;
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
enum Mapping {
|
||||
@@ -10,7 +10,7 @@ enum Mapping {
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GlyphUnicodeMap {
|
||||
entries: BTreeMap<String, Mapping>,
|
||||
entries: Arc<BTreeMap<String, Mapping>>,
|
||||
}
|
||||
|
||||
fn upper_hex(s: &str) -> bool {
|
||||
@@ -69,7 +69,7 @@ impl GlyphUnicodeMap {
|
||||
}
|
||||
}
|
||||
};
|
||||
self.entries.insert(glyph, mapping);
|
||||
Arc::make_mut(&mut self.entries).insert(glyph, mapping);
|
||||
warning
|
||||
}
|
||||
/// Resolve against the actual TFM namespace and encoding glyph name. An
|
||||
@@ -185,10 +185,13 @@ mod tests {
|
||||
] {
|
||||
assert_eq!(map.lookup(font, name).as_deref(), expected, "{font}/{name}");
|
||||
}
|
||||
let snapshot = map.clone();
|
||||
assert!(map.define("A".into(), "03b1").is_some());
|
||||
assert!(Arc::ptr_eq(&map.entries, &snapshot.entries));
|
||||
assert_eq!(map.lookup("g", "A").as_deref(), Some("0041"));
|
||||
assert!(map.define("tfm:f/A".into(), "110000").is_some());
|
||||
assert_eq!(map.lookup("f", "A"), None);
|
||||
assert_eq!(snapshot.lookup("f", "A").as_deref(), Some("D83DDE00"));
|
||||
assert_eq!(map.lookup("g", "A").as_deref(), Some("0041"));
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//! wired up.
|
||||
|
||||
use crate::cmr10::Cmr10Metrics;
|
||||
use crate::execution::{Span, TokenOrigin};
|
||||
use crate::math::{self, MathAtom, MathColumnAlign};
|
||||
use crate::paragraph::ParagraphFont;
|
||||
use crate::{CellAlignment, Float, FloatPlacement, Halign, HorizontalItem, Page, VerticalItem};
|
||||
@@ -355,6 +356,78 @@ impl SvgTransparency {
|
||||
}
|
||||
|
||||
impl DisplayList {
|
||||
/// Reuse a raw shipout layout with a verified map of its source spans.
|
||||
/// The current execution still projects forms and resolves PDF resources.
|
||||
#[doc(hidden)]
|
||||
pub fn relocate_sources(
|
||||
&self,
|
||||
mut relocate_span: impl FnMut(Span) -> Option<Span>,
|
||||
) -> Option<Self> {
|
||||
if !self.forms.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut relocate_origin = |mut origin: TokenOrigin| {
|
||||
origin.span = relocate_span(origin.span)?;
|
||||
if let Some(invocation) = origin.invocation {
|
||||
origin.invocation = Some(relocate_span(invocation)?);
|
||||
}
|
||||
Some(origin)
|
||||
};
|
||||
let mut layout = self.clone();
|
||||
for (old, moved) in self.sources.values().zip(layout.sources.values_mut()) {
|
||||
for (index, origin) in old.tokens.iter().enumerate() {
|
||||
let shifted = relocate_origin(*origin)?;
|
||||
// Keep the lowered origin order and its equality classes. A
|
||||
// newly merged or split origin would change PaintSource::merge.
|
||||
if old.tokens[..index]
|
||||
.iter()
|
||||
.zip(&moved.tokens[..index])
|
||||
.any(|(left, right)| (left == origin) != (*right == shifted))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
moved.tokens[index] = shifted;
|
||||
}
|
||||
}
|
||||
use crate::pdf_device::PdfGraphics;
|
||||
for item in &mut layout.items {
|
||||
match item {
|
||||
DisplayItem::PdfGraphics { operation, .. } => match operation {
|
||||
PdfGraphics::XdvFormUse { source, .. } => *source = relocate_origin(*source)?,
|
||||
PdfGraphics::Save
|
||||
| PdfGraphics::Matrix(_)
|
||||
| PdfGraphics::Restore { .. }
|
||||
| PdfGraphics::Literal { .. }
|
||||
| PdfGraphics::SaveMatrix(_)
|
||||
| PdfGraphics::TextBoundary
|
||||
| PdfGraphics::XdvFormBegin(_)
|
||||
| PdfGraphics::XdvFormEnd(_) => {}
|
||||
},
|
||||
DisplayItem::NativeGlyph { .. }
|
||||
| DisplayItem::OpenTypeGlyph { .. }
|
||||
| DisplayItem::OpenTypeActualText(_)
|
||||
| DisplayItem::OpenTypeColor(_)
|
||||
| DisplayItem::MathGlyph { .. }
|
||||
| DisplayItem::Text { .. }
|
||||
| DisplayItem::Rule { .. }
|
||||
| DisplayItem::Line { .. }
|
||||
| DisplayItem::Image { .. }
|
||||
| DisplayItem::PdfImage { .. }
|
||||
| DisplayItem::PdfImageObject(_)
|
||||
| DisplayItem::PdfForm { .. }
|
||||
| DisplayItem::Rect { .. }
|
||||
| DisplayItem::Frame { .. }
|
||||
| DisplayItem::Link { .. }
|
||||
| DisplayItem::Background(_)
|
||||
| DisplayItem::Fill(_)
|
||||
| DisplayItem::PdfColor { .. }
|
||||
| DisplayItem::PdfTextSpace { .. }
|
||||
| DisplayItem::Special(_) => {}
|
||||
}
|
||||
}
|
||||
Some(layout)
|
||||
}
|
||||
|
||||
/// Whether page or captured form colors depend on a PDF default color space.
|
||||
pub fn has_pdf_default_colors(&self) -> bool {
|
||||
self.pdf_resources.has_default_color_spaces
|
||||
@@ -2507,6 +2580,138 @@ impl Page {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relocates_raw_shipout_origins_without_changing_paint_or_virtual_packets() {
|
||||
use crate::math_engine_tex::{MathItem, PositionedItem};
|
||||
use crate::pdf_device::PdfGraphics;
|
||||
use crate::provenance::{Derivation, PaintSource};
|
||||
use std::sync::Arc;
|
||||
|
||||
let span = |source, start| Span {
|
||||
source,
|
||||
start,
|
||||
end: start + 1,
|
||||
};
|
||||
let glyph_origin = TokenOrigin {
|
||||
span: span(2, 7),
|
||||
invocation: Some(span(3, 12)),
|
||||
};
|
||||
let other_origin = TokenOrigin {
|
||||
span: span(3, 4),
|
||||
invocation: None,
|
||||
};
|
||||
let form_origin = TokenOrigin {
|
||||
span: span(3, 15),
|
||||
invocation: Some(span(2, 5)),
|
||||
};
|
||||
let packet = Arc::new(vec![PositionedItem {
|
||||
x: 2,
|
||||
y: 3,
|
||||
item: MathItem::Rule {
|
||||
width: 4,
|
||||
height: 5,
|
||||
},
|
||||
source: PaintSource::default(),
|
||||
}]);
|
||||
let mut layout = DisplayList {
|
||||
items: vec![
|
||||
DisplayItem::Rule {
|
||||
x: 1,
|
||||
y: 2,
|
||||
width: 3,
|
||||
height: 4,
|
||||
},
|
||||
DisplayItem::PdfGraphics {
|
||||
x: 5,
|
||||
y: 6,
|
||||
operation: PdfGraphics::XdvFormUse {
|
||||
number: 7,
|
||||
options: Default::default(),
|
||||
source: form_origin,
|
||||
available: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
xdv_horizontal_offsets: vec![(1, 8)],
|
||||
prepared_virtual_glyphs: Some([(0, packet.clone())].into()),
|
||||
..Default::default()
|
||||
};
|
||||
layout.sources.insert(
|
||||
0,
|
||||
PaintSource {
|
||||
tokens: vec![glyph_origin, other_origin],
|
||||
derivations: vec![Derivation::FontMapping],
|
||||
},
|
||||
);
|
||||
let relocated = layout
|
||||
.relocate_sources(|value| {
|
||||
Some(if value.source == 3 && value.start >= 10 {
|
||||
span(value.source, value.start + 2)
|
||||
} else {
|
||||
value
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
let mut expected = layout.clone();
|
||||
expected.sources.get_mut(&0).unwrap().tokens[0].invocation = Some(span(3, 14));
|
||||
let DisplayItem::PdfGraphics {
|
||||
operation: PdfGraphics::XdvFormUse { source, .. },
|
||||
..
|
||||
} = &mut expected.items[1]
|
||||
else {
|
||||
unreachable!();
|
||||
};
|
||||
source.span = span(3, 17);
|
||||
assert_eq!(relocated, expected);
|
||||
assert!(Arc::ptr_eq(
|
||||
&relocated.prepared_virtual_glyphs.unwrap()[&0],
|
||||
&packet
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_new_collision_or_unproved_invocation_in_relocated_origins() {
|
||||
use crate::provenance::PaintSource;
|
||||
|
||||
let span = |offset| Span {
|
||||
source: 0,
|
||||
start: offset,
|
||||
end: offset,
|
||||
};
|
||||
let layout = DisplayList {
|
||||
items: vec![DisplayItem::Rule {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 1,
|
||||
height: 1,
|
||||
}],
|
||||
sources: [(
|
||||
0,
|
||||
PaintSource {
|
||||
tokens: vec![
|
||||
TokenOrigin {
|
||||
span: span(5),
|
||||
invocation: Some(span(8)),
|
||||
},
|
||||
TokenOrigin {
|
||||
span: span(6),
|
||||
invocation: Some(span(8)),
|
||||
},
|
||||
],
|
||||
derivations: Vec::new(),
|
||||
},
|
||||
)]
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(layout.relocate_sources(|_| Some(span(3))).is_none());
|
||||
assert!(
|
||||
layout
|
||||
.relocate_sources(|value| { (value != span(8)).then_some(value) })
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tall_delimiters_are_lowered_to_stay_centered() {
|
||||
let atom = crate::math::parse_math(r"\left(\frac{a}{b}\right)");
|
||||
|
||||
@@ -151,6 +151,34 @@ impl ProjectSnapshot {
|
||||
next.seal()
|
||||
}
|
||||
|
||||
/// Extend the immutable external inputs without changing project buffers
|
||||
/// or granting writes outside the original project.
|
||||
pub fn with_external_resources(
|
||||
self: &Arc<Self>,
|
||||
resources: &BTreeMap<PathBuf, Arc<[u8]>>,
|
||||
) -> Result<Arc<Self>, String> {
|
||||
if resources.keys().all(|path| self.files.contains_key(path)) {
|
||||
return Ok(self.clone());
|
||||
}
|
||||
let mut next = self.next_revision(self.version.revision)?;
|
||||
for (path, data) in resources {
|
||||
if next.files.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
if path.starts_with(&self.configuration.cwd) || !self.covered(path) {
|
||||
return Err(format!(
|
||||
"external resource is outside declared roots: {}",
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
next.files
|
||||
.insert(path.clone(), Self::capture(path.clone(), data.clone()));
|
||||
next.directories
|
||||
.extend(path.ancestors().skip(1).map(Path::to_path_buf));
|
||||
}
|
||||
next.seal()
|
||||
}
|
||||
|
||||
fn next_revision(&self, revision: u64) -> Result<Self, String> {
|
||||
self.validate()?;
|
||||
let mut next = self.clone();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Failed observations are retained without publishing or claiming a checkpoint.
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::cell::RefCell;
|
||||
use std::{cell::RefCell, sync::Arc};
|
||||
use texrra_tex_core::{execution::*, resources::ResourceTrace};
|
||||
|
||||
fn source(name: &str, text: &str) -> SourceFile {
|
||||
@@ -52,7 +52,7 @@ fn failed_child_macro_keeps_actual_versions_meanings_events_and_state_boundary()
|
||||
);
|
||||
assert_eq!(host.messages, ["BEFORE"]);
|
||||
let e = &failure.evidence;
|
||||
assert_eq!(e.sources, [main, child]);
|
||||
assert_eq!(e.sources, [Arc::new(main), Arc::new(child)]);
|
||||
for (s, v) in e.sources.iter().zip(&e.source_versions) {
|
||||
assert_eq!(v.sha256, format!("{:x}", Sha256::digest(&s.data)));
|
||||
assert_eq!(v.bytes, s.data.len() as u64);
|
||||
@@ -102,7 +102,7 @@ fn cancellation_preserves_observed_progress_but_prestart_does_not_invent_input()
|
||||
};
|
||||
let failure = run().run_detailed(main.clone(), &mut host).unwrap_err();
|
||||
assert!(failure.error.message.contains("cancelled"));
|
||||
assert_eq!(failure.evidence.sources, [main.clone()]);
|
||||
assert_eq!(failure.evidence.sources, [Arc::new(main.clone())]);
|
||||
assert!(failure.evidence.reads.contains(&Dependency::Source(0)));
|
||||
assert_eq!(host.messages, ["FIRST"]);
|
||||
let before = run().run_detailed(main, &mut host).unwrap_err();
|
||||
@@ -145,6 +145,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() {
|
||||
.start()
|
||||
.run(executor(), source("old.tex", r"\count0=1\end"), &mut host)
|
||||
.unwrap();
|
||||
assert_eq!(previous.execution_resources, Some(host.trace.clone()));
|
||||
host.armed = true;
|
||||
let failure = session
|
||||
.start()
|
||||
@@ -156,6 +157,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() {
|
||||
assert_eq!(completed.execution.state.count(0), 2);
|
||||
assert_eq!(completed.revision, failure.revision);
|
||||
assert_eq!(failure.resources, Some(host.trace.clone()));
|
||||
assert_eq!(completed.execution_resources, failure.resources);
|
||||
assert_eq!(session.latest().unwrap().revision, previous.revision);
|
||||
assert!(host.pending.borrow().as_ref().unwrap().revision() > completed.revision);
|
||||
host.pending.borrow_mut().take();
|
||||
@@ -165,6 +167,7 @@ fn superseding_after_core_completion_retains_result_without_publishing_it() {
|
||||
.unwrap_err();
|
||||
assert!(matches!(interrupted.error, RevisionError::Cancelled));
|
||||
assert!(interrupted.completed_execution.is_none());
|
||||
assert_eq!(interrupted.resources, Some(host.trace.clone()));
|
||||
assert!(
|
||||
interrupted
|
||||
.failed_execution
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Reference material copied from the independent pdfTeX DVI run.
|
||||
//! Leader placement and repeated shipout effects against pdfTeX fixtures.
|
||||
use serde_json::Value;
|
||||
use std::{fs, io::Write, path::PathBuf};
|
||||
use texrra_tex_core::{execution::*, math_engine_tex::MathItem};
|
||||
@@ -176,3 +176,67 @@ fn repeated_device_effects_follow_the_paint_order_and_obey_placement_budget() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_pdf_link_nodes_keep_their_final_rectangle() {
|
||||
let execution = Executor::new(
|
||||
State::initex()
|
||||
.with_etex()
|
||||
.with_input_profile(InputProfile::TeX8Bit),
|
||||
Limits::default(),
|
||||
)
|
||||
.with_native_pages()
|
||||
.run(
|
||||
SourceFile {
|
||||
name: "links.tex".into(),
|
||||
data: include_bytes!("fixtures/leaders/links.tex").to_vec(),
|
||||
},
|
||||
&mut NoFiles,
|
||||
)
|
||||
.unwrap();
|
||||
let pdf = texrra_tex_core::pdf::shipout_lists_to_native_pdf(
|
||||
&execution.shipout_display_lists().unwrap(),
|
||||
execution.state.pdf_final_options(),
|
||||
)
|
||||
.unwrap();
|
||||
let document = lopdf::Document::load_mem(&pdf).unwrap();
|
||||
|
||||
// PDF /Rect arrays from pdfTeX 1.40.29, in thousandths of a PDF point.
|
||||
let expected: Vec<Vec<[i64; 4]>> = serde_json::from_str(include_str!(
|
||||
"fixtures/leaders/reference-link-rectangles.json"
|
||||
))
|
||||
.unwrap();
|
||||
let pages = document.get_pages();
|
||||
assert_eq!(pages.len(), expected.len());
|
||||
let mut objects = std::collections::BTreeSet::new();
|
||||
for ((page, id), expected) in pages.into_iter().zip(expected) {
|
||||
let annotations = document
|
||||
.get_dictionary(id)
|
||||
.unwrap()
|
||||
.get(b"Annots")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap();
|
||||
let actual = annotations
|
||||
.iter()
|
||||
.map(|object| {
|
||||
let id = object.as_reference().unwrap();
|
||||
assert!(objects.insert(id), "duplicate annotation object on page {page}");
|
||||
let rect = document
|
||||
.get_dictionary(id)
|
||||
.unwrap()
|
||||
.get(b"Rect")
|
||||
.unwrap()
|
||||
.as_array()
|
||||
.unwrap();
|
||||
assert_eq!(rect.len(), 4);
|
||||
std::array::from_fn(|i| match rect[i] {
|
||||
lopdf::Object::Integer(value) => value * 1000,
|
||||
lopdf::Object::Real(value) => (value * 1000.0).round() as i64,
|
||||
ref value => panic!("unexpected rectangle coordinate {value:?}"),
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(actual, expected, "page {page}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
\pdfoutput=1\pdfcompresslevel=0\pdfobjcompresslevel=0\pdfpkresolution=600
|
||||
\catcode123=1\catcode125=2\pdflinkmargin=0pt
|
||||
\def\tile{\hbox to2pt{\pdfstartlink width1pt height2pt depth0pt user{/Subtype /Link /A << /S /URI /URI (https://example.invalid/) >>}\vrule width1pt height2pt\pdfendlink\hss}}
|
||||
\setbox5=\tile
|
||||
\shipout\hbox{\cleaders\copy5\hskip6pt}
|
||||
\shipout\hbox{\copy5\kern2pt\copy5}
|
||||
\shipout\hbox{\cleaders\hbox to18pt{\copy5\kern1pt\leaders\copy5\hskip1pt\copy5%
|
||||
\kern1pt\leaders\copy5\hskip4pt\kern1pt\leaders\copy5\hskip4pt\hss}\hskip37pt}
|
||||
\def\runtile{\hbox to2pt{\pdfstartlink height2pt depth0pt user{/Subtype /Link /A << /S /URI /URI (https://example.invalid/) >>}\vrule width1pt height2pt\pdfendlink\hss}}
|
||||
\shipout\vbox{\cleaders\vbox{\hbox{\cleaders\runtile\hskip6pt}}\vskip4pt}
|
||||
\end
|
||||
@@ -0,0 +1,31 @@
|
||||
[
|
||||
[
|
||||
[75985, -73993, 149978, 73993],
|
||||
[75985, -73993, 149978, 73993],
|
||||
[75985, -73993, 149978, 73993]
|
||||
],
|
||||
[
|
||||
[72000, 72000, 72996, 73993],
|
||||
[75985, 72000, 76981, 73993]
|
||||
],
|
||||
[
|
||||
[90431, -1494, 162929, 144000],
|
||||
[94416, -5480, 170899, 144000],
|
||||
[98401, -9465, 178869, 144000],
|
||||
[104379, -116832, 206765, 144000],
|
||||
[104379, -116832, 206765, 144000],
|
||||
[90431, -1494, 162929, 144000],
|
||||
[94416, -5480, 170899, 144000],
|
||||
[98401, -9465, 178869, 144000],
|
||||
[104379, -116832, 206765, 144000],
|
||||
[104379, -116832, 206765, 144000]
|
||||
],
|
||||
[
|
||||
[75985, -73993, 149978, 144000],
|
||||
[75985, -73993, 149978, 144000],
|
||||
[75985, -73993, 149978, 144000],
|
||||
[75985, -73993, 149978, 144000],
|
||||
[75985, -73993, 149978, 144000],
|
||||
[75985, -73993, 149978, 144000]
|
||||
]
|
||||
]
|
||||
+31
-7
@@ -38,17 +38,41 @@ python3 target/local-beta/native-beta.py compile /path/to/main.tex /path/to/outp
|
||||
|
||||
## 使用项目的 Web 界面
|
||||
|
||||
将 texrra-web 放在引擎仓库旁边。启动或重开时指定 Web 目录。
|
||||
将 texrra-web 放在引擎仓库旁边。从项目列表新建项目或拖入 ZIP。
|
||||
|
||||
~~~sh
|
||||
python3 target/local-beta/native-beta.py web --web-dir ../texrra-web --projects-dir target/local-projects
|
||||
~~~
|
||||
|
||||
导入后打开项目的主文件,左侧可切换源文件,右侧显示原生实时预览。
|
||||
ZIP 可包含子目录、源文件及图像等资源。库中的导入副本保留原样,
|
||||
编辑时点击「保存源文件」生成独立副本。当前本地服务同时打开一个项目。
|
||||
|
||||
也可用 Web 工作台直接打开样例或重开已保存的项目。
|
||||
|
||||
~~~sh
|
||||
python3 target/local-beta/native-beta.py open --web-dir ../texrra-web
|
||||
python3 target/local-beta/native-beta.py resume /path/to/saved-project --web-dir ../texrra-web
|
||||
~~~
|
||||
|
||||
该入口显示 Web 工作台的文件栏、编辑区和预览区。编辑、局部预览、
|
||||
源码保存及下载 PDF 都使用原生 Beta 会话。每次启动打开一个由命令行
|
||||
指定的项目。现有 Web 的项目列表和 ZIP 导入仍在原 serve 入口。
|
||||
启动指令中的其他参数和保存目录格式与上文相同。
|
||||
## 输入公式
|
||||
|
||||
在编辑区点击「行内公式」或「独立公式」可插入对应的 LaTeX 定界符,
|
||||
并把光标放在公式内部。有选区时,定界符包住已选中的内容。
|
||||
也可以直接键入 $...$ 或 \[...\]。使用 align 环境时,在导言区加入
|
||||
\usepackage{amsmath}。例如在正文中输入以下内容。
|
||||
|
||||
~~~latex
|
||||
行内公式 $E=mc^2$。
|
||||
\[
|
||||
\frac{\alpha+\beta}{\sqrt{1+x^2}}
|
||||
\]
|
||||
~~~
|
||||
|
||||
Tab 输入两个空格或缩进所选行,Shift+Tab 将焦点移到上一个控件。
|
||||
切换文件会记住各自的光标、选区和滚动位置。停顿后的首次编辑和输入法
|
||||
确认立即发起编译,连续输入的后续修改在短暂停顿后合并提交。编译出错时
|
||||
可继续查看上一次成功的预览,修正后页面会自动更新。
|
||||
|
||||
## 保存和重新打开
|
||||
|
||||
@@ -60,8 +84,8 @@ python3 target/local-beta/native-beta.py resume /path/to/saved-project --web-dir
|
||||
python3 target/local-beta/native-beta.py resume /path/to/texrra-sources-directory
|
||||
~~~
|
||||
|
||||
有编译错误的草稿也可以保存。重开目前需要通过首次编译,若草稿仍有错误,
|
||||
可先在保存目录的 sources 中修正源文件。每次保存都会得到独立的一份。
|
||||
有编译错误的草稿也可以保存和重开。打开后可在编辑器修正错误。
|
||||
每次保存都会得到独立的一份。
|
||||
|
||||
## 已对照的项目
|
||||
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
|
||||
本文件记录用户重申的最终目标,是短期 goal、实现优先级和验收标准的上位约束。
|
||||
|
||||
## 2026-12-02 当前开发目标的收尾条件
|
||||
|
||||
用户要求先完成 XeTeX 整行编辑复用和浏览器 100 ms 可见时延。
|
||||
两项都用实际编译和页面交付验证后,可以结束当前开发目标。
|
||||
后续模板由用户补充,按实际项目出现的兼容问题继续适配。
|
||||
下方记录正式版的长期能力范围和原来的统一验收条件。
|
||||
|
||||
## Beta 优先交付
|
||||
|
||||
先交付可试用的 Route-D 本地编辑器和原生 CLI。试用范围列明已实际对照的
|
||||
|
||||
@@ -18,6 +18,436 @@
|
||||
| W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;原样 12 页 NeurIPS 的中部编辑与恢复已验证前后缀复用、仅更新一页,且与独立全量一致。全部副作用/交叉编辑、旧来源与正式性能门禁仍待闭合 |
|
||||
| W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 |
|
||||
|
||||
## 2026-12-02 浏览器可见时延试测
|
||||
|
||||
空闲后的首次编辑和输入法确认立即发起编译,连续输入的后续请求
|
||||
保留合并。计时仍包括接收响应、SVG 解码、实际页面替换和绘制。
|
||||
检查点准备阶段去除对已通过的首候选的重复快照遍历,保留实时
|
||||
文件状态与效果重放校验。宏分配使用地址哈希集合去重,报告
|
||||
访问顺序和计数保持一致,七项统计专项通过。
|
||||
|
||||
本机 Edge 对冻结格式和资源下的原样 A4 执行 60 次不同的正文修改,
|
||||
主文件和子文件各 30 次,均更新实际显示页并核对 PDF 和来源。
|
||||
构建使用 release,内核和引擎包为 opt-level 1。性能二进制在 XeTeX
|
||||
无换行符末行补丁前启动构建,本次 A4 两个文件都有行终止符。
|
||||
|
||||
| A4 热编辑 | 输入到发请求 p50 | 执行 p50 | 编辑到可见 p50 / p95 |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| 主文件正文 | 1.5 ms | 140.6 ms | 242.0 / 370.0 ms |
|
||||
| 子文件正文 | 1.5 ms | 96.0 ms | 192.8 / 272.9 ms |
|
||||
|
||||
服务进程峰值 RSS 602,592 KiB。浏览器可见时延仍高于 100 ms。
|
||||
等待已缩短,主要剩余成本为实际执行、请求响应和页面绘制。
|
||||
主文件的独立诊断表明,输出例程结束后能取得会合候选,但变动
|
||||
后的读依赖集合和累计节点计数可能拒绝复用。后续要补齐可验证的
|
||||
依赖和计数换算,再用相同样例对照独立全量。
|
||||
原始样本、阶段用时和构建指纹位于 `target/p4-browser-visible-progress/`。
|
||||
|
||||
## 2026-12-02 后缀复用的依赖与盒节点计数
|
||||
|
||||
编辑后的前缀保留全部旧前缀依赖时,可把新增依赖并入结果,并保留
|
||||
被跳过的后缀依赖。旧前缀独有的依赖若消失,继续执行。资源统计读取
|
||||
仍须相同。累计盒节点数可沿用后缀增量。若两次运行的盒容量累计值
|
||||
不同,只有在证明后缀不会触发容量重算时才复用。即时发页统计和
|
||||
收尾报告同步换算,宿主重放使用内核确认的收尾报告。依赖记录或
|
||||
累计值变化后,后续快照重新捕获。
|
||||
|
||||
十四项定向管线回归和四项内核单测通过。用例覆盖新增依赖后的实际跳步、依赖减少
|
||||
时重新执行,以及累计节点数双向变化。增量与独立全量的执行、PDF、
|
||||
统计日志和来源映射通过对照。冻结 A4 的六次主文件正文编辑每次
|
||||
只更新第 1 页,复用 849,607 步前缀,仍执行剩余的 53,612 或
|
||||
53,615 步。六次均与独立全量的执行、PDF、SVG、来源、资源记录
|
||||
和生成文件一致。样本与构建清单在
|
||||
`target/p4-a4-suffix-proof/run-men4zig6/`。该批使用 opt-level 0
|
||||
的诊断构建,计时与浏览器基线分开记录。另两次带诊断探针的
|
||||
编辑到达同一发页后的检查,首个拒绝条件均为前缀事件数改变
|
||||
(680 → 694、694 → 696)。A4 的收尾统计确实计入保留事件,
|
||||
后续复用须证明跨接缝的共享关系与新前缀的统计增量。诊断在
|
||||
`target/p4-a4-suffix-proof/run-rabbmwpj/run.log`。
|
||||
|
||||
原生检查点还改为共享未修改的字形 Unicode 映射,实际定义变动时
|
||||
复制。序列化格式和 PDF 字符映射按原规则生成。
|
||||
|
||||
### A4 浏览器复测
|
||||
|
||||
同一台机器的 Edge、同一份格式和资源、同一组实际输入事件。
|
||||
使用相同的 release opt-level 1 构建设置和独立试用服务。
|
||||
主文件和子文件各 30 次,均更新实际显示页。60 次输出的 PDF、
|
||||
SVG 和来源映射指纹逐项与上一批一致。
|
||||
|
||||
| A4 热编辑 | 实际执行 p50 / p95 | 编辑到可见 p50 / p95 |
|
||||
| --- | ---: | ---: |
|
||||
| 主文件正文 | 132.3 / 145.3 ms | 230.3 / 256.3 ms |
|
||||
| 子文件正文 | 86.0 / 126.0 ms | 184.1 / 241.5 ms |
|
||||
|
||||
从输入到发起请求的 p50 均为 1.5 ms。两组的响应到确认绘制
|
||||
p50 分别为 33.2 和 33.3 ms,进程峰值 RSS 为 603,280 KiB。
|
||||
本轮可见时延低于上一批,100 ms 条件仍未通过。两批实际执行
|
||||
步数一致,机器负载有变化,不能把时延差额归因于单个代码变动。
|
||||
原始样本、构建清单、机器状态和逐次输出对照在
|
||||
`target/p4-a4-browser-recheck/`。
|
||||
|
||||
## 2026-12-02 XeTeX 整行编辑复用
|
||||
|
||||
XeTeX 扫描器保留已读物理行采用的分行规则。UTF-8、Bytes 及其他
|
||||
按字节分行的解码器可以在同类规则内切换。稳定的 UTF-16 LE/BE
|
||||
按真实端序和代码单元核对 CR、LF、CRLF、BOM 及接缝。文件末行
|
||||
直接结束时,需同时验证已加载行和 EOF。若已读前缀跨过不同分行
|
||||
规则,继续执行以恢复真实状态。已观察过变化行号的后缀同样重跑。
|
||||
|
||||
原样 12 页 NeurIPS 2025 在第 408 行前插入一条 34 字节注释,
|
||||
并在只保留长版的会话中删除。两次各复用 14,696,911 步前缀和
|
||||
26,853 步后缀,执行 4,847,127 步。两次共各发布 0 个页面更新。
|
||||
末行位置由 765 变为 766,随后恢复。第 4 页字形来源双向移动
|
||||
34 字节。执行、PDF、SVG、页面与来源映射、资源和生成文件均
|
||||
与各自的独立全量相同。更早的会合点之后仍有入口行号观测。
|
||||
记录及资源冻结清单位于 `target/p4-xetex-physical-lines/`。
|
||||
|
||||
四页集成样例使用实写 UTF-16 LE BOM 和 CRLF,并覆盖含 LF 字节的
|
||||
普通字符,整行增删均复用后缀。变更前的十二项扫描及来源单测、
|
||||
加入 EOF 支持后的十二项管线回归通过。
|
||||
|
||||
## 2026-12-01 整行增删后的后缀复用
|
||||
|
||||
固定字节分行的 TeX8Bit 和 UnicodeScalar 输入支持完整物理行的插入和
|
||||
删除。需要有唯一的行边界,且起点之后的原始输入与已加载行能逐字节
|
||||
核验。支持 LF、CRLF 和 CR。会合和发布时分别换算扫描行、组和条件的
|
||||
来源行号、最终输入位置,以及实际 glyph 的字节坐标。XeTeX 可在作业中
|
||||
切换分行编码,整行编辑目前继续重新执行。
|
||||
|
||||
复用按输入源比较会合点和完成作业的行号观测数。即使前缀已经执行过
|
||||
`\inputlineno`,后缀再次读取仍会被发现。诊断和追踪携带的行号也有
|
||||
记录。字节数不变但换行符位置移动时,同样检查后缀中的行号观测。
|
||||
旧执行记录缺少这项证据时,行边界变化后的后缀重新执行。
|
||||
|
||||
四页作业从各自唯一的旧修订增删整行,实际跳过未变后缀。最终的物理
|
||||
行号及后页 glyph 来源同步换算,原页面无需更新。延迟写出重新读取
|
||||
同一源文件行号时,重新执行并在日志中写入新值。另用等长编辑移动
|
||||
保存令牌的来源行,方向盒警告从第 4 行改为第 5 行。与独立全量的
|
||||
执行、PDF、预览、来源映射、资源和生成日志均对照一致。
|
||||
|
||||
用原样五页 PLOS ONE 的冻结格式、书目及 184 项实际资源路径复验。
|
||||
在正文中插入一条 CRLF 注释行后,最终输入位置从第 384 行变为第 385 行。
|
||||
运行记录显示,前缀已经读取过入口行号,增量仍跳过 700,640 步后缀,
|
||||
复用 4 页绘制,预览的页面更新量为 0。增量和独立全量的执行、PDF、
|
||||
SVG、来源映射、资源、aux、out 和 log 均一致。验证结果和文件指纹
|
||||
位于 `target/p4-physical-line-edit/plos/`。
|
||||
|
||||
八项来源与扫描单测和十一项管线回归通过。日志及复现入口在
|
||||
`target/p4-physical-line-edit/`。原有资源、文件副作用和状态会合
|
||||
条件继续适用。
|
||||
|
||||
## 2026-12-01 减少后缀拼接的复制
|
||||
|
||||
发布事件列表按最终长度一次分配。来源换算直接更新已有的草稿节点,
|
||||
共享列表根据实际坐标变更决定是否创建新副本。嵌套缓存命中仍传递
|
||||
来源变化,同一对象在保留的状态和事件中继续共享。换算失败时
|
||||
丢弃本次拼接并继续执行。
|
||||
|
||||
原样 12 页 NeurIPS 的单字节插入和删除各执行 646,780 步,
|
||||
跳过 4,634,847 步后缀。两次均只更新第 3 页,复用其余 11 页。
|
||||
第 4 页的字形来源分别向前或向后移动 1 字节。执行状态、PDF、
|
||||
SVG、来源映射、资源与流、aux、out 和 log 与独立全量一致。
|
||||
两次 PDF 和第 3 页 SVG 与本轮对照版逐字节一致。
|
||||
|
||||
本轮观察到插入和删除的后缀拼接分别用时 400 和 269 ms。
|
||||
并行构建影响了同轮基线的时延,现有采样仍需在固定条件下复验。
|
||||
四项来源换算单测和八项管线回归通过。实跑日志、两组独立全量
|
||||
对照与 PDF/SVG 指纹位于 `target/p4-suffix-draft/`。
|
||||
|
||||
## 2026-12-01 引导盒重复绘制的 PDF 链接
|
||||
|
||||
pdfTeX 把链接的声明尺寸和绘制后的矩形存入同一节点。引导盒的
|
||||
每次平铺再次访问这个节点,并用上次写入的值计算当前矩形。
|
||||
同一节点安排的注释对象最终读取该节点的最后一个矩形。原生在
|
||||
发页遍历内保留平铺节点的身份,同时按原有规则为每次出现创建
|
||||
注释。普通盒副本和同一平铺图案内的不同链接保留各自的身份。
|
||||
|
||||
以 pdfTeX 1.40.29 的实跑 PDF 为参考,四页注释数分别为 3、2、10、6,
|
||||
全部 21 个注释的矩形逐项一致。样例覆盖普通盒副本、平铺内多个链接、
|
||||
放不下的图案、不同对齐位置与水平和垂直嵌套,以及宽度自动延伸的
|
||||
链接。旧原生在第 1 页给三个注释分别写入不同矩形,复现日志与参考
|
||||
PDF 保存在 `target/repeated-leader-links/`。四项引导盒回归和
|
||||
已有的运行链接矩阵变换回归通过。
|
||||
参考 PDF 的 SHA-256 为
|
||||
`a33ca51a7c6c179e91f5edb6699b378f6adaf73c81f8594a0713af10bcf854ce`。
|
||||
|
||||
## 2026-12-01 拆分后缀会合的内核开销
|
||||
|
||||
比较换算后的执行状态时,仅复制需要迁移来源的字段。命令表缓存
|
||||
键集合的有序引用和散列,命令含义仍读取当前值。共享同一段历史的
|
||||
两份会话只统计一次共同事件,继续独立统计各自的后续事件及活跃资源。
|
||||
|
||||
按实际操作拆分的内核会合用时如下。两个编辑方向均复用已验证的后缀。
|
||||
|
||||
| 编辑 | 状态比较 | 保留资源记账 | 后缀拼接 | 内核会合合计 |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| 插入 1 字节 | 107 ms | 132 ms | 367 ms | 612 ms |
|
||||
| 删除 1 字节 | 106 ms | 191 ms | 263 ms | 564 ms |
|
||||
|
||||
原样 12 页 NeurIPS 两次仍执行 646,780 步,跳过 4,634,847 步,
|
||||
重建 1 页绘制并复用 11 页。第 4 页的字形来源随输入变化换算。
|
||||
完整执行及输出与独立全量一致,PDF 和局部 SVG 与上一版逐字节一致。
|
||||
三项定向内核单测和八项管线回归通过。该次观察用于定位后续成本,
|
||||
正式可见时延仍按冻结工况验收。原始记录在
|
||||
`target/p4-kernel-check-phases/`。
|
||||
|
||||
## 2026-12-01 热编辑的会合与宿主开销
|
||||
|
||||
在 `57c05d9` 的 NeurIPS 同一行增删对照中,从 Prepared 到
|
||||
Executed 取得 1,098 个 CPU 样本。高频位置包括内存分配、
|
||||
复制、命令排序,以及用于确认宏来源的 token 克隆。
|
||||
|
||||
宏重定位现在先检查来源和调用位置,位置移动时才复制宏体。
|
||||
同一次会合与后缀拼接共享已验证的结果。直接更新已有草稿,
|
||||
省去对完整状态的重复复制。成功执行也直接拥有已取得的资源
|
||||
轨迹,被其他修订取消的结果和失败证据继续保留各自的轨迹。
|
||||
编译观察器可分别取得捕获、宿主核验、内核核验、后缀重放
|
||||
和保留检查点的时间。
|
||||
|
||||
同一项目两个热编辑的 Prepared 至 Executed 由 2.28/2.12 秒
|
||||
记录为 1.57/1.07 秒。会合核验与拼接分别占 808/523 毫秒,
|
||||
此区间的宿主核验和后缀重放合计 21/14 毫秒。扣除这些实测区间
|
||||
及捕获开销后,恢复、执行和核心收尾还有 723/525 毫秒。
|
||||
宏和 token 重定位相关样本由 62/1,098 降至 19/661。
|
||||
这些数据用于选定下一次优化位置。正式可见时延和内存仍按冻结
|
||||
工况采样。
|
||||
|
||||
两次仍执行 646,780 步、跳过 4,634,847 步后缀,重生成 1 页
|
||||
绘制并复用 11 页。完整执行、PDF、SVG、字形来源、显示列表、
|
||||
资源和文件效果等同独立全量,PDF 和局部 SVG 与上版逐字节一致。
|
||||
八项管线回归和三项失败及取消回归通过。
|
||||
下一批沿内核会合核验拆分状态比较、资源记账和后缀换算。
|
||||
证据位于 `target/p4-hot-execution-profile/`。
|
||||
|
||||
### Springer Nature 旋转目标复核
|
||||
|
||||
本地 pdfTeX 1.40.29 上,同一个旋转 XYZ 目标仅在输入前加入
|
||||
一个创建后丢弃的空盒,坐标就从 `[71.004 128.249]` 变成
|
||||
`[-4009.694 128.249]`,栅格相同。八种控制在 INITEX 和 plain
|
||||
格式各重复两次,同组 PDF 字节一致。所检查的 WEB 实现表明,
|
||||
普通 XYZ 未写入 FitR 尺寸字段,但矩阵输出会读取这些节点槽位。
|
||||
该结果依赖内核节点分配与释放历史,Springer 第 5 页 `table.3`
|
||||
坐标差异仍开放。对照与源码版本指纹已保存在
|
||||
`target/p4-hot-execution-profile/springer-controls/`。
|
||||
|
||||
## 2026-12-01 复用已核验后缀的页面绘制
|
||||
|
||||
宿主重放通过后,当前编译尝试保留实际后缀原执行的身份、首个
|
||||
复用页及已验证的来源换算。缓存绘制属于同一执行对象且页序匹配
|
||||
时,直接使用其原始绘制列表并换算字形和 XDV 表单调用的来源。
|
||||
其余页面继续走现有的精确比较和绘制流程。较早的执行可以提供
|
||||
后缀,当前已经发布的页面缓存仍需匹配原执行。
|
||||
|
||||
当前修订继续解析字体、投影 PDF 表单和资源、生成来源映射并完成
|
||||
导出。
|
||||
|
||||
12 页原样 NeurIPS 的第 3 页分别插入和删除 1 字节。两次都从
|
||||
第 272 行恢复,执行 646,780 步并跳过 4,634,847 步未改后缀。
|
||||
重新生成的绘制列表由上版 10 页降为 1 页,复用 11 页,两次都只
|
||||
发布第 3 页。第 4 页字形来源按当前输入移动 1 字节。完整执行、
|
||||
PDF、SVG、显示列表、来源映射、资源与流轨迹,以及 aux、out、log
|
||||
均与独立全量一致。两份 PDF 及局部 SVG 与上版对应产物逐字节一致。
|
||||
|
||||
六项内核单测和十项管线回归通过。原执行身份不一致时,仍可复用
|
||||
已核验的执行后缀,当前缓存绘制按原有逐页比较。证据及指纹位于
|
||||
`target/p4-relocated-layout/`。本次两次热编辑在 Prepared 至 Executed
|
||||
阶段分别用时 2.14 秒和 1.78 秒。后续测清宿主重放和内核执行各自的
|
||||
成本,正式可见时延与内存仍按冻结语料验收。
|
||||
|
||||
## 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 源码增删后复用已执行的前缀
|
||||
|
||||
原生会话校验入口已装载的物理行和前缀字节。改动留在未读部分时,
|
||||
可以恢复已经出页的检查点。历史出页统计使用当前入口字节数重算
|
||||
源码、扫描缓冲区及首次宿主读取的计数。其余资源、输入流和输出
|
||||
操作仍逐项核验。若正文已通过 `\pdffilesize` 读取入口大小,
|
||||
文件长度改变会使该检查点失效,查询从较早边界重新执行。
|
||||
|
||||
优化构建与七项定向回归通过,包含插入、删除、显式大小查询,以及
|
||||
原有后缀复用和资源核验。12 页 NeurIPS 样稿保留原始文件,项目
|
||||
快照另加一行 `\tracingstats=2` 以覆盖全部 12 次出页统计。在第 9 页
|
||||
先插入 5 字节,再删除 6 字节,分别从第 621、644 行恢复。
|
||||
实际重新执行 1,966,711 和 1,733,850 步,分别约占同版本全量的
|
||||
10.0% 和 8.9%。两次都只发布第 9 页的预览更新。完整执行、PDF、
|
||||
显示列表、SVG、来源映射、资源与流轨迹,以及 aux、out、log
|
||||
都与独立全量一致。证据在 `target/p4-resized-entry-prefix/`。
|
||||
|
||||
异长编辑后仍执行剩余输入。下一步以字节一致的物理行验证会合,
|
||||
将旧后缀内已核实的来源区间映射至当前入口坐标,并用独立全量核对。
|
||||
正式兼容性矩阵、可见时延及内存报告继续按产品目标验收。
|
||||
|
||||
## 2026-12-01 逻辑步数变化后复用已核验的后缀
|
||||
|
||||
会合时用当前已完成步数加上旧后缀实际执行的步数。全程保留原有
|
||||
内核状态、材料、来源、依赖和宿主核验。换算超出步数上限则继续
|
||||
真实执行并给出对应诊断。调整后的检查点仅在布局帧已经结束时
|
||||
传给后续编辑,以避免沿用活动帧此前保存的预算。
|
||||
|
||||
出页和收尾的结构化统计使用换算后的计数,收尾诊断以同一格式
|
||||
生成并重放到当前日志,仍核对诊断字节上限。定向用例用相同长度的
|
||||
两种宏调用分别增加和减少步数,两个方向都复用后缀。结构化统计、
|
||||
PDF、来源及日志与独立全量一致。将步数上限设为原任务总数后,
|
||||
增加步数的版本与独立全量报同样的错,保留上一版 PDF。
|
||||
|
||||
原样 12 页 NeurIPS 先改第 3 页标点,随后改第 9 页分号。
|
||||
总执行步数由 19,570,891 增至 19,570,892。第二次从第 620 行
|
||||
恢复,执行 1,030,251 步,跳过 935,951 步后缀,只更新第 9 页。
|
||||
完整执行、PDF、SVG、来源、依赖、文件流及 aux/out/log 均逐轮
|
||||
与同版独立全量一致。旧证据相同修改曾跳过零步,两个版本对应的
|
||||
PDF、SVG 仍逐字节一致。
|
||||
|
||||
优化构建和四项定向回归通过。证据在 target/p4-step-offset/,
|
||||
SHA256SUMS 指纹为
|
||||
a89992a774bbde20a66d18106ae8fe7e30eab4cad46b8071f2bee6540443e122。
|
||||
后续处理输入长度改变后的来源位置。一致性、可见时延与内存继续
|
||||
按产品总目标的正式门禁验收。
|
||||
|
||||
## 2026-12-01 正文编辑后保留排版材料的共享关系
|
||||
|
||||
原样 NeurIPS 改第 3 页标点,完整事件序列中只有四条值发生变化。
|
||||
其中竖直材料、段落和出页三条持有盒子或诊断列表。此前合并历史
|
||||
后,活跃状态的统计相符,保留历史却多计了 49 个盒子、2,032 个
|
||||
水平节点和 2,043 个诊断节点,后续候选因此被拒绝。
|
||||
|
||||
合并时保留变化事件中值相同的子列表分配。沿用当前修订不同的值,
|
||||
在同一次合并中保留其共享关系。保存后续检查点前仍检查会合位置
|
||||
和恢复位置的完整材料统计及存活引用关系,并重放和核对宿主边界。
|
||||
此前未读历史统计的作业也在会合位置完成材料核验,以便后续修订
|
||||
可以开启统计。
|
||||
|
||||
原样 NeurIPS 先改第 3 页标点,再改单个第 9 页字母。第二次从
|
||||
第 620 行恢复,上一版从第 345 行恢复。实际执行从 3,699,397
|
||||
降至 1,030,250 步,减少 72.2%。两次分别只更新第 3、9 页。
|
||||
完整执行、PDF、SVG、来源、查找、资源、流、aux/out 和日志均
|
||||
逐次与同版独立全量一致。两个版本对应的 PDF 和 SVG 字节相同。
|
||||
|
||||
优化构建及三项定向回归通过。12 页用例让后续页面复用同一份
|
||||
TeX 盒子,并校验持续编辑与全量一致。证据在 target/p4-alias-graft/。
|
||||
SHA256SUMS 指纹为
|
||||
f10c4fcf3e81caa642efcfa873fb48032b8937eab1e8c1ceed3dbb31271c8839。
|
||||
下一入口是逻辑步数变化后的安全收敛,需继续核对步数预算和真实
|
||||
统计输出。正式浏览器可见时延、峰值内存和兼容矩阵继续统一验收。
|
||||
|
||||
## 2026-12-01 将已验证的后续检查点带入新修订
|
||||
|
||||
后缀复用完成时,会话可保留更靠后的执行检查点供下次编辑恢复。
|
||||
后续检查点沿用已经核验的旧执行状态和事件块,换入新修订的源码
|
||||
与有变化的事件。内容相同的事件保留其原分配,以便仍引用它们的
|
||||
后续状态保持一致。材料统计和共享关系、输入扫描器及隔离草稿的
|
||||
文件操作均核验通过后才保留。每个源码区间沿用已有的检查点预算。
|
||||
|
||||
12 页定向 TeX 文档先改第 2 页再改第 9 页,第二次从更后的位置
|
||||
恢复,保留前一次编辑。两次结果的执行、PDF、预览和来源与独立
|
||||
全量一致。优化构建和三项会话回归通过。
|
||||
|
||||
原样 NeurIPS 先修改第 7 行注释。无页面变化,复用 5,882,245 个
|
||||
后缀执行步。随后修改第 9 页正文,从第 620 行恢复,实际执行
|
||||
1,030,250 步,只更新第 9 页。两个修订的完整执行、PDF、SVG、
|
||||
绘制列表、来源、依赖、文件流与 aux/out/log 均与各自独立全量一致。
|
||||
|
||||
原样 NeurIPS 第 3 页正文标点接第 9 页字母的既有序列仍从第 345
|
||||
行恢复,实际执行 3,699,397 步。诊断确认后续候选未通过材料历史
|
||||
核验。该序列的两个修订和上轮 PDF、SVG 逐字节一致,各自通过
|
||||
本轮全量对照。下一步应处理发生变化的出页事件中仍被后续状态
|
||||
引用的材料,继续保留现有核验规则。正式时延和内存待统一验收。
|
||||
|
||||
证据在 target/p4-rebased-prefix/,包括首轮材料核验拒绝记录。
|
||||
SHA256SUMS 指纹为
|
||||
f41de187a38acb2bac83af19d2fefb25b837048b0af81d2817f687c5f294a878。
|
||||
|
||||
## 2026-12-01 八页之后的后缀检查点
|
||||
|
||||
每份完成执行仍最多保留八个收敛检查点。前四页逐页保留,
|
||||
后面四个位置随页数增大间隔。间隔翻倍时移除不再落在
|
||||
新间隔上的旧位置。相同页边界上的内核和宿主核验继续生效。
|
||||
调度模拟到一百万页,已保留的检查点峰值仍为八个。
|
||||
|
||||
原样 12 页 NeurIPS 先编辑第 3 页,随后将第 9 页同一字母
|
||||
改成小写。本轮相对 a5dba52 跳过 935,951 步,实际执行
|
||||
从 4,635,348 降至 3,699,397 步,只更新第 9 页。第 3 页编辑的
|
||||
复用量相同。两种标点替换各增加一个逻辑执行步,未满足
|
||||
现有收敛约束,继续执行后缀。三个对照的每次编辑均与各自
|
||||
独立全量的完整执行、PDF、SVG、来源、资源和辅助文件一致。
|
||||
两个构建之间对应的 PDF 和 SVG 也逐字节相同。
|
||||
|
||||
优化构建和三项定向回归通过,含 12 页 TeX 用例、连续跨页
|
||||
编辑和宿主重放后安全回退。证据在 target/p4-long-settled/,
|
||||
SHA256SUMS 指纹为
|
||||
08988302c45d9cbab093dda42d7547070d9cbb9dc43974a593d1380640b3a3d3。
|
||||
|
||||
跨到第 9 页时仍从第 345 行恢复,下一步要验证如何复用更靠近
|
||||
编辑处的前缀和已有页面来源。逻辑步数变化后的收敛仍待处理。
|
||||
正式可见时延、内存和兼容矩阵继续统一验收。
|
||||
|
||||
## 2026-12-01 连续跨页编辑保留后缀检查点
|
||||
|
||||
后缀复用成功后,本轮只执行到收敛点。会话现在还会保留一份能
|
||||
提供更后检查点的已完成执行。每次使用都按当前源码、内核状态、
|
||||
实际依赖和宿主调用重新核验并重放。只保留一个额外比对来源。
|
||||
|
||||
原样 NeurIPS 2025 的 12 页作业连续编辑第 3 页两次,随后编辑
|
||||
第 4 页。前两次分别执行 646,780 和 546,599 步。第三次从相同
|
||||
的入口检查点恢复,较旧的已归档优化库执行 4,635,348 步,
|
||||
本轮跳过其后 4,068,540 步,实际执行 566,808 步。每次只更新
|
||||
受编辑的一页。三次修订的完整执行、PDF、SVG、绘制列表、来源、
|
||||
读取与查找、流位置、aux/out 和日志均与本轮的独立全量一致。
|
||||
|
||||
跨构建比较中三份 PDF 逐字节相同。第 4 页 SVG 有四处双引号属性
|
||||
转义差异,来自旧库之后已经合入的 SVG 修复。保留原差异。
|
||||
优化构建及两项会话回归通过,涵盖跨页连续编辑和重放拒绝后的
|
||||
草稿回退。证据在 target/p4-consecutive-suffix/,SHA256SUMS
|
||||
指纹为 b84b3dc54061a4aa8f403069a1d1653940a92814959beb2f25ad5475c8b63fd2。
|
||||
|
||||
仍需覆盖八页之后的收敛采集,以及源字节长度变化后的位置对应。
|
||||
可见时延、峰值内存和兼容矩阵继续按统一验收执行。
|
||||
|
||||
## 2026-11-29 原生 Web Beta 公式与项目导入
|
||||
|
||||
空白正文首次编译后再编辑公式,旧版本会把尚未捕获的已安装数学字体
|
||||
和宏包判为缺失。原生编辑会话按失败查找记录,在声明的 TeX 资源树中
|
||||
解析实际文件,扩展只读输入快照并在同一修订重试。保留已有输入字节、
|
||||
输出权限和取消行为。真正的编译错误仍保留上一版可下载 PDF。
|
||||
|
||||
现有 Web 项目列表接通本地项目库和 ZIP 拖放。原样 A4 多文件放在
|
||||
ZIP 的子目录,已有同名 PDF 和额外图像保留原字节。Edge 中首次
|
||||
插入行内公式、陈列公式,再添加 amsmath 与 align。每次实际改变
|
||||
版面只替换第一页。未知命令显示诊断,恢复后能继续编辑。下载的
|
||||
PDF 与保存源码副本的独立命令行两轮编译逐字节一致。
|
||||
|
||||
证据在 target/native-beta-library/。SHA256SUMS 指纹为
|
||||
3e606a869968058f881f9faa440976e1a767fe5e49b2c99c6cb32b2386083b1c。
|
||||
试用包沿用已验证的 pdfLaTeX 格式和本机 TeX Live 资源。
|
||||
[Web 启动和公式输入](NATIVE_BETA.md#使用项目的-web-界面)
|
||||
|
||||
## 2026-11-29 原生 Beta 接入 texrra-web 工作台
|
||||
|
||||
本地启动器的 --web-dir 接入现有 texrra-web 的 HTML、样式和图标。
|
||||
|
||||
+155
-18
@@ -13,12 +13,18 @@ const selector = document.querySelector("#project-files");
|
||||
const name = document.querySelector("#name, #open-file-path");
|
||||
const fileTree = document.querySelector("#file-tree");
|
||||
const edits = new Map();
|
||||
const fileViews = new Map();
|
||||
const EDIT_IDLE_MS = 70;
|
||||
let files;
|
||||
let activeFile;
|
||||
let sequence = 0;
|
||||
let publishedRevision = null;
|
||||
let draft = null;
|
||||
let frame;
|
||||
let composing = false;
|
||||
let compileTimer;
|
||||
let lastTypingAt = -Infinity;
|
||||
let promptCompilePending = false;
|
||||
const projectPrefix = location.pathname.startsWith("/p/") ? location.pathname.slice(0, -1) : "";
|
||||
const previewDraft = new URLSearchParams(location.hash.slice(1)).get("preview") !== "published";
|
||||
|
||||
function attachWebControls() {
|
||||
@@ -38,7 +44,9 @@ function attachWebControls() {
|
||||
download.textContent = "下载 PDF";
|
||||
document.querySelector("#export-pdf").replaceWith(download);
|
||||
|
||||
document.querySelector("#back-button").hidden = true;
|
||||
const back = document.querySelector("#back-button");
|
||||
back.hidden = !location.pathname.startsWith("/p/");
|
||||
back.addEventListener("click", () => { location.href = "/"; });
|
||||
document.querySelector("#toggle-engine").hidden = true;
|
||||
document.querySelector("#header-actions").textContent = "原生 Beta";
|
||||
document.querySelector("footer").textContent = "Ctrl/Cmd+S 保存源码副本";
|
||||
@@ -49,9 +57,31 @@ function attachWebControls() {
|
||||
}
|
||||
|
||||
function selectFile(filename) {
|
||||
if (filename === activeFile) return;
|
||||
if (activeFile !== undefined) {
|
||||
if (composing) {
|
||||
// Let the platform commit the old file before replacing its buffer.
|
||||
source.blur();
|
||||
if (composing) {
|
||||
composing = false;
|
||||
queueCompile(true);
|
||||
}
|
||||
}
|
||||
fileViews.set(activeFile, {
|
||||
start: source.selectionStart,
|
||||
end: source.selectionEnd,
|
||||
direction: source.selectionDirection,
|
||||
top: source.scrollTop,
|
||||
left: source.scrollLeft,
|
||||
});
|
||||
}
|
||||
activeFile = filename;
|
||||
name.textContent = filename;
|
||||
source.value = edits.get(filename) ?? files.get(filename);
|
||||
const view = fileViews.get(filename);
|
||||
source.setSelectionRange(view?.start ?? 0, view?.end ?? 0, view?.direction ?? "none");
|
||||
source.scrollTop = view?.top ?? 0;
|
||||
source.scrollLeft = view?.left ?? 0;
|
||||
if (fileTree) {
|
||||
for (const row of fileTree.children) {
|
||||
const selected = row.dataset.path === activeFile;
|
||||
@@ -115,14 +145,14 @@ function restorePublishedPages() {
|
||||
function acceptPublication(revision, previous) {
|
||||
revokeDetached(previous);
|
||||
publishedRevision = revision;
|
||||
pdf.href = `/pdf?revision=${revision}`;
|
||||
pdf.href = projectPrefix + `/pdf?revision=${revision}`;
|
||||
pdf.hidden = false;
|
||||
draft = null;
|
||||
}
|
||||
|
||||
async function publicationStatus(edit, revision) {
|
||||
while (edit === sequence) {
|
||||
const response = await fetch(`/publication?revision=${revision}`);
|
||||
const response = await fetch(projectPrefix + `/publication?revision=${revision}`);
|
||||
const result = await response.json();
|
||||
if (!response.ok || result.state === "failed") throw new Error(result.error);
|
||||
if (result.state === "published") return result;
|
||||
@@ -134,7 +164,7 @@ async function publicationStatus(edit, revision) {
|
||||
async function compile(edit, submitted, changes) {
|
||||
const replacements = [];
|
||||
try {
|
||||
const response = await fetch("/preview", {
|
||||
const response = await fetch(projectPrefix + "/preview", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
@@ -212,14 +242,97 @@ async function compile(edit, submitted, changes) {
|
||||
}
|
||||
}
|
||||
|
||||
function queueCompile() {
|
||||
const edit = ++sequence;
|
||||
const submitted = performance.now();
|
||||
cancelAnimationFrame(frame);
|
||||
function invalidatePreview() {
|
||||
++sequence;
|
||||
clearTimeout(compileTimer);
|
||||
compileTimer = undefined;
|
||||
promptCompilePending = false;
|
||||
restorePublishedPages();
|
||||
status.textContent = "正在编译";
|
||||
const changes = Object.fromEntries(edits);
|
||||
frame = requestAnimationFrame(() => compile(edit, submitted, changes));
|
||||
}
|
||||
|
||||
function queueCompile(immediate = false) {
|
||||
const submitted = performance.now();
|
||||
// Edits arriving before the first dispatch share its prompt submission.
|
||||
const prompt = immediate || promptCompilePending || submitted - lastTypingAt >= EDIT_IDLE_MS;
|
||||
invalidatePreview();
|
||||
if (!immediate) lastTypingAt = submitted;
|
||||
promptCompilePending = prompt;
|
||||
const edit = sequence;
|
||||
if (status.textContent !== "正在编译") status.textContent = "正在编译";
|
||||
compileTimer = setTimeout(() => {
|
||||
if (edit !== sequence || composing) return;
|
||||
compileTimer = undefined;
|
||||
promptCompilePending = false;
|
||||
compile(edit, submitted, Object.fromEntries(edits));
|
||||
}, prompt ? 0 : EDIT_IDLE_MS);
|
||||
}
|
||||
|
||||
function recordEdit(forceCompile = false) {
|
||||
const changed = source.value !== (edits.get(activeFile) ?? files.get(activeFile));
|
||||
if (changed) edits.set(activeFile, source.value);
|
||||
if (changed || forceCompile) queueCompile(forceCompile);
|
||||
}
|
||||
|
||||
function replaceSourceRange(text, start, end, selectionStart, selectionEnd, direction) {
|
||||
source.focus({ preventScroll: true });
|
||||
source.setSelectionRange(start, end);
|
||||
const before = source.value;
|
||||
try {
|
||||
// Use the browser's editing command when available so insertion is undoable.
|
||||
document.execCommand("insertText", false, text);
|
||||
} catch {
|
||||
// The range API also works when the editing command is unavailable.
|
||||
}
|
||||
if (source.value === before) source.setRangeText(text, start, end, "end");
|
||||
source.setSelectionRange(selectionStart, selectionEnd, direction);
|
||||
recordEdit();
|
||||
}
|
||||
|
||||
function indentSource() {
|
||||
const start = source.selectionStart;
|
||||
const end = source.selectionEnd;
|
||||
if (start === end) {
|
||||
replaceSourceRange(" ", start, end, start + 2, start + 2, "none");
|
||||
return;
|
||||
}
|
||||
const firstLine = start === 0 ? 0 : source.value.lastIndexOf("\n", start - 1) + 1;
|
||||
const selection = source.value.slice(firstLine, end);
|
||||
const indented = selection.split("\n").map((line, index, lines) =>
|
||||
index === lines.length - 1 && line === "" ? line : " " + line
|
||||
).join("\n");
|
||||
replaceSourceRange(indented, firstLine, end, start + 2,
|
||||
end + indented.length - selection.length, source.selectionDirection);
|
||||
}
|
||||
|
||||
function addFormulaButtons() {
|
||||
const heading = document.querySelector(".editor-panel .panel-head, .edit .file");
|
||||
if (!heading) return;
|
||||
const group = document.createElement("span");
|
||||
group.setAttribute("role", "group");
|
||||
group.setAttribute("aria-label", "插入公式");
|
||||
group.style.display = "inline-flex";
|
||||
group.style.gap = ".35rem";
|
||||
group.style.marginInlineStart = ".5rem";
|
||||
group.style.whiteSpace = "nowrap";
|
||||
for (const [label, open, close] of [
|
||||
["行内公式", "$", "$"],
|
||||
["独立公式", "\\[\n", "\n\\]"],
|
||||
]) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "btn small";
|
||||
button.textContent = label;
|
||||
button.addEventListener("click", () => {
|
||||
if (composing || source.disabled || source.readOnly) return;
|
||||
const start = source.selectionStart;
|
||||
const end = source.selectionEnd;
|
||||
const selection = source.value.slice(start, end);
|
||||
replaceSourceRange(open + selection + close, start, end,
|
||||
start + open.length, end + open.length, source.selectionDirection);
|
||||
});
|
||||
group.append(button);
|
||||
}
|
||||
heading.append(group);
|
||||
}
|
||||
|
||||
async function saveSources() {
|
||||
@@ -227,7 +340,7 @@ async function saveSources() {
|
||||
saved.hidden = false;
|
||||
saved.textContent = "正在保存源文件";
|
||||
try {
|
||||
const response = await fetch("/save", {
|
||||
const response = await fetch(projectPrefix + "/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ sequence, files: Object.fromEntries(edits) }),
|
||||
@@ -244,7 +357,7 @@ async function saveSources() {
|
||||
|
||||
async function openProject() {
|
||||
try {
|
||||
const response = await fetch("/project");
|
||||
const response = await fetch(projectPrefix + "/project");
|
||||
if (!response.ok) throw new Error("无法打开源文件");
|
||||
const project = await response.json();
|
||||
files = new Map(Object.entries(project.files));
|
||||
@@ -264,10 +377,15 @@ async function openProject() {
|
||||
}
|
||||
selectFile(project.name);
|
||||
source.disabled = false;
|
||||
source.setAttribute("autocapitalize", "off");
|
||||
source.setAttribute("autocorrect", "off");
|
||||
source.setAttribute("autocomplete", "off");
|
||||
addFormulaButtons();
|
||||
sequence = project.sequence;
|
||||
save.disabled = false;
|
||||
save.addEventListener("click", saveSources);
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (composing || event.isComposing) return;
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
|
||||
event.preventDefault();
|
||||
if (!save.disabled) saveSources();
|
||||
@@ -280,11 +398,30 @@ async function openProject() {
|
||||
name.hidden = true;
|
||||
selector.addEventListener("change", () => selectFile(selector.value));
|
||||
}
|
||||
source.addEventListener("input", () => {
|
||||
edits.set(activeFile, source.value);
|
||||
queueCompile();
|
||||
source.addEventListener("compositionstart", () => {
|
||||
composing = true;
|
||||
invalidatePreview();
|
||||
});
|
||||
queueCompile();
|
||||
source.addEventListener("compositionend", () => {
|
||||
if (!composing) return;
|
||||
composing = false;
|
||||
recordEdit(true);
|
||||
});
|
||||
source.addEventListener("input", (event) => {
|
||||
if (composing) return;
|
||||
if (event.isComposing) {
|
||||
invalidatePreview();
|
||||
return;
|
||||
}
|
||||
recordEdit();
|
||||
});
|
||||
source.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Tab" || composing || event.isComposing
|
||||
|| event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;
|
||||
event.preventDefault();
|
||||
indentSource();
|
||||
});
|
||||
queueCompile(true);
|
||||
} catch (failure) {
|
||||
showError(failure.message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"use strict";
|
||||
|
||||
const list = document.querySelector("#projects-view");
|
||||
const grid = document.querySelector("#project-grid");
|
||||
const empty = document.querySelector("#projects-empty");
|
||||
const upload = document.querySelector("#upload-zip");
|
||||
const input = document.querySelector("#zip-input");
|
||||
const drop = document.querySelector("#drop-zone");
|
||||
const create = document.querySelector("#new-project");
|
||||
const message = document.querySelector("#toast");
|
||||
|
||||
list.hidden = false;
|
||||
document.querySelector("#header-actions").textContent = "原生 Beta";
|
||||
document.querySelector("footer").textContent = "";
|
||||
|
||||
async function request(path, options) {
|
||||
const response = await fetch(path, options);
|
||||
const result = await response.json();
|
||||
if (!response.ok) throw new Error(result.error);
|
||||
return result;
|
||||
}
|
||||
|
||||
function open(project) {
|
||||
location.href = "/p/" + encodeURIComponent(project.id) + "/";
|
||||
}
|
||||
|
||||
function projectCard(project) {
|
||||
const card = document.createElement("article");
|
||||
card.className = "project-card";
|
||||
const body = document.createElement("div");
|
||||
body.className = "project-body";
|
||||
const title = document.createElement("h3");
|
||||
title.textContent = project.name;
|
||||
const details = document.createElement("p");
|
||||
details.className = "project-meta";
|
||||
details.textContent = project.mainFile || "没有 TeX 主文件";
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "project-actions";
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "btn primary";
|
||||
button.textContent = "打开";
|
||||
button.disabled = !project.mainFile;
|
||||
button.addEventListener("click", () => open(project));
|
||||
actions.append(button);
|
||||
body.append(title, details, actions);
|
||||
card.append(body);
|
||||
return card;
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const { projects } = await request("/api/projects");
|
||||
grid.replaceChildren(...projects.map(projectCard));
|
||||
empty.hidden = projects.length > 0;
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function showError(error) {
|
||||
message.hidden = false;
|
||||
message.textContent = error.message;
|
||||
}
|
||||
|
||||
async function importFile(file) {
|
||||
if (!file || upload.disabled) return;
|
||||
if (!file.name.toLowerCase().endsWith(".zip")) {
|
||||
showError(new Error("请选择 ZIP 压缩包"));
|
||||
return;
|
||||
}
|
||||
upload.disabled = true;
|
||||
message.hidden = true;
|
||||
try {
|
||||
const name = file.name.slice(0, -4);
|
||||
const project = await request("/api/projects?name=" + encodeURIComponent(name), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/zip" },
|
||||
body: file,
|
||||
});
|
||||
open(project);
|
||||
} catch (error) {
|
||||
showError(error);
|
||||
} finally {
|
||||
input.value = "";
|
||||
upload.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
upload.addEventListener("click", () => input.click());
|
||||
input.addEventListener("change", () => importFile(input.files[0]));
|
||||
drop.addEventListener("dragover", (event) => event.preventDefault());
|
||||
drop.addEventListener("drop", (event) => {
|
||||
event.preventDefault();
|
||||
importFile(event.dataTransfer.files[0]);
|
||||
});
|
||||
// An in-page form works in embeddable browsers that suppress JS prompts.
|
||||
const projectDialog = document.createElement("dialog");
|
||||
projectDialog.style.cssText = "width:min(26rem, calc(100% - 2rem));padding:1.25rem;border:1px solid #d5dce3;border-radius:12px";
|
||||
const projectForm = document.createElement("form");
|
||||
projectForm.style.cssText = "display:grid;gap:.8rem";
|
||||
const projectName = document.createElement("input");
|
||||
projectName.type = "text";
|
||||
projectName.required = true;
|
||||
projectName.autocomplete = "off";
|
||||
projectName.id = "project-name";
|
||||
projectName.style.cssText = "width:100%;padding:.55rem .65rem;font:inherit";
|
||||
const projectLabel = document.createElement("label");
|
||||
projectLabel.htmlFor = projectName.id;
|
||||
projectLabel.id = "project-name-label";
|
||||
projectLabel.textContent = "项目名称";
|
||||
projectDialog.setAttribute("aria-labelledby", projectLabel.id);
|
||||
const projectError = document.createElement("p");
|
||||
projectError.hidden = true;
|
||||
projectError.setAttribute("role", "alert");
|
||||
const projectActions = document.createElement("div");
|
||||
projectActions.style.cssText = "display:flex;justify-content:flex-end;gap:.5rem";
|
||||
const cancel = document.createElement("button");
|
||||
cancel.type = "button";
|
||||
cancel.className = "btn";
|
||||
cancel.textContent = "取消";
|
||||
const submit = document.createElement("button");
|
||||
submit.type = "submit";
|
||||
submit.className = "btn primary";
|
||||
submit.textContent = "创建项目";
|
||||
projectActions.append(cancel, submit);
|
||||
projectForm.append(projectLabel, projectName, projectError, projectActions);
|
||||
projectDialog.append(projectForm);
|
||||
document.body.append(projectDialog);
|
||||
|
||||
create.addEventListener("click", () => {
|
||||
projectName.value = "";
|
||||
projectName.setCustomValidity("");
|
||||
projectError.hidden = true;
|
||||
projectDialog.showModal();
|
||||
projectName.focus();
|
||||
});
|
||||
cancel.addEventListener("click", () => projectDialog.close());
|
||||
projectName.addEventListener("input", () => projectName.setCustomValidity(""));
|
||||
projectForm.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
if (submit.disabled) return;
|
||||
const name = projectName.value.trim();
|
||||
if (!name) {
|
||||
projectName.setCustomValidity("请输入项目名称");
|
||||
projectName.reportValidity();
|
||||
return;
|
||||
}
|
||||
submit.disabled = true;
|
||||
projectError.hidden = true;
|
||||
try {
|
||||
const project = await request("/api/projects/new", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name }),
|
||||
});
|
||||
open(project);
|
||||
} catch (error) {
|
||||
projectError.textContent = error.message;
|
||||
projectError.hidden = false;
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
refresh();
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::{EditorSession, InputProfile, fs, json, prepare, projects::ProjectStore, reply};
|
||||
use std::{
|
||||
io::{ErrorKind, Read},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
use tiny_http::Request;
|
||||
|
||||
pub(super) const SCRIPT: &str = include_str!("library.js");
|
||||
const MAX_ZIP_UPLOAD: u64 = 64 * 1024 * 1024;
|
||||
|
||||
pub(super) struct Library {
|
||||
store: ProjectStore,
|
||||
format: PathBuf,
|
||||
manifest: PathBuf,
|
||||
runs: PathBuf,
|
||||
profile: InputProfile,
|
||||
}
|
||||
|
||||
impl Library {
|
||||
pub(super) fn new(
|
||||
store: PathBuf,
|
||||
format: PathBuf,
|
||||
manifest: PathBuf,
|
||||
runs: PathBuf,
|
||||
profile: InputProfile,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
fs::create_dir_all(&store)?;
|
||||
let store = store.canonicalize()?;
|
||||
fs::create_dir_all(&runs)?;
|
||||
let runs = runs.canonicalize()?;
|
||||
if runs.starts_with(&store) || store.starts_with(&runs) {
|
||||
return Err("Project and compilation directories must be separate".into());
|
||||
}
|
||||
Ok(Self {
|
||||
store: ProjectStore::new(store)?,
|
||||
format,
|
||||
manifest,
|
||||
runs,
|
||||
profile,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn list(&self, request: Request) {
|
||||
match self.store.list() {
|
||||
Ok(projects) => reply(request, 200, json!({"projects": projects})),
|
||||
Err(error) => reply(request, 500, json!({"error": error})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn import(&self, mut request: Request) {
|
||||
if !request.headers().iter().any(|header| {
|
||||
header.field.equiv("Content-Type")
|
||||
&& header.value.as_str().split(';').next() == Some("application/zip")
|
||||
}) {
|
||||
reply(request, 415, json!({"error": "Expected a ZIP archive"}));
|
||||
return;
|
||||
}
|
||||
let name = project_name(&request);
|
||||
let mut bytes = Vec::new();
|
||||
if let Err(error) = request
|
||||
.as_reader()
|
||||
.take(MAX_ZIP_UPLOAD + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
{
|
||||
reply(request, 400, json!({"error": error.to_string()}));
|
||||
return;
|
||||
}
|
||||
if bytes.len() as u64 > MAX_ZIP_UPLOAD {
|
||||
reply(request, 413, json!({"error": "ZIP upload exceeds 64 MB"}));
|
||||
return;
|
||||
}
|
||||
match self.store.create_from_zip(&name, &bytes) {
|
||||
Ok(project) => reply(request, 201, json!(project)),
|
||||
Err(error) => reply(request, 422, json!({"error": error})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create(&self, mut request: Request) {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct NewProject {
|
||||
name: String,
|
||||
}
|
||||
if !request.headers().iter().any(|header| {
|
||||
header.field.equiv("Content-Type")
|
||||
&& header.value.as_str().split(';').next() == Some("application/json")
|
||||
}) {
|
||||
reply(
|
||||
request,
|
||||
415,
|
||||
json!({"error": "Expected JSON project details"}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let project: NewProject = match super::read_json(&mut request) {
|
||||
Ok(value) => value,
|
||||
Err(error) => {
|
||||
reply(request, 400, json!({"error": error}));
|
||||
return;
|
||||
}
|
||||
};
|
||||
match self.store.create_empty(&project.name) {
|
||||
Ok(project) => reply(request, 201, json!(project)),
|
||||
Err(error) => reply(request, 422, json!({"error": error})),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open(&self, id: &str) -> Result<EditorSession, Box<dyn std::error::Error>> {
|
||||
let root = self.store.project_dir(id)?;
|
||||
if fs::symlink_metadata(&root)?.file_type().is_symlink() {
|
||||
return Err("The project directory must be a local working copy".into());
|
||||
}
|
||||
let info = self.store.info(id)?;
|
||||
if info.main_file.is_empty() {
|
||||
return Err("The project does not contain a TeX entry file".into());
|
||||
}
|
||||
let source = self.store.file_path(id, &info.main_file)?.canonicalize()?;
|
||||
let files = info
|
||||
.files
|
||||
.iter()
|
||||
.filter(|file| file.path != info.main_file)
|
||||
.map(|file| PathBuf::from(&file.path))
|
||||
.collect::<Vec<_>>();
|
||||
let run = fresh_run(&self.runs, id)?;
|
||||
let mut session = EditorSession::new(run, |run| {
|
||||
prepare(
|
||||
&root,
|
||||
&source,
|
||||
&self.format,
|
||||
&self.manifest,
|
||||
run,
|
||||
&files,
|
||||
self.profile,
|
||||
)
|
||||
})?;
|
||||
session.id = Some(info.id);
|
||||
Ok(session)
|
||||
}
|
||||
}
|
||||
|
||||
fn fresh_run(parent: &Path, id: &str) -> std::io::Result<PathBuf> {
|
||||
for index in 1.. {
|
||||
let candidate = parent.join(format!("{id}-{}-{index}", std::process::id()));
|
||||
match fs::create_dir(&candidate) {
|
||||
Ok(()) => return Ok(candidate),
|
||||
Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
unreachable!()
|
||||
}
|
||||
|
||||
fn project_name(request: &Request) -> String {
|
||||
let name = request
|
||||
.url()
|
||||
.split_once('?')
|
||||
.and_then(|(_, query)| query.split('&').find_map(|pair| pair.strip_prefix("name=")))
|
||||
.unwrap_or("Project");
|
||||
let mut bytes = Vec::with_capacity(name.len());
|
||||
let mut input = name.as_bytes().iter().copied();
|
||||
while let Some(byte) = input.next() {
|
||||
match byte {
|
||||
b'%' => {
|
||||
let hex = |byte: u8| char::from(byte).to_digit(16);
|
||||
if let Some(value) = input.next().and_then(hex).zip(input.next().and_then(hex)) {
|
||||
bytes.push((value.0 * 16 + value.1) as u8);
|
||||
}
|
||||
}
|
||||
b'+' => bytes.push(b' '),
|
||||
_ => bytes.push(byte),
|
||||
}
|
||||
}
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
}
|
||||
+327
-87
@@ -8,7 +8,7 @@ use std::{
|
||||
path::{Component, Path, PathBuf},
|
||||
sync::{
|
||||
Arc, Condvar, Mutex,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
@@ -19,10 +19,15 @@ use texrra_engine::native::{
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
execution::InputProfile,
|
||||
resources::{InputPolicy, SearchPath, WorldConfig},
|
||||
resources::{InputPolicy, ResourceKind, SearchPath, WorldConfig},
|
||||
};
|
||||
use tiny_http::{Header, Method, Request, Response, Server};
|
||||
|
||||
mod library;
|
||||
#[path = "../../src/projects.rs"]
|
||||
#[allow(dead_code)]
|
||||
mod projects;
|
||||
mod resource_capture;
|
||||
mod saved_project;
|
||||
|
||||
const MAX_EDIT_BODY: u64 = 2 * 1024 * 1024;
|
||||
@@ -177,6 +182,7 @@ struct Publication {
|
||||
|
||||
#[derive(Default)]
|
||||
struct Queue {
|
||||
closed: AtomicBool,
|
||||
next: Mutex<Option<Work>>,
|
||||
available: Condvar,
|
||||
current: AtomicU64,
|
||||
@@ -188,7 +194,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
std::process::exit(status);
|
||||
}
|
||||
let mut args = std::env::args_os().skip(1).peekable();
|
||||
let usage = "native_editor [--input-profile tex8bit|unicode|xetex] [--web-dir DIR] SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...]";
|
||||
let usage = "native_editor [--input-profile PROFILE] [--web-dir DIR] [--source-root DIR] SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...] or native_editor [--input-profile PROFILE] --web-dir DIR --projects STORE FORMAT FORMAT_RESOURCES RUNS [PORT]";
|
||||
let input_profile = if args.next_if(|arg| arg == "--input-profile").is_some() {
|
||||
match args.next().as_deref().and_then(std::ffi::OsStr::to_str) {
|
||||
Some("tex8bit") => InputProfile::TeX8Bit,
|
||||
@@ -205,63 +211,172 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut args = args.map(PathBuf::from);
|
||||
let source = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let manifest = args.next().ok_or(usage)?;
|
||||
let run = args.next().ok_or(usage)?;
|
||||
let port = args
|
||||
.next()
|
||||
.map(|s| s.to_string_lossy().parse())
|
||||
.transpose()?
|
||||
.unwrap_or(0u16);
|
||||
let additional = args.collect::<Vec<_>>();
|
||||
fs::create_dir(&run)?;
|
||||
let run = run.canonicalize()?;
|
||||
let EditorProject {
|
||||
mut project,
|
||||
entry,
|
||||
editable,
|
||||
declared,
|
||||
options,
|
||||
} = prepare(&source, &format, &manifest, &run, &additional, input_profile)?;
|
||||
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let source_root = if args.next_if(|arg| arg == "--source-root").is_some() {
|
||||
Some(PathBuf::from(args.next().ok_or(usage)?).canonicalize()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut args = args.map(PathBuf::from).peekable();
|
||||
let library = if args.next_if(|arg| arg == Path::new("--projects")).is_some() {
|
||||
let store = args.next().ok_or(usage)?;
|
||||
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let manifest = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let runs = args.next().ok_or(usage)?;
|
||||
Some(library::Library::new(
|
||||
store,
|
||||
format,
|
||||
manifest,
|
||||
runs,
|
||||
input_profile,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if library.is_some() && web.is_none() {
|
||||
return Err("The project library requires --web-dir".into());
|
||||
}
|
||||
let (port, mut session) = if library.is_some() {
|
||||
(read_port(args.next())?, None)
|
||||
} else {
|
||||
let source = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let format = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let manifest = args.next().ok_or(usage)?.canonicalize()?;
|
||||
let run = args.next().ok_or(usage)?;
|
||||
let port = read_port(args.next())?;
|
||||
let additional = args.collect::<Vec<_>>();
|
||||
fs::create_dir(&run)?;
|
||||
let run = run.canonicalize()?;
|
||||
let root = source_root
|
||||
.as_deref()
|
||||
.unwrap_or_else(|| source.parent().expect("a source file has a parent"));
|
||||
(
|
||||
port,
|
||||
Some(EditorSession::new(run, |run| {
|
||||
prepare(
|
||||
root,
|
||||
&source,
|
||||
&format,
|
||||
&manifest,
|
||||
run,
|
||||
&additional,
|
||||
input_profile,
|
||||
)
|
||||
})?),
|
||||
)
|
||||
};
|
||||
let server = Server::http(("127.0.0.1", port)).map_err(|e| e.to_string())?;
|
||||
let queue = Arc::new(Queue {
|
||||
current: AtomicU64::new(project.version().revision),
|
||||
..Queue::default()
|
||||
});
|
||||
std::thread::spawn({
|
||||
let queue = queue.clone();
|
||||
move || worker(&queue)
|
||||
});
|
||||
let mut save_number = 0;
|
||||
println!("Native editor http://{}", server.server_addr());
|
||||
for request in server.incoming_requests() {
|
||||
let path = request.url().to_owned();
|
||||
match (request.method(), path.as_str()) {
|
||||
(&Method::Get, "/") => respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref().map_or_else(|| PAGE.into(), |assets| assets.index.clone()),
|
||||
),
|
||||
(&Method::Get, "/styles.css") if web.is_some() => respond(
|
||||
request, 200, "text/css; charset=utf-8", web.as_ref().unwrap().styles.clone(),
|
||||
),
|
||||
(&Method::Get, "/favicon.svg") if web.is_some() => respond(
|
||||
request, 200, "image/svg+xml", web.as_ref().unwrap().favicon.clone(),
|
||||
),
|
||||
// The shared Web shell requests this stylesheet. Native preview
|
||||
// pages carry their glyph outlines in their SVG output.
|
||||
(&Method::Get, "/fonts.css") if web.is_some() => {
|
||||
respond(request, 200, "text/css; charset=utf-8", Vec::new())
|
||||
let url = request.url().to_owned();
|
||||
let path = url.as_str();
|
||||
if let (&Method::Get, Some(assets)) = (request.method(), &web) {
|
||||
if let Some((kind, bytes)) = assets.file(path) {
|
||||
respond(request, 200, kind, bytes);
|
||||
continue;
|
||||
}
|
||||
(&Method::Get, "/app.js") => respond(
|
||||
}
|
||||
if path == "/app.js" && request.method() == &Method::Get {
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/javascript; charset=utf-8",
|
||||
SCRIPT.into(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let mut session_path = path;
|
||||
if let Some(library) = &library {
|
||||
if path == "/" && request.method() == &Method::Get {
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref().unwrap().dashboard.clone(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if path == "/library.js" && request.method() == &Method::Get {
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/javascript; charset=utf-8",
|
||||
library::SCRIPT.into(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if path == "/api/projects" && request.method() == &Method::Get {
|
||||
library.list(request);
|
||||
continue;
|
||||
}
|
||||
if path.starts_with("/api/projects?") && request.method() == &Method::Post {
|
||||
library.import(request);
|
||||
continue;
|
||||
}
|
||||
if path == "/api/projects/new" && request.method() == &Method::Post {
|
||||
library.create(request);
|
||||
continue;
|
||||
}
|
||||
let Some((id, rest)) = path
|
||||
.strip_prefix("/p/")
|
||||
.and_then(|path| path.split_once('/'))
|
||||
else {
|
||||
reply(request, 404, json!({"error": "Not found"}));
|
||||
continue;
|
||||
};
|
||||
if rest.is_empty() && request.method() == &Method::Get {
|
||||
if session.as_ref().and_then(|s| s.id.as_deref()) != Some(id) {
|
||||
match library.open(id) {
|
||||
Ok(next) => session = Some(next),
|
||||
Err(error) => {
|
||||
reply(request, 422, json!({"error": error.to_string()}));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref().unwrap().index.clone(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if session.as_ref().and_then(|s| s.id.as_deref()) != Some(id) {
|
||||
reply(
|
||||
request,
|
||||
409,
|
||||
json!({"error": "The project is no longer open. Reload to reopen it."}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
session_path = &path[path.len() - rest.len() - 1..];
|
||||
}
|
||||
let Some(session) = &mut session else {
|
||||
reply(request, 404, json!({"error": "Not found"}));
|
||||
continue;
|
||||
};
|
||||
let EditorSession {
|
||||
run,
|
||||
compiler,
|
||||
queue,
|
||||
save_number,
|
||||
editor,
|
||||
..
|
||||
} = session;
|
||||
let EditorProject {
|
||||
project,
|
||||
entry,
|
||||
editable,
|
||||
declared,
|
||||
options,
|
||||
} = editor;
|
||||
match (request.method(), session_path) {
|
||||
(&Method::Get, "/") => respond(
|
||||
request,
|
||||
200,
|
||||
"text/html; charset=utf-8",
|
||||
web.as_ref()
|
||||
.map_or_else(|| PAGE.into(), |assets| assets.index.clone()),
|
||||
),
|
||||
(&Method::Get, "/project") => {
|
||||
let file = project.file(&entry).expect("the editor owns its entry");
|
||||
@@ -274,7 +389,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
request,
|
||||
200,
|
||||
json!({
|
||||
"name": entry.file_name().unwrap().to_string_lossy(),
|
||||
"name": entry.strip_prefix(run.as_path()).unwrap().to_string_lossy(),
|
||||
"source": std::str::from_utf8(&file.data)?,
|
||||
"files": files,
|
||||
"sequence": queue.current.load(Ordering::Acquire),
|
||||
@@ -306,7 +421,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let path = editable
|
||||
.get(&name)
|
||||
.ok_or_else(|| format!("File is not editable: {name}"))?;
|
||||
if *path == entry && value.is_none() {
|
||||
if path == entry && value.is_none() {
|
||||
return Err("The entry file cannot be removed".into());
|
||||
}
|
||||
Ok((path.clone(), value.map(|text| Arc::from(text.into_bytes()))))
|
||||
@@ -322,7 +437,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
project.with_file_changes(edit.sequence, updates)
|
||||
});
|
||||
project = match next {
|
||||
*project = match next {
|
||||
Ok(project) => project,
|
||||
Err(error) => {
|
||||
reply(request, 422, json!({ "error": error }));
|
||||
@@ -367,17 +482,31 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
};
|
||||
if save.sequence < queue.current.load(Ordering::Acquire) {
|
||||
reply(request, 409, json!({"error": "A newer edit is already queued"}));
|
||||
reply(
|
||||
request,
|
||||
409,
|
||||
json!({"error": "A newer edit is already queued"}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
let changes: Option<BTreeMap<_, _>> = save.files.iter()
|
||||
.map(|(name, data)| editable.get(name).map(|path| (path.as_path(), data.as_bytes())))
|
||||
let changes: Option<BTreeMap<_, _>> = save
|
||||
.files
|
||||
.iter()
|
||||
.map(|(name, data)| {
|
||||
editable
|
||||
.get(name)
|
||||
.map(|path| (path.as_path(), data.as_bytes()))
|
||||
})
|
||||
.collect();
|
||||
let Some(changes) = changes else {
|
||||
reply(request, 422, json!({"error": "The save refers to an unknown source file"}));
|
||||
reply(
|
||||
request,
|
||||
422,
|
||||
json!({"error": "The save refers to an unknown source file"}),
|
||||
);
|
||||
continue;
|
||||
};
|
||||
match saved_project::save(&run, &entry, &declared, &project, changes, &mut save_number) {
|
||||
match saved_project::save(run, entry, declared, project, changes, save_number) {
|
||||
Ok(path) => reply(request, 200, json!({"directory": path})),
|
||||
Err(error) => reply(request, 500, json!({"error": error.to_string()})),
|
||||
}
|
||||
@@ -442,6 +571,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
|
||||
struct WebAssets {
|
||||
dashboard: Vec<u8>,
|
||||
index: Vec<u8>,
|
||||
styles: Vec<u8>,
|
||||
favicon: Vec<u8>,
|
||||
@@ -449,12 +579,77 @@ struct WebAssets {
|
||||
|
||||
impl WebAssets {
|
||||
fn load(path: &Path) -> std::io::Result<Self> {
|
||||
let index = fs::read_to_string(path.join("index.html"))?;
|
||||
let dashboard = index.replace("src=\"/app.js\"", "src=\"/library.js\"");
|
||||
Ok(Self {
|
||||
index: fs::read(path.join("index.html"))?,
|
||||
dashboard: dashboard.into_bytes(),
|
||||
index: index.into_bytes(),
|
||||
styles: fs::read(path.join("styles.css"))?,
|
||||
favicon: fs::read(path.join("favicon.svg"))?,
|
||||
})
|
||||
}
|
||||
|
||||
fn file(&self, path: &str) -> Option<(&'static str, Vec<u8>)> {
|
||||
match path {
|
||||
"/styles.css" => Some(("text/css; charset=utf-8", self.styles.clone())),
|
||||
"/favicon.svg" => Some(("image/svg+xml", self.favicon.clone())),
|
||||
"/fonts.css" => Some(("text/css; charset=utf-8", Vec::new())),
|
||||
"/app.js" => Some(("text/javascript; charset=utf-8", SCRIPT.into())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_port(value: Option<PathBuf>) -> Result<u16, std::num::ParseIntError> {
|
||||
value.map_or(Ok(0), |port| port.to_string_lossy().parse())
|
||||
}
|
||||
|
||||
struct EditorSession {
|
||||
id: Option<String>,
|
||||
run: PathBuf,
|
||||
compiler: NativeCompiler,
|
||||
queue: Arc<Queue>,
|
||||
save_number: u64,
|
||||
editor: EditorProject,
|
||||
}
|
||||
|
||||
impl EditorSession {
|
||||
fn new(
|
||||
run: PathBuf,
|
||||
prepare_editor: impl FnOnce(&Path) -> Result<EditorProject, Box<dyn std::error::Error>>,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let editor = prepare_editor(&run)?;
|
||||
let compiler = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let queue = Arc::new(Queue {
|
||||
current: AtomicU64::new(editor.project.version().revision),
|
||||
..Queue::default()
|
||||
});
|
||||
std::thread::spawn({
|
||||
let queue = queue.clone();
|
||||
move || worker(&queue)
|
||||
});
|
||||
Ok(Self {
|
||||
id: None,
|
||||
run,
|
||||
compiler,
|
||||
queue,
|
||||
save_number: 0,
|
||||
editor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EditorSession {
|
||||
fn drop(&mut self) {
|
||||
let mut pending = self.queue.next.lock().unwrap();
|
||||
self.queue.closed.store(true, Ordering::Release);
|
||||
// A fresh revision cancels any work still running on the old session.
|
||||
self.compiler.start();
|
||||
if let Some(old) = pending.take() {
|
||||
reply(old.request, 409, json!({"error": "The project has closed"}));
|
||||
}
|
||||
self.queue.available.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn read_json<T: serde::de::DeserializeOwned>(request: &mut Request) -> Result<T, String> {
|
||||
@@ -479,6 +674,7 @@ struct EditorProject {
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
source_root: &Path,
|
||||
source: &Path,
|
||||
format: &Path,
|
||||
manifest: &Path,
|
||||
@@ -491,16 +687,24 @@ fn prepare(
|
||||
let mut world = WorldConfig::from_environment(run, roots)?;
|
||||
world.input_policy = InputPolicy::Tex;
|
||||
let name = source
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.strip_prefix(source_root)?
|
||||
.to_str()
|
||||
.ok_or("Source needs a UTF-8 filename")?;
|
||||
let entry = run.join(name);
|
||||
let entry_dir = entry.parent().expect("the entry has a parent");
|
||||
fs::create_dir_all(entry_dir)?;
|
||||
if entry_dir != run {
|
||||
world
|
||||
.paths
|
||||
.entry(ResourceKind::Tex)
|
||||
.or_insert_with(|| vec![SearchPath::Defaults])
|
||||
.insert(0, SearchPath::directory(entry_dir, false));
|
||||
}
|
||||
let original = fs::read(source)?;
|
||||
std::str::from_utf8(&original)?;
|
||||
fs::write(&entry, &original)?;
|
||||
let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]);
|
||||
let mut files = BTreeMap::<PathBuf, Arc<[u8]>>::from([(entry.clone(), Arc::from(original))]);
|
||||
let source_root = source.parent().expect("the entry has a parent");
|
||||
let mut declared = BTreeSet::from([entry.clone()]);
|
||||
let mut directories = BTreeSet::new();
|
||||
for relative in additional {
|
||||
@@ -561,12 +765,14 @@ fn prepare(
|
||||
files.insert(logical, data);
|
||||
}
|
||||
}
|
||||
let mut request = CompileRequest::new(
|
||||
world.clone(),
|
||||
&entry,
|
||||
entry.with_extension("pdf"),
|
||||
job_time()?,
|
||||
);
|
||||
let mut output = entry.with_extension("pdf");
|
||||
if declared.contains(&output) || declared.contains(&output.with_extension("log")) {
|
||||
let directory = run.join(".texrra-output");
|
||||
fs::create_dir(&directory)?;
|
||||
directories.insert(directory.clone());
|
||||
output = directory.join(output.file_name().expect("the output has a filename"));
|
||||
}
|
||||
let mut request = CompileRequest::new(world.clone(), &entry, output, job_time()?);
|
||||
request.entry = Entry::Format(format.into());
|
||||
request.etex = true;
|
||||
request.input_profile = input_profile;
|
||||
@@ -574,13 +780,28 @@ fn prepare(
|
||||
request = request.observe_generated_initial();
|
||||
// Provision the finite, immutable resource bundle used by this trial.
|
||||
// The seed uses the same native compiler and actual package bytes.
|
||||
let seed = NativeCompiler::default().compile(request.clone())?;
|
||||
for (path, captured) in seed.inputs.files() {
|
||||
if !path.starts_with(run) {
|
||||
files.insert(path.to_owned(), captured?.data.clone());
|
||||
let seed = NativeCompiler::default().compile_detailed(request.clone());
|
||||
let (inputs, trace, generated) = match &seed {
|
||||
Ok(seed) => (
|
||||
Some(seed.inputs.as_ref()),
|
||||
Some(&seed.resources.trace),
|
||||
Some(&seed.resources.generated_artifacts),
|
||||
),
|
||||
Err(failure) if matches!(failure.error, CompileError::Execution(_)) => (
|
||||
failure.inputs.as_deref(),
|
||||
failure.trace.as_ref(),
|
||||
failure.resources.as_ref().map(|r| &r.generated_artifacts),
|
||||
),
|
||||
Err(failure) => return Err(failure.error.to_string().into()),
|
||||
};
|
||||
for (path, captured) in inputs.iter().flat_map(|inputs| inputs.files()) {
|
||||
if let Ok(file) = captured
|
||||
&& !path.starts_with(run)
|
||||
{
|
||||
files.insert(path.to_owned(), file.data.clone());
|
||||
}
|
||||
}
|
||||
for lookup in &seed.resources.trace.lookups {
|
||||
for lookup in trace.iter().flat_map(|trace| &trace.lookups) {
|
||||
if let Some(path) = &lookup.resolved
|
||||
&& !path.starts_with(run)
|
||||
&& !files.contains_key(path)
|
||||
@@ -605,11 +826,9 @@ fn prepare(
|
||||
coverage.insert(path.parent().ok_or("A resource needs a parent")?.to_owned());
|
||||
}
|
||||
}
|
||||
let generated = seed
|
||||
.resources
|
||||
.generated_artifacts
|
||||
.writes
|
||||
let generated = generated
|
||||
.iter()
|
||||
.flat_map(|artifacts| &artifacts.writes)
|
||||
.map(|write| write.path.clone())
|
||||
.collect();
|
||||
let project = ProjectSnapshot::new(ProjectDefinition {
|
||||
@@ -632,8 +851,16 @@ fn prepare(
|
||||
}
|
||||
|
||||
fn worker(queue: &Arc<Queue>) {
|
||||
let mut resources = resource_capture::ResourceCapture::default();
|
||||
loop {
|
||||
let Work {
|
||||
let work = queue
|
||||
.available
|
||||
.wait_while(queue.next.lock().unwrap(), |next| {
|
||||
next.is_none() && !queue.closed.load(Ordering::Acquire)
|
||||
})
|
||||
.unwrap()
|
||||
.take();
|
||||
let Some(Work {
|
||||
request,
|
||||
job,
|
||||
mut compile,
|
||||
@@ -641,12 +868,10 @@ fn worker(queue: &Arc<Queue>) {
|
||||
visible_revision,
|
||||
received,
|
||||
preview_draft,
|
||||
} = queue
|
||||
.available
|
||||
.wait_while(queue.next.lock().unwrap(), |next| next.is_none())
|
||||
.unwrap()
|
||||
.take()
|
||||
.expect("the worker was woken with an edit");
|
||||
}) = work
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let observer = Arc::new(EditorObserver {
|
||||
started: Instant::now(),
|
||||
ended: Mutex::new([0.0; 5]),
|
||||
@@ -659,7 +884,22 @@ fn worker(queue: &Arc<Queue>) {
|
||||
});
|
||||
let revision = job.revision();
|
||||
compile.observer = Some(observer.clone());
|
||||
let result = job.compile(compile);
|
||||
let mut project = compile
|
||||
.project
|
||||
.clone()
|
||||
.expect("the editor submits a project snapshot");
|
||||
project = resources
|
||||
.apply(&project)
|
||||
.expect("captured resources retain their original roots");
|
||||
let result = job
|
||||
.compile_expanding_project(compile.with_project(project.clone()), |failure| {
|
||||
if observer.request.lock().unwrap().is_none() || !observer.is_current() {
|
||||
return None;
|
||||
}
|
||||
project = resources.expand(&project, failure)?;
|
||||
Some(project.clone())
|
||||
})
|
||||
.map_err(|failure| failure.error);
|
||||
let compile_ms = observer.elapsed_ms();
|
||||
let request = observer.request.lock().unwrap().take();
|
||||
let Some(request) = request else {
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
};
|
||||
use texrra_engine::native::CompileFailure;
|
||||
use texrra_tex_core::resources::{FileWorld, ProjectSnapshot, ResourceKind, SearchPath};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ResourceCapture {
|
||||
resources: BTreeMap<PathBuf, Arc<[u8]>>,
|
||||
host: Option<FileWorld>,
|
||||
}
|
||||
|
||||
impl ResourceCapture {
|
||||
pub(super) fn apply(
|
||||
&self,
|
||||
project: &Arc<ProjectSnapshot>,
|
||||
) -> Result<Arc<ProjectSnapshot>, String> {
|
||||
project.with_external_resources(&self.resources)
|
||||
}
|
||||
|
||||
pub(super) fn expand(
|
||||
&mut self,
|
||||
project: &Arc<ProjectSnapshot>,
|
||||
failure: &CompileFailure,
|
||||
) -> Option<Arc<ProjectSnapshot>> {
|
||||
let trace = failure.trace.as_ref()?;
|
||||
let config = project.configuration();
|
||||
let search_roots = config
|
||||
.texmf_roots
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(
|
||||
config
|
||||
.paths
|
||||
.values()
|
||||
.flatten()
|
||||
.filter_map(|path| match path {
|
||||
SearchPath::Directory { path, .. } => Some(config.cwd.join(path)),
|
||||
SearchPath::Defaults => None,
|
||||
}),
|
||||
)
|
||||
.collect::<Vec<_>>();
|
||||
let host = match &mut self.host {
|
||||
Some(host) => host,
|
||||
slot => slot.insert(FileWorld::new(config.clone()).ok()?),
|
||||
};
|
||||
let mut queried = BTreeSet::new();
|
||||
let mut added = BTreeMap::new();
|
||||
for lookup in trace
|
||||
.lookups
|
||||
.iter()
|
||||
.filter(|lookup| lookup.resolved.is_none())
|
||||
{
|
||||
if !queried.insert((lookup.kind, &lookup.name, &lookup.from)) {
|
||||
continue;
|
||||
}
|
||||
let resolved = if lookup.kind == ResourceKind::Tex {
|
||||
host.resolve_tex_input(&lookup.name, &lookup.from)
|
||||
} else {
|
||||
host.resolve(lookup.kind, &lookup.name, &lookup.from)
|
||||
};
|
||||
if let Ok(Some(path)) = resolved
|
||||
&& !path.starts_with(&config.cwd)
|
||||
&& search_roots.iter().any(|root| path.starts_with(root))
|
||||
&& project.file(&path).is_none()
|
||||
&& fs::metadata(&path).is_ok_and(|metadata| metadata.is_file())
|
||||
&& let Ok(bytes) = fs::read(&path)
|
||||
{
|
||||
added.insert(path, Arc::from(bytes));
|
||||
}
|
||||
}
|
||||
if added.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let expanded = project.with_external_resources(&added).ok()?;
|
||||
self.resources.extend(added);
|
||||
Some(expanded)
|
||||
}
|
||||
}
|
||||
@@ -50,7 +50,9 @@ pub(super) fn save(
|
||||
files.push(name);
|
||||
}
|
||||
}
|
||||
let entry_name = entry.file_name().expect("the entry has a name").to_str().unwrap();
|
||||
let entry_name = entry
|
||||
.strip_prefix(run)
|
||||
.expect("entry stays in the working copy");
|
||||
let manifest = fs::File::create(staging.join("project.json"))?;
|
||||
serde_json::to_writer_pretty(manifest, &serde_json::json!({
|
||||
"entry": entry_name, "files": files,
|
||||
|
||||
+17
-3
@@ -125,13 +125,20 @@ def launch(args):
|
||||
env.update(manifest["environment"])
|
||||
env["TEXRRA_STATE_DIR"] = str(bundle / "state")
|
||||
profile = manifest["input_profile"]
|
||||
if args.action in ("open", "resume"):
|
||||
if args.action == "web":
|
||||
command = [
|
||||
bundle / "bin" / binary_name("native_editor"), "--input-profile", profile,
|
||||
"--web-dir", args.web_dir.resolve(strict=True), "--projects",
|
||||
args.projects_dir.resolve(), bundle / FORMAT, bundle / RESOURCES,
|
||||
bundle / "web-runs", str(args.port),
|
||||
]
|
||||
elif args.action in ("open", "resume"):
|
||||
if args.action == "resume":
|
||||
saved = args.snapshot.resolve(strict=True)
|
||||
project = json.loads((saved / "project.json").read_text(encoding="utf-8"))
|
||||
entry = Path(project["entry"])
|
||||
if len(entry.parts) != 1 or entry.name in ("", ".."):
|
||||
raise ValueError("The saved project entry must be a filename")
|
||||
if entry.is_absolute() or not entry.parts or ".." in entry.parts:
|
||||
raise ValueError("The saved project entry must be a relative path")
|
||||
source = (saved / "sources" / entry).resolve(strict=True)
|
||||
assets = project["files"]
|
||||
else:
|
||||
@@ -146,6 +153,8 @@ def launch(args):
|
||||
command = [bundle / "bin" / binary_name("native_editor"), "--input-profile", profile]
|
||||
if args.web_dir:
|
||||
command.extend(["--web-dir", args.web_dir.resolve(strict=True)])
|
||||
if args.action == "resume":
|
||||
command.extend(["--source-root", saved / "sources"])
|
||||
command.extend([source, bundle / FORMAT, bundle / RESOURCES, run, str(args.port), *assets])
|
||||
else:
|
||||
command = native_command(bundle / "bin" / binary_name("texrra"), profile, roots)
|
||||
@@ -178,6 +187,11 @@ def main():
|
||||
command.add_argument("--run-dir", type=Path)
|
||||
command.add_argument("--port", type=int, default=0)
|
||||
|
||||
web = commands.add_parser("web", help="open the native Web project library")
|
||||
web.add_argument("--web-dir", type=Path, required=True)
|
||||
web.add_argument("--projects-dir", type=Path, default=Path("projects"))
|
||||
web.add_argument("--port", type=int, default=0)
|
||||
|
||||
compiler = commands.add_parser("compile", help="produce a PDF with the bundle's native CLI")
|
||||
compiler.add_argument("entry", type=Path)
|
||||
compiler.add_argument("output", type=Path)
|
||||
|
||||
+69
-11
@@ -27,6 +27,7 @@ use std::{
|
||||
collections::BTreeMap,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
pub use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot, ProjectVersion};
|
||||
pub use texrra_tex_core::resources::{WorldFailure, WorldObservation};
|
||||
@@ -34,7 +35,7 @@ use texrra_tex_core::{
|
||||
execution::{
|
||||
Cancellation, ExecutionFailure, Executor, FormatImage, InputProfile, JobTime, Limits,
|
||||
NativeSession, Profile, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceFile,
|
||||
SourceProvider, State, WriteDestination,
|
||||
SourceProvider, State, SuffixKernelTimings, WriteDestination,
|
||||
},
|
||||
pdf_unicode::XdvGlyphNames,
|
||||
render::{DisplayItem, DisplayList},
|
||||
@@ -94,12 +95,32 @@ pub enum CompileStage {
|
||||
Exported,
|
||||
ReadyToPublish,
|
||||
}
|
||||
/// Elapsed work while resuming a native checkpoint after prefix replay.
|
||||
/// The callback slices are disjoint and included in `resume`.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct CheckpointTimings {
|
||||
/// Restoring the executor, running new commands, observing checkpoints,
|
||||
/// and finishing the revision's kernel result.
|
||||
pub resume: Duration,
|
||||
pub capture: Duration,
|
||||
pub suffix_host_validation: Duration,
|
||||
pub suffix_kernel_validation: Duration,
|
||||
/// Subintervals within `suffix_kernel_validation`.
|
||||
pub suffix_kernel: SuffixKernelTimings,
|
||||
pub suffix_host_replay: Duration,
|
||||
/// Collecting the retained checkpoint set after the resumed run.
|
||||
pub retain: Duration,
|
||||
}
|
||||
|
||||
/// Called outside the publication lock. An observer can request a new
|
||||
/// revision or fail without publishing this result. Start/cancel are allowed;
|
||||
/// schedule compilation after the callback returns, rather than recursing.
|
||||
pub trait CompileObserver: Send + Sync {
|
||||
fn stage(&self, revision: u64, stage: CompileStage) -> Result<(), String>;
|
||||
|
||||
/// Observe the work of a resumed native revision before layout begins.
|
||||
fn checkpoint_timings(&self, _revision: u64, _timings: CheckpointTimings) {}
|
||||
|
||||
/// Called for a completed native draft before its staged files are synced
|
||||
/// and installed. The caller can display these pages provisionally. The
|
||||
/// compile result determines whether this revision actually published.
|
||||
@@ -982,6 +1003,34 @@ impl CompileJob {
|
||||
}
|
||||
pub fn compile_detailed(
|
||||
self,
|
||||
request: CompileRequest,
|
||||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||||
self.compile_attempt(request)
|
||||
}
|
||||
|
||||
/// Retry a failed, unpublished attempt in the same revision after the
|
||||
/// caller supplies a new snapshot. A newer revision cancels every attempt.
|
||||
pub fn compile_expanding_project(
|
||||
self,
|
||||
mut request: CompileRequest,
|
||||
mut expand: impl FnMut(&CompileFailure) -> Option<Arc<ProjectSnapshot>>,
|
||||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||||
for _ in 0..24 {
|
||||
match self.compile_attempt(request.clone()) {
|
||||
Err(failure) if !self.job.cancellation().is_cancelled() => {
|
||||
let Some(project) = expand(&failure) else {
|
||||
return Err(failure);
|
||||
};
|
||||
request = request.with_project(project);
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
self.compile_attempt(request)
|
||||
}
|
||||
|
||||
fn compile_attempt(
|
||||
&self,
|
||||
mut request: CompileRequest,
|
||||
) -> Result<Arc<CompiledDocument>, CompileFailure> {
|
||||
if self.compiler.entry_checkpoints.is_some()
|
||||
@@ -1099,9 +1148,9 @@ impl CompileJob {
|
||||
evidence.phase = AttemptPhase::Executing;
|
||||
let cache = &self.compiler.line_break_cache;
|
||||
let before = cache.work();
|
||||
let (executed, next_checkpoint) = if let Some(current) = active_checkpoint {
|
||||
let (executed, next_checkpoint, reused_layouts) = if let Some(current) = active_checkpoint {
|
||||
debug_assert!(executor.is_none());
|
||||
let (executed, next) = current.resume(
|
||||
let (executed, next, reused_layouts) = current.resume(
|
||||
&request,
|
||||
&self.job,
|
||||
source,
|
||||
@@ -1111,7 +1160,7 @@ impl CompileJob {
|
||||
allow_suffix,
|
||||
suffix_failure,
|
||||
)?;
|
||||
(executed, Some(next))
|
||||
(executed, Some(next), reused_layouts)
|
||||
} else {
|
||||
let executor = executor
|
||||
.expect("fresh native job has an executor")
|
||||
@@ -1122,9 +1171,9 @@ impl CompileJob {
|
||||
if let Some(snapshot) = &captured {
|
||||
snapshot.report_capture(&mut entry_checkpoint_work);
|
||||
}
|
||||
(executed, captured)
|
||||
(executed, captured, None)
|
||||
} else {
|
||||
(self.job.run_detailed(executor, source, files), None)
|
||||
(self.job.run_detailed(executor, source, files), None, None)
|
||||
}
|
||||
};
|
||||
let execution = match executed {
|
||||
@@ -1163,18 +1212,27 @@ impl CompileJob {
|
||||
== Target::Shipouts
|
||||
{
|
||||
use texrra_tex_core::execution::Event;
|
||||
let relocated_suffix = prior_layout.as_ref().and_then(|prior| {
|
||||
reused_layouts.as_ref()
|
||||
.filter(|reused| Arc::ptr_eq(&prior.execution, &reused.donor))
|
||||
.map(|reused| &reused.suffix)
|
||||
});
|
||||
let mut old = prior_layout.as_deref().into_iter().flat_map(|prior| {
|
||||
prior.execution.execution.events.iter().filter_map(|event| {
|
||||
if let Event::Shipout(page) = event { Some(page.as_ref()) } else { None }
|
||||
}).zip(&prior.shipout_layouts)
|
||||
});
|
||||
}).enumerate();
|
||||
let pages = e.shipout_display_lists_with(|page| {
|
||||
if let Some((_, layout)) =
|
||||
old.next().filter(|(prior, _)| page.shares_local_layout_with(prior))
|
||||
{
|
||||
let reused = old.next().and_then(|(index, (prior, layout))| {
|
||||
relocated_suffix
|
||||
.and_then(|suffix| suffix.relocate_layout(index, layout))
|
||||
.map(Arc::new)
|
||||
.or_else(|| page.shares_local_layout_with(prior).then(|| layout.clone()))
|
||||
});
|
||||
if let Some(layout) = reused {
|
||||
shipout_layout_work.reused_pages += 1;
|
||||
shipout_layouts.push(layout.clone());
|
||||
return Ok((**layout).clone());
|
||||
return Ok((*layout).clone());
|
||||
}
|
||||
let layout = page.display_list()?;
|
||||
shipout_layout_work.lowered_pages += 1;
|
||||
|
||||
+205
-46
@@ -7,9 +7,10 @@ use std::{
|
||||
collections::{BTreeMap, BTreeSet, VecDeque},
|
||||
ffi::OsString,
|
||||
path::Path,
|
||||
time::Instant,
|
||||
};
|
||||
use texrra_tex_core::{
|
||||
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint},
|
||||
execution::{CheckpointDecision, CheckpointSource, EntryCheckpoint, Event, RelocatedShipoutSuffix, StatisticsPhase, StatisticsReport},
|
||||
resources::{ResourceKind, ResourceLookup, ResourceReadRange},
|
||||
};
|
||||
#[cfg(test)]
|
||||
@@ -71,6 +72,9 @@ pub(super) struct CheckpointSet {
|
||||
entries: Vec<Arc<CachedCheckpoint>>,
|
||||
calls: Arc<[Call]>,
|
||||
completion: Option<Arc<CompletedExecution>>,
|
||||
// An earlier run can still supply boundaries beyond the point where this
|
||||
// run stopped executing. Its checkpoints remain comparison inputs only.
|
||||
suffix_base: Option<Arc<CompletedExecution>>,
|
||||
refresh_on_resume: bool,
|
||||
edit_frontier: Option<usize>,
|
||||
}
|
||||
@@ -80,12 +84,26 @@ pub(super) struct SelectedCheckpoint {
|
||||
candidate: ExecutionCandidate,
|
||||
}
|
||||
|
||||
pub(super) struct ReusedShipoutLayouts {
|
||||
pub(super) donor: Arc<RevisionExecution>,
|
||||
pub(super) suffix: RelocatedShipoutSuffix,
|
||||
}
|
||||
|
||||
enum ExecutionCandidate {
|
||||
Boundary(usize),
|
||||
Completed(Arc<CompletedExecution>),
|
||||
}
|
||||
|
||||
const SOURCE_INTERVALS: usize = 4;
|
||||
const DENSE_SETTLED_PAGES: usize = 4;
|
||||
const SPARSE_SETTLED_SLOTS: usize = 4;
|
||||
|
||||
fn settled_page_stride(page: usize) -> usize {
|
||||
page.saturating_sub(DENSE_SETTLED_PAGES)
|
||||
.div_ceil(SPARSE_SETTLED_SLOTS)
|
||||
.max(1)
|
||||
.next_power_of_two()
|
||||
}
|
||||
|
||||
// Each interval can keep an early command boundary and a more advanced
|
||||
// boundary after actual shipout. Larger jobs sample pages at wider intervals.
|
||||
@@ -189,11 +207,13 @@ impl CaptureSchedule {
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.fixed_frontier.is_none() && source.output_returned
|
||||
&& pages > self.settled_page && pages <= 8
|
||||
{
|
||||
if self.fixed_frontier.is_none() && source.output_returned && pages > self.settled_page {
|
||||
self.settled_page = pages;
|
||||
return Some(Capture::Settled { page: pages, regular });
|
||||
// A wider grid is a subset of the earlier grid, so a new run
|
||||
// still visits any checkpoint retained by a completed run.
|
||||
if pages.saturating_sub(DENSE_SETTLED_PAGES) % settled_page_stride(pages) == 0 {
|
||||
return Some(Capture::Settled { page: pages, regular });
|
||||
}
|
||||
}
|
||||
regular.map(Capture::Entry).or(line_end)
|
||||
}
|
||||
@@ -328,6 +348,10 @@ impl<'a> CapturedEntries<'a> {
|
||||
let slots = match slots {
|
||||
Capture::Settled { page, regular } => {
|
||||
if let Some((_, calls)) = host.prefix() {
|
||||
let stride = settled_page_stride(page);
|
||||
self.settled.retain(|&old, _| {
|
||||
old.saturating_sub(DENSE_SETTLED_PAGES) % stride == 0
|
||||
});
|
||||
self.settled.insert(page, SettledCheckpoint {
|
||||
entry: entry.clone(),
|
||||
host: host.files().replay_boundary(),
|
||||
@@ -386,11 +410,70 @@ impl<'a> CapturedEntries<'a> {
|
||||
self.changed = true;
|
||||
}
|
||||
|
||||
fn replay_settled_suffix(
|
||||
&mut self,
|
||||
page: usize,
|
||||
current: &EntryCheckpoint,
|
||||
prior: &SettledCheckpoint,
|
||||
completed: &CompletedExecution,
|
||||
end_statistics: Option<&StatisticsReport>,
|
||||
host: &mut RecordingHost,
|
||||
cancellation: &Cancellation,
|
||||
) -> Result<(), String> {
|
||||
let project = self.request.project.as_deref().expect("settled replay uses a project");
|
||||
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 stride = bytes.div_ceil(SOURCE_INTERVALS).max(1);
|
||||
let mut later = [const { None }; SOURCE_INTERVALS];
|
||||
// Untranslated live continuations and their source intervals still
|
||||
// refer to the old entry when its length changed.
|
||||
if previous_bytes == bytes
|
||||
&& 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;
|
||||
if later[interval].is_some() {
|
||||
continue;
|
||||
}
|
||||
check(cancellation).map_err(|error| error.to_string())?;
|
||||
if let Some(entry) = rebase(&anchor.entry) {
|
||||
later[interval] = Some((page, anchor, entry));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut replayed = prior.call_count;
|
||||
for (interval, (page, anchor, entry)) in later.into_iter().enumerate()
|
||||
.filter_map(|(interval, anchor)| anchor.map(|anchor| (interval, anchor)))
|
||||
{
|
||||
let Some(calls) = completed.calls.get(replayed..anchor.call_count) else {
|
||||
continue;
|
||||
};
|
||||
host.replay_suffix(calls, end_statistics, cancellation)?;
|
||||
replayed = anchor.call_count;
|
||||
if anchor.host == host.files().replay_boundary() {
|
||||
let regular = CaptureSlots {
|
||||
interval,
|
||||
early: false,
|
||||
page: true,
|
||||
edit: false,
|
||||
next_page: page.saturating_add(1),
|
||||
};
|
||||
self.capture(Capture::Settled { page, regular: Some(regular) }, Arc::new(entry), host);
|
||||
}
|
||||
}
|
||||
host.replay_suffix(&completed.calls[replayed..], end_statistics, cancellation)?;
|
||||
completed.guard.verify_replayed_inputs(host.files(), project).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn finish(
|
||||
self,
|
||||
recording: RecordingHost,
|
||||
refresh_on_resume: bool,
|
||||
result: &Arc<RevisionExecution>,
|
||||
suffix_base: Option<Arc<CompletedExecution>>,
|
||||
) -> Option<Arc<CheckpointSet>> {
|
||||
if !self.changed {
|
||||
return None;
|
||||
@@ -455,6 +538,7 @@ impl<'a> CapturedEntries<'a> {
|
||||
entries,
|
||||
calls,
|
||||
completion,
|
||||
suffix_base,
|
||||
refresh_on_resume,
|
||||
edit_frontier,
|
||||
}))
|
||||
@@ -562,7 +646,7 @@ impl CheckpointCache {
|
||||
|slots, entry, host| captures.capture(slots, Arc::new(entry), host),
|
||||
);
|
||||
let next = result.as_ref().ok().and_then(|result| {
|
||||
captures.finish(recording, self.minimum_frontier.is_none(), result)
|
||||
captures.finish(recording, self.minimum_frontier.is_none(), result, None)
|
||||
});
|
||||
(result, next)
|
||||
}
|
||||
@@ -629,23 +713,30 @@ impl PublishedCheckpoints {
|
||||
cancellation,
|
||||
&mut attempt,
|
||||
Some(Box::new(|world, preparation| {
|
||||
let mut rejection = None;
|
||||
let remaining = std::iter::from_fn(|| candidates.pop_front());
|
||||
for candidate in std::iter::once(first).chain(remaining) {
|
||||
match candidate
|
||||
// Only the first candidate passed the immutable project
|
||||
// and entry-prefix checks before arriving at this host.
|
||||
let guard = first.guard();
|
||||
let rejection = match guard
|
||||
.verify_clock_environment()
|
||||
.and_then(|()| guard.verify_host(project, world, preparation))
|
||||
{
|
||||
Ok(()) => {
|
||||
selected = Some(first);
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) => error,
|
||||
};
|
||||
for candidate in std::iter::from_fn(|| candidates.pop_front()) {
|
||||
if candidate
|
||||
.accept_entry(project)
|
||||
.and_then(|()| candidate.guard().verify(request, world, preparation))
|
||||
.is_ok()
|
||||
{
|
||||
Ok(()) => {
|
||||
selected = Some(candidate);
|
||||
return Ok(());
|
||||
}
|
||||
Err(error) => {
|
||||
rejection.get_or_insert(error);
|
||||
}
|
||||
selected = Some(candidate);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(rejection.unwrap_or_else(|| "no entry checkpoint retained".into()))
|
||||
Err(rejection)
|
||||
})),
|
||||
EffectMode::Draft,
|
||||
KernelPreparation::Resume,
|
||||
@@ -695,6 +786,7 @@ impl CheckpointSet {
|
||||
entries,
|
||||
calls: Arc::from(&self.calls[..replay_count]),
|
||||
completion: None,
|
||||
suffix_base: None,
|
||||
refresh_on_resume: self.refresh_on_resume,
|
||||
edit_frontier: self.edit_frontier,
|
||||
}))
|
||||
@@ -792,6 +884,7 @@ impl SelectedCheckpoint {
|
||||
(
|
||||
Result<Arc<RevisionExecution>, RevisionFailure>,
|
||||
Arc<CheckpointSet>,
|
||||
Option<ReusedShipoutLayouts>,
|
||||
),
|
||||
CompileError,
|
||||
> {
|
||||
@@ -803,7 +896,11 @@ impl SelectedCheckpoint {
|
||||
work.reused_steps = completed.result.execution.steps;
|
||||
work.reused_completion = true;
|
||||
work.replayed_calls = completed.calls.len();
|
||||
return Ok((job.reuse_completed_after_host_replay(&completed.result, files), self.set));
|
||||
return Ok((
|
||||
job.reuse_completed_after_host_replay(&completed.result, files),
|
||||
self.set,
|
||||
None,
|
||||
));
|
||||
}
|
||||
};
|
||||
let checkpoint = &self.set.entries[index];
|
||||
@@ -818,7 +915,7 @@ impl SelectedCheckpoint {
|
||||
let result = job
|
||||
.resume_entry_after_host_replay(&checkpoint.entry, source, files)
|
||||
.ok_or_else(changed_prefix)?;
|
||||
return Ok((result, self.set));
|
||||
return Ok((result, self.set, None));
|
||||
}
|
||||
|
||||
let previous = checkpoint
|
||||
@@ -861,7 +958,12 @@ impl SelectedCheckpoint {
|
||||
);
|
||||
let cwd = &request.world.cwd;
|
||||
let cancellation = job.cancellation();
|
||||
let completed = if allow_suffix { self.set.completion.as_deref() } else { None };
|
||||
let suffixes = self.set.completion.iter().chain(&self.set.suffix_base);
|
||||
let mut suffix_base = None;
|
||||
let mut reused_layouts = None;
|
||||
let mut timings = CheckpointTimings::default();
|
||||
let timed = request.observer.is_some();
|
||||
let resume_started = timed.then(Instant::now);
|
||||
let result = job
|
||||
.resume_deciding_suffix(
|
||||
&checkpoint.entry,
|
||||
@@ -885,57 +987,101 @@ impl SelectedCheckpoint {
|
||||
},
|
||||
|slots, entry, host| {
|
||||
let entry = Arc::new(entry);
|
||||
captures.capture(slots, entry.clone(), host);
|
||||
measure(&mut timings.capture, timed, || {
|
||||
captures.capture(slots, entry.clone(), host);
|
||||
});
|
||||
let Capture::Settled { page, .. } = slots else {
|
||||
return CheckpointDecision::Continue;
|
||||
};
|
||||
let Some((completed, old)) =
|
||||
completed.and_then(|job| job.settled.get(&page).map(|old| (job, old)))
|
||||
else {
|
||||
let Some(new) = captures.settled.get(&page).filter(|_| allow_suffix) else {
|
||||
return CheckpointDecision::Continue;
|
||||
};
|
||||
let Some(new) = captures.settled.get(&page) else {
|
||||
return CheckpointDecision::Continue;
|
||||
};
|
||||
if old.call_count != new.call_count || old.host != new.host
|
||||
|| !can_replay_completed_suffix(completed, request, host.files())
|
||||
{
|
||||
return CheckpointDecision::Continue;
|
||||
}
|
||||
let Some(execution) = entry.splice_settled_suffix(&old.entry, &completed.result.execution)
|
||||
else {
|
||||
let Some((completed, old, execution, layout)) = suffixes.clone().find_map(|completed| {
|
||||
let old = completed.settled.get(&page)?;
|
||||
let host_matches = measure(&mut timings.suffix_host_validation, timed, || {
|
||||
old.call_count == new.call_count
|
||||
&& new.host.matches_for_suffix(&old.host)
|
||||
&& can_replay_completed_suffix(completed, request, host.files())
|
||||
});
|
||||
if !host_matches {
|
||||
return None;
|
||||
}
|
||||
let kernel_timings = timed.then_some(&mut timings.suffix_kernel);
|
||||
let (execution, layout) = measure(&mut timings.suffix_kernel_validation, timed, || {
|
||||
entry.splice_settled_suffix_observed(
|
||||
&old.entry, &completed.result.execution, kernel_timings,
|
||||
)
|
||||
})?;
|
||||
Some((completed, old, execution, layout))
|
||||
}) else {
|
||||
return CheckpointDecision::Continue;
|
||||
};
|
||||
let calls = &completed.calls[old.call_count..];
|
||||
let replayed = host.replay_suffix(calls, &cancellation)
|
||||
.and_then(|()| completed.guard.verify_replayed_inputs(
|
||||
host.files(), request.project.as_deref().expect("settled replay uses a project"),
|
||||
).map_err(|error| error.to_string()));
|
||||
let end_statistics = execution.events.last().and_then(|event| match event {
|
||||
Event::Statistics(report) if matches!(report.phase, StatisticsPhase::End { .. }) =>
|
||||
Some(report.as_ref()),
|
||||
_ => None,
|
||||
});
|
||||
let replayed = measure(&mut timings.suffix_host_replay, timed, || {
|
||||
captures.replay_settled_suffix(
|
||||
page, &entry, old, completed, end_statistics, host, &cancellation,
|
||||
)
|
||||
});
|
||||
if let Err(error) = replayed {
|
||||
let discarded = entry.completed_steps().saturating_sub(work.reused_steps);
|
||||
*suffix_failure = Some((error.clone(), discarded));
|
||||
return CheckpointDecision::ReplayFailed(error);
|
||||
}
|
||||
// Keep a single comparison run with the furthest recorded
|
||||
// boundary. Do not chain older completed runs.
|
||||
suffix_base = suffixes.clone()
|
||||
.max_by_key(|candidate| {
|
||||
(candidate.settled.keys().next_back().copied(), Arc::ptr_eq(candidate, completed))
|
||||
})
|
||||
.cloned();
|
||||
work.reused_suffix_steps = execution.steps - entry.completed_steps();
|
||||
work.reused_steps += work.reused_suffix_steps;
|
||||
work.replayed_calls += calls.len();
|
||||
reused_layouts = layout.map(|suffix| ReusedShipoutLayouts {
|
||||
donor: Arc::clone(&completed.result),
|
||||
suffix,
|
||||
});
|
||||
CheckpointDecision::Reuse(Box::new(execution))
|
||||
},
|
||||
)
|
||||
.map_err(CompileError::Host)?
|
||||
.ok_or_else(changed_prefix)?;
|
||||
let next = result.as_ref().ok().and_then(|result| {
|
||||
captures.finish(recording, true, result)
|
||||
if let Some(started) = resume_started {
|
||||
timings.resume = started.elapsed();
|
||||
}
|
||||
let next = measure(&mut timings.retain, timed, || {
|
||||
result.as_ref().ok().and_then(|result| captures.finish(recording, true, result, suffix_base))
|
||||
});
|
||||
if result.is_ok() {
|
||||
if let Some(observer) = &request.observer {
|
||||
observer.checkpoint_timings(job.revision(), timings);
|
||||
}
|
||||
} else {
|
||||
reused_layouts = None;
|
||||
}
|
||||
if let Some(next) = next {
|
||||
next.report_capture(work);
|
||||
Ok((result, next))
|
||||
Ok((result, next, reused_layouts))
|
||||
} else {
|
||||
Ok((result, self.set))
|
||||
Ok((result, self.set, reused_layouts))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn measure<T>(elapsed: &mut Duration, enabled: bool, action: impl FnOnce() -> T) -> T {
|
||||
let started = enabled.then(Instant::now);
|
||||
let value = action();
|
||||
if let Some(started) = started {
|
||||
*elapsed += started.elapsed();
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
fn can_replay_completed_suffix(
|
||||
completed: &CompletedExecution,
|
||||
request: &CompileRequest,
|
||||
@@ -1223,6 +1369,11 @@ impl PrefixInputGuard {
|
||||
));
|
||||
}
|
||||
}
|
||||
self.verify_clock_environment()?;
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
fn verify_clock_environment(&self) -> Result<(), String> {
|
||||
if self
|
||||
.clock_environment
|
||||
.as_ref()
|
||||
@@ -1230,7 +1381,7 @@ impl PrefixInputGuard {
|
||||
{
|
||||
return Err("checkpoint file-date environment changed".into());
|
||||
}
|
||||
Ok(current)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_replayed_inputs(&self, files: &Files, current: &ProjectSnapshot) -> Result<(), CompileError> {
|
||||
@@ -1262,11 +1413,19 @@ impl PrefixInputGuard {
|
||||
world: &FileWorld,
|
||||
preparation: &HostPreparation,
|
||||
) -> Result<(), String> {
|
||||
let current = self.verify_project(request)?;
|
||||
self.verify_host(self.verify_project(request)?, world, preparation)
|
||||
}
|
||||
|
||||
fn verify_host(
|
||||
&self,
|
||||
project: &ProjectSnapshot,
|
||||
world: &FileWorld,
|
||||
preparation: &HostPreparation,
|
||||
) -> Result<(), String> {
|
||||
if self.format_input_bindings != world.trace().format_input_bindings {
|
||||
return Err("checkpoint format input bindings changed".into());
|
||||
}
|
||||
if world.trace().reads.first() != current.file(&self.entry).map(|file| &file.version) {
|
||||
if world.trace().reads.first() != project.file(&self.entry).map(|file| &file.version) {
|
||||
return Err("checkpoint entry resolved to a different path".into());
|
||||
}
|
||||
let current = preparation
|
||||
|
||||
@@ -6,7 +6,7 @@ use std::fs;
|
||||
#[cfg(test)]
|
||||
use texrra_tex_core::source_map::SourceMap;
|
||||
use texrra_tex_core::{
|
||||
execution::{Error, HostResourceUsage, WriteDestination},
|
||||
execution::{Error, HostResourceUsage, StatisticsPhase, StatisticsReport, WriteDestination},
|
||||
resources::{LoadedResource, ResourceKind, ResourceVersion},
|
||||
};
|
||||
|
||||
@@ -16,6 +16,8 @@ pub(super) enum Call {
|
||||
Checked(Arc<CheckedCall>),
|
||||
ReadSource(Arc<SourceRead>),
|
||||
FileSize(Arc<SizeRead>),
|
||||
EndStatistics(Arc<StatisticsReport>),
|
||||
ResourceUsage(Arc<ResourceUsageRead>),
|
||||
}
|
||||
|
||||
pub(super) struct SourceRead {
|
||||
@@ -31,6 +33,11 @@ pub(super) struct SizeRead {
|
||||
read: Option<ResourceVersion>,
|
||||
}
|
||||
|
||||
pub(super) struct ResourceUsageRead {
|
||||
observed: Option<HostResourceUsage>,
|
||||
entry_bytes: Option<u64>,
|
||||
}
|
||||
|
||||
pub(super) struct RebindableSourceObservations {
|
||||
pub(super) size: Option<u64>,
|
||||
}
|
||||
@@ -45,6 +52,23 @@ impl Call {
|
||||
pub(super) fn replay(&self, files: &mut Files, partial_source: Option<&ResourceVersion>) -> Result<(), String> {
|
||||
match self {
|
||||
Self::Checked(call) => call(files),
|
||||
Self::EndStatistics(report) => files.observe_statistics(report),
|
||||
Self::ResourceUsage(read) => {
|
||||
let mut expected = read.observed.clone();
|
||||
if let (Some(usage), Some(previous), Some(current)) =
|
||||
(&mut expected, read.entry_bytes, files.replayed_entry_bytes())
|
||||
{
|
||||
// The first read was the verified entry. All other
|
||||
// resource and stream observations are still exact.
|
||||
usage.rebind_entry_bytes(previous, current)
|
||||
.ok_or("invalid replayed entry resource usage")?;
|
||||
}
|
||||
let actual = files.resource_usage()?;
|
||||
if actual != expected {
|
||||
return Err(format!("resource usage changed: expected {expected:?}, observed {actual:?}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::FileSize(read) => {
|
||||
let before = files.resource_trace().reads.len();
|
||||
let observed = files.file_size(&read.name, &read.from);
|
||||
@@ -150,16 +174,33 @@ impl<'a> RecordingHost<'a> {
|
||||
self.files
|
||||
}
|
||||
|
||||
pub(super) fn replay_suffix(&mut self, calls: &[Call], cancellation: &Cancellation) -> Result<(), String> {
|
||||
pub(super) fn replay_suffix(
|
||||
&mut self,
|
||||
calls: &[Call],
|
||||
end_statistics: Option<&StatisticsReport>,
|
||||
cancellation: &Cancellation,
|
||||
) -> Result<(), String> {
|
||||
let recorded = self.calls.as_mut().ok_or("host calls are unavailable")?;
|
||||
if recorded.len() + calls.len() >= MAX_REPLAY_CALLS {
|
||||
return Err("completed suffix exceeds the host recording budget".into());
|
||||
}
|
||||
for call in calls {
|
||||
check(cancellation).map_err(|error| error.to_string())?;
|
||||
let call = match call {
|
||||
Call::EndStatistics(report) => {
|
||||
// The kernel has already checked and translated this report.
|
||||
let translated = end_statistics.ok_or("completed suffix is missing its final statistics")?;
|
||||
if report.as_ref() == translated {
|
||||
call.clone()
|
||||
} else {
|
||||
Call::EndStatistics(Arc::new(translated.clone()))
|
||||
}
|
||||
}
|
||||
call => call.clone(),
|
||||
};
|
||||
call.replay(self.files, None)?;
|
||||
recorded.push(call);
|
||||
}
|
||||
recorded.extend_from_slice(calls);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -225,8 +266,18 @@ impl SourceProvider for RecordingHost<'_> {
|
||||
fn set_interaction_mode(&mut self, mode: u8) -> Result<(), String> {
|
||||
call!(self, set_interaction_mode(mode))
|
||||
}
|
||||
fn replayed_entry_bytes(&self) -> Option<u64> {
|
||||
self.files.replayed_entry_bytes()
|
||||
}
|
||||
fn resource_usage(&mut self) -> Result<Option<HostResourceUsage>, String> {
|
||||
call!(self, resource_usage())
|
||||
let observed = self.files.resource_usage()?;
|
||||
if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS {
|
||||
calls.push(Call::ResourceUsage(Arc::new(ResourceUsageRead {
|
||||
observed: observed.clone(),
|
||||
entry_bytes: self.files.replayed_entry_bytes(),
|
||||
})));
|
||||
}
|
||||
Ok(observed)
|
||||
}
|
||||
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String> {
|
||||
let result = self.files.read_versioned_source(name, from);
|
||||
@@ -384,6 +435,17 @@ impl SourceProvider for RecordingHost<'_> {
|
||||
let text = text.to_owned();
|
||||
call!(self, observe_diagnostic(destination, &text))
|
||||
}
|
||||
fn observe_statistics(&mut self, report: &StatisticsReport) -> Result<(), String> {
|
||||
// Shipout reports do not write the step count in their transcript.
|
||||
if !matches!(&report.phase, StatisticsPhase::End { .. }) {
|
||||
return self.observe_diagnostic(report.destination, &report.text);
|
||||
}
|
||||
self.files.observe_statistics(report)?;
|
||||
if let Some(calls) = &mut self.calls && calls.len() < MAX_REPLAY_CALLS {
|
||||
calls.push(Call::EndStatistics(Arc::new(report.clone())));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn observe_inline_diagnostic(
|
||||
&mut self,
|
||||
destination: WriteDestination,
|
||||
|
||||
+27
-6
@@ -159,6 +159,20 @@ struct DraftLedger {
|
||||
|
||||
#[derive(PartialEq, Eq)]
|
||||
pub(super) struct ReplayBoundary {
|
||||
entry_bytes: Option<u64>,
|
||||
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<u8>)>,
|
||||
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 {
|
||||
@@ -1634,6 +1651,10 @@ impl SourceProvider for Files {
|
||||
Some(self.world.trace())
|
||||
}
|
||||
|
||||
fn replayed_entry_bytes(&self) -> Option<u64> {
|
||||
self.world.trace().reads.first().map(|read| read.bytes)
|
||||
}
|
||||
|
||||
fn resource_usage(
|
||||
&mut self,
|
||||
) -> Result<Option<texrra_tex_core::execution::HostResourceUsage>, String> {
|
||||
|
||||
+13
-2
@@ -13,11 +13,14 @@ const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
|
||||
const ZIP64_MESSAGE: &str =
|
||||
"ZIP64 archives are not supported; re-create the archive without ZIP64 extensions";
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub(super) struct ProjectFile {
|
||||
pub(super) path: String,
|
||||
pub(super) size: u64,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(super) struct ProjectInfo {
|
||||
pub(super) id: String,
|
||||
pub(super) name: String,
|
||||
@@ -629,6 +632,7 @@ fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
}
|
||||
let mut entries = Vec::new();
|
||||
let mut cursor = cd_offset;
|
||||
let mut expanded = 0u64;
|
||||
for _ in 0..count {
|
||||
if read_u32(cursor)? != 0x0201_4b50 {
|
||||
return Err("corrupt zip central directory".to_string());
|
||||
@@ -653,6 +657,13 @@ fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
if flags & 0x0001 != 0 {
|
||||
return Err("encrypted zip entries are not supported".to_string());
|
||||
}
|
||||
expanded += uncompressed_size as u64;
|
||||
if uncompressed_size as u64 > MAX_FILE_BYTES
|
||||
|| expanded > MAX_PROJECT_BYTES
|
||||
|| entries.len() >= MAX_PROJECT_FILES
|
||||
{
|
||||
return Err(format!("ZIP entry exceeds project limits: {name}"));
|
||||
}
|
||||
if read_u32(local_offset)? != 0x0403_4b50 {
|
||||
return Err("corrupt zip local header".to_string());
|
||||
}
|
||||
@@ -665,9 +676,9 @@ fn read_zip(bytes: &[u8]) -> Result<Vec<(String, Vec<u8>)>, String> {
|
||||
let content = match method {
|
||||
0 => data.to_vec(),
|
||||
8 => {
|
||||
let mut decoder = DeflateDecoder::new(data);
|
||||
let mut output = Vec::new();
|
||||
decoder
|
||||
DeflateDecoder::new(data)
|
||||
.take(uncompressed_size as u64 + 1)
|
||||
.read_to_end(&mut output)
|
||||
.map_err(|error| format!("could not inflate `{name}`: {error}"))?;
|
||||
output
|
||||
|
||||
+745
-5
@@ -15,7 +15,7 @@ use std::{
|
||||
use texrra_engine::native::*;
|
||||
use texrra_tex_core::{
|
||||
artifacts::file_version,
|
||||
execution::{Cancellation, JobTime},
|
||||
execution::{Cancellation, InputProfile, JobTime},
|
||||
resources::{FileWorld, GeneratedLookupOrigin, ResourceKind, SearchPath, WorldConfig},
|
||||
};
|
||||
const HEADER: &str = r"\catcode123=1\catcode125=2\catcode35=6\font\f=cmr10\f ";
|
||||
@@ -444,6 +444,10 @@ fn paragraph_search_reuse_keeps_current_paint_sources_writes_and_layout() {
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
fn atomic_definition(p: &Path, revision: u64, body: &str) -> ProjectDefinition {
|
||||
atomic_definition_with_source(p, revision, format!("{HEADER}{body}").into_bytes())
|
||||
}
|
||||
|
||||
fn atomic_definition_with_source(p: &Path, revision: u64, source: Vec<u8>) -> ProjectDefinition {
|
||||
let mut configuration = request(p).world;
|
||||
let map = match &configuration.paths[&ResourceKind::Map][0] {
|
||||
SearchPath::Directory { path, .. } => path.join("pdftex.map"),
|
||||
@@ -451,10 +455,7 @@ fn atomic_definition(p: &Path, revision: u64, body: &str) -> ProjectDefinition {
|
||||
};
|
||||
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let mut files = std::collections::BTreeMap::new();
|
||||
files.insert(
|
||||
p.join("main.tex"),
|
||||
Arc::from(format!("{HEADER}{body}").into_bytes()),
|
||||
);
|
||||
files.insert(p.join("main.tex"), Arc::from(source));
|
||||
for font in ["cmr10", "cmr7"] {
|
||||
for (relative, actual) in [
|
||||
(
|
||||
@@ -1649,6 +1650,745 @@ fn checkpoint_tracks_consumed_stream_bytes_and_eof_across_page_edits() {
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consecutive_edits_reuse_later_settled_suffixes() {
|
||||
let cwd = directory("consecutive-settled-suffixes");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |second, third| format!(r"
|
||||
\tracingstats=1
|
||||
\shipout\hbox{{Cover ABCXYZ}}
|
||||
\setbox3=\hbox{{{second}}}
|
||||
\shipout\box3
|
||||
\relax
|
||||
\setbox3=\hbox{{{third}}}
|
||||
\shipout\box3
|
||||
\relax
|
||||
\shipout\hbox{{Unchanged}}
|
||||
\end
|
||||
");
|
||||
let mut project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body('A', 'X'))).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, second, third, expected_page) in [
|
||||
(2, 'B', 'X', 1),
|
||||
(3, 'C', 'X', 1),
|
||||
(4, 'C', 'Y', 2),
|
||||
] {
|
||||
let source = format!("{HEADER}{}", body(second, third));
|
||||
project = project
|
||||
.with_file_edits(revision, [(entry.clone(), Arc::from(source.into_bytes()))].into())
|
||||
.unwrap();
|
||||
let input = request.clone().with_project(project.clone());
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(work.reused_suffix_steps > 0, "revision {revision}: {work:?}");
|
||||
let preview = updated.preview_since(Some(previous.revision())).unwrap();
|
||||
let changed: Vec<_> = preview.pages.iter().map(|page| page.index).collect();
|
||||
assert_eq!(changed, [expected_page]);
|
||||
|
||||
let full = NativeCompiler::default().compile(input).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.source_map.sources, full.source_map.sources);
|
||||
assert_eq!(updated.source_map.pages, full.source_map.pages);
|
||||
previous = updated;
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_suffix_carries_a_verified_prefix_into_later_edits() {
|
||||
let cwd = directory("long-settled-suffix");
|
||||
let entry = cwd.join("main.tex");
|
||||
let middle = "\\shipout\\hbox{\\copy7 Middle}\\relax\n".repeat(6);
|
||||
let tail = "\\shipout\\hbox{Unchanged}\\relax\n".repeat(3);
|
||||
let body = |second, ninth| {
|
||||
format!(r"
|
||||
\tracingstats=1
|
||||
\shipout\hbox{{Cover ABXY}}
|
||||
\setbox3=\hbox{{{second}}}
|
||||
\setbox7=\hbox{{Shared}}
|
||||
\shipout\hbox{{\unhbox3\copy7}}
|
||||
\relax
|
||||
{middle}\setbox3=\hbox{{{ninth}}}
|
||||
\shipout\box3
|
||||
\relax
|
||||
{tail}\end
|
||||
")
|
||||
};
|
||||
let mut project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body('A', 'X'))).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, second, ninth, expected_page) in [(2, 'B', 'X', 1), (3, 'B', 'Y', 8)] {
|
||||
let source = format!("{HEADER}{}", body(second, ninth));
|
||||
let start_of_middle = source.find(&middle).unwrap();
|
||||
project = project
|
||||
.with_file_edits(revision, [(entry.clone(), Arc::from(source.into_bytes()))].into())
|
||||
.unwrap();
|
||||
let input = request.clone().with_project(project.clone());
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(work.reused_suffix_steps > 0, "{work:?}");
|
||||
if revision == 3 {
|
||||
assert!(work.reused_frontier.unwrap() > start_of_middle, "{work:?}");
|
||||
}
|
||||
|
||||
let preview = updated.preview_since(Some(previous.revision())).unwrap();
|
||||
assert_eq!(preview.page_count, 12);
|
||||
let changed: Vec<_> = preview.pages.iter().map(|page| page.index).collect();
|
||||
assert_eq!(changed, [expected_page]);
|
||||
|
||||
let full = NativeCompiler::default().compile(input).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.source_map.pages, full.source_map.pages);
|
||||
assert_eq!(updated.source_map.sources, full.source_map.sources);
|
||||
assert_eq!(updated.preview_since(None).unwrap().pages, full.preview_since(None).unwrap().pages);
|
||||
previous = updated;
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_suffix_keeps_new_prefix_reads_but_rejects_missing_reads() {
|
||||
use texrra_tex_core::execution::Dependency;
|
||||
|
||||
let cwd = directory("settled-prefix-dependencies");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |ignored| format!(r"
|
||||
\catcode64=9 \catcode63=9
|
||||
?\relax
|
||||
\shipout\hbox{{Cover}}\relax
|
||||
{ignored}\relax
|
||||
\shipout\hbox{{Checkpoint}}\relax
|
||||
\shipout\hbox{{Suffix}}\relax
|
||||
\endinput\shipout\hbox{{Final}}\relax\end
|
||||
");
|
||||
for (before, after, reuse) in [('?', '@', true), ('@', '?', false)] {
|
||||
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before))).unwrap();
|
||||
let mut request = request(&cwd).observe_generated_initial();
|
||||
request.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let donor = session.compile(request.clone().with_project(project.clone())).unwrap();
|
||||
let new_read = Dependency::CatCode('@');
|
||||
assert_eq!(donor.execution.execution.reads.contains(&new_read), before == '@');
|
||||
let source = format!("{HEADER}{}", body(after));
|
||||
let project = project.with_file_edits(
|
||||
2, [(entry.clone(), Arc::from(source.into_bytes()))].into(),
|
||||
).unwrap();
|
||||
let input = request.with_project(project);
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(!work.reused_completion, "{work:?}");
|
||||
assert_eq!(work.reused_suffix_steps > 0, reuse, "{work:?}");
|
||||
assert_eq!(updated.execution.execution.reads.contains(&new_read), after == '@');
|
||||
let log = fs::read(cwd.join("job.log")).unwrap();
|
||||
let full = NativeCompiler::default().compile(input).unwrap();
|
||||
assert_eq!(updated.execution.execution, full.execution.execution);
|
||||
assert_eq!(updated.pdf, full.pdf);
|
||||
assert_eq!(updated.source_map.pages, full.source_map.pages);
|
||||
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_suffix_translates_cumulative_box_charges_in_both_directions() {
|
||||
use texrra_tex_core::execution::{Event, StatisticsPhase};
|
||||
|
||||
let cwd = directory("settled-box-charge");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |variant| format!(r"
|
||||
\tracingstats=2
|
||||
\setbox0=\vbox{{\kern1sp\kern2sp}}
|
||||
\def\variantA{{\relax}}
|
||||
\def\variantB{{\setbox7=\copy0\setbox7=\box9\relax}}
|
||||
\variantA\variantB\relax
|
||||
\shipout\hbox{{Cover}}\relax
|
||||
\variant{variant}\relax
|
||||
\shipout\hbox{{Checkpoint}}\relax
|
||||
\shipout\hbox{{Suffix}}\relax
|
||||
\endinput\shipout\hbox{{Final}}\relax\end
|
||||
");
|
||||
let final_charge = |document: &CompiledDocument| {
|
||||
let Some(Event::Statistics(report)) = document.execution.execution.events.last() else {
|
||||
panic!("missing final resource report");
|
||||
};
|
||||
let StatisticsPhase::End { usage, .. } = &report.phase else {
|
||||
panic!("expected final resource report");
|
||||
};
|
||||
usage.box_nodes_created
|
||||
};
|
||||
|
||||
for (before, after) in [('A', 'B'), ('B', 'A')] {
|
||||
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(before))).unwrap();
|
||||
let mut request = request(&cwd).observe_generated_initial();
|
||||
request.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let donor = session.compile(request.clone().with_project(project.clone())).unwrap();
|
||||
let source = format!("{HEADER}{}", body(after));
|
||||
let project = project.with_file_edits(
|
||||
2, [(entry.clone(), Arc::from(source.into_bytes()))].into(),
|
||||
).unwrap();
|
||||
let input = request.with_project(project);
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(!work.reused_completion && work.reused_suffix_steps > 0, "{work:?}");
|
||||
if after == 'B' {
|
||||
assert!(final_charge(&updated) > final_charge(&donor));
|
||||
} else {
|
||||
assert!(final_charge(&updated) < final_charge(&donor));
|
||||
}
|
||||
let log = fs::read(cwd.join("job.log")).unwrap();
|
||||
let full = NativeCompiler::default().compile(input).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!(log, fs::read(cwd.join("job.log")).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_entry_prefix_reuses_verified_statistics() {
|
||||
let cwd = directory("resized-entry-statistics");
|
||||
let entry = cwd.join("main.tex");
|
||||
let stable = r"
|
||||
\tracingstats=2
|
||||
\shipout\hbox{Cover}\relax
|
||||
\shipout\hbox{Second}\relax
|
||||
\shipout\hbox{Third}\relax
|
||||
";
|
||||
let body = |text| format!(r"{stable}
|
||||
\shipout\hbox{{{text}}}\relax
|
||||
\shipout\hbox{{Last}}\relax
|
||||
\end
|
||||
");
|
||||
let mut project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body("Late"))).unwrap();
|
||||
let mut request = request(&cwd).observe_generated_initial();
|
||||
request.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
session.compile(request.clone().with_project(project.clone())).unwrap();
|
||||
|
||||
for (revision, text) in [(2, "Later"), (3, "Now")] {
|
||||
let source = format!("{HEADER}{}", body(text));
|
||||
let after_first_shipout = source.find(r"\shipout\hbox{Second}").unwrap();
|
||||
project = project
|
||||
.with_file_edits(revision, [(entry.clone(), Arc::from(source.into_bytes()))].into())
|
||||
.unwrap();
|
||||
let input = request.clone().with_project(project.clone());
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(
|
||||
work.reused_frontier.is_some_and(|frontier| frontier >= after_first_shipout),
|
||||
"{work:?}"
|
||||
);
|
||||
assert!(work.reused_steps > 0, "{work:?}");
|
||||
|
||||
let log = fs::read(cwd.join("job.log")).unwrap();
|
||||
let full = NativeCompiler::default().compile(input).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.source_map.sources, full.source_map.sources);
|
||||
assert_eq!(updated.source_map.pages, full.source_map.pages);
|
||||
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resized_entry_prefix_invalidates_an_executed_file_size_query() {
|
||||
let cwd = directory("resized-entry-file-size");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |text| format!(r"
|
||||
\shipout\hbox{{Cover}}\relax
|
||||
\count42=\pdffilesize{{main.tex}}\relax
|
||||
\tracingstats=2
|
||||
\shipout\hbox{{\the\count42}}\relax
|
||||
\shipout\hbox{{{text}}}\relax
|
||||
\end
|
||||
");
|
||||
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body("Late"))).unwrap();
|
||||
let mut request = request(&cwd).observe_generated_initial();
|
||||
request.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let initial = session.compile(request.clone().with_project(project.clone())).unwrap();
|
||||
|
||||
let source = format!("{HEADER}{}", body("Later"));
|
||||
let query = source.find(r"\count42=").unwrap();
|
||||
let query_end = query + source[query..].find('\n').unwrap() + 1;
|
||||
assert!(initial.entry_checkpoint_work.captured_frontier.is_some_and(|frontier| frontier > query_end));
|
||||
let bytes = i32::try_from(source.len()).unwrap();
|
||||
let project = project
|
||||
.with_file_edits(2, [(entry, Arc::from(source.into_bytes()))].into())
|
||||
.unwrap();
|
||||
let request = request.with_project(project);
|
||||
let updated = session.compile(request.clone()).unwrap();
|
||||
let full = NativeCompiler::default().compile(request).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(work.reused_frontier.is_none_or(|frontier| frontier <= query_end), "{work:?}");
|
||||
assert_eq!(updated.execution.execution.state.count(42), bytes);
|
||||
assert_eq!(updated.execution.execution, full.execution.execution);
|
||||
assert_eq!(updated.resources.trace, full.resources.trace);
|
||||
assert_eq!(updated.pdf, full.pdf);
|
||||
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();
|
||||
for (revision, letter, note) in [(2, 'B', "expanded comment"), (3, 'C', "x")] {
|
||||
// Only the current document can donate the suffix in either direction.
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let previous = session.compile(request.clone().with_project(project.clone())).unwrap();
|
||||
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:?}");
|
||||
let layout = &updated.shipout_layout_work;
|
||||
if tail_query.is_empty() {
|
||||
// The cover and both pages in the accepted tail reuse local layout.
|
||||
assert!(layout.reused_pages >= 3, "{work:?} {layout:?}");
|
||||
} else {
|
||||
// Only the cover can use its original source coordinates.
|
||||
assert_eq!(layout.reused_pages, 1, "{work:?} {layout:?}");
|
||||
assert_eq!(updated.execution.execution.state.count(42), bytes);
|
||||
}
|
||||
assert_eq!(layout.lowered_pages + layout.reused_pages, 5);
|
||||
let preview = updated.preview_since(Some(previous.revision())).unwrap();
|
||||
assert_eq!(preview.pages.iter().map(|page| page.index).collect::<Vec<_>>(), [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());
|
||||
}
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_line_edits_reuse_the_settled_suffix_and_relocate_provenance() {
|
||||
check_whole_line_suffix_edits("whole-line-safe-suffix", InputProfile::TeX8Bit, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xetex_utf16_whole_line_edits_reuse_and_relocate_the_settled_suffix() {
|
||||
check_whole_line_suffix_edits("whole-line-utf16-suffix", InputProfile::XeTeX, false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whole_line_edits_reexecute_a_delayed_input_line_read_on_the_same_source() {
|
||||
check_whole_line_suffix_edits("whole-line-delayed-inputlineno", InputProfile::TeX8Bit, true);
|
||||
}
|
||||
|
||||
fn check_whole_line_suffix_edits(label: &str, profile: InputProfile, observe_delayed_line: bool) {
|
||||
let cwd = directory(label);
|
||||
let entry = cwd.join("main.tex");
|
||||
let encode = |source: &str| -> Vec<u8> {
|
||||
if profile == InputProfile::XeTeX {
|
||||
let physical_lines = source.replace('\n', "\r\n");
|
||||
[0xff, 0xfe]
|
||||
.into_iter()
|
||||
.chain(physical_lines.encode_utf16().flat_map(u16::to_le_bytes))
|
||||
.collect()
|
||||
} else {
|
||||
source.as_bytes().to_vec()
|
||||
}
|
||||
};
|
||||
let byte_offset = |source: &str, marker: &str| {
|
||||
encode(&source[..source.find(marker).unwrap()]).len()
|
||||
};
|
||||
let delayed = if observe_delayed_line {
|
||||
r"\write16{Suffix line \number\inputlineno}"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let body = |inserted| {
|
||||
format!(
|
||||
r"
|
||||
\tracingstats=2
|
||||
\count42=\inputlineno\relax
|
||||
\shipout\hbox{{Cover}}\relax% Preserve the comment catcode read before either edit.
|
||||
{inserted}\shipout\hbox{{Checkpoint}}\relax
|
||||
\gdef\saved{{Suffix glyphs}}
|
||||
\shipout\hbox{{\saved}}\relax
|
||||
\setbox5=\hbox{{Final{delayed}}}
|
||||
\endinput\shipout\box5\relax\end
|
||||
"
|
||||
)
|
||||
};
|
||||
let final_line = |body: &str| {
|
||||
body.lines()
|
||||
.position(|line| line.starts_with(r"\endinput"))
|
||||
.unwrap()
|
||||
+ 1
|
||||
};
|
||||
let comment = if profile == InputProfile::XeTeX {
|
||||
// U+010A contains an LF byte in UTF-16 LE without ending the line.
|
||||
"% Inserted physical line \u{010a}\n"
|
||||
} else {
|
||||
"% Inserted physical line\n"
|
||||
};
|
||||
for (seed, edited) in [("", comment), (comment, "")] {
|
||||
// Give each direction one donor, so the deletion cannot reuse a
|
||||
// completed revision that already contained the shorter source.
|
||||
let original = body(seed);
|
||||
let original_source = encode(&format!("{HEADER}{original}"));
|
||||
let project =
|
||||
ProjectSnapshot::new(atomic_definition_with_source(&cwd, 1, original_source)).unwrap();
|
||||
let mut input = request(&cwd).observe_generated_initial();
|
||||
input.world = project.configuration();
|
||||
input.input_profile = profile;
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let donor = session
|
||||
.compile(input.clone().with_project(project.clone()))
|
||||
.unwrap();
|
||||
let donor_execution = &donor.execution.execution;
|
||||
let donor_line = final_line(&original);
|
||||
assert_eq!(donor_execution.input_position, Some((0, donor_line)));
|
||||
|
||||
let changed = body(edited);
|
||||
let current_line = final_line(&changed);
|
||||
assert_eq!(
|
||||
current_line,
|
||||
if edited.is_empty() {
|
||||
donor_line - 1
|
||||
} else {
|
||||
donor_line + 1
|
||||
}
|
||||
);
|
||||
let source = format!("{HEADER}{changed}");
|
||||
let prefix_read_end = byte_offset(&source, r"\shipout\hbox{Cover}");
|
||||
let glyph_offset = byte_offset(&source, "Suffix glyphs");
|
||||
let project = project
|
||||
.with_file_edits(2, [(entry.clone(), Arc::from(encode(&source)))].into())
|
||||
.unwrap();
|
||||
let input = input.with_project(project);
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let execution = &updated.execution.execution;
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(!work.reused_completion, "{work:?}");
|
||||
assert!(
|
||||
work.reused_frontier.is_some_and(|frontier| frontier >= prefix_read_end),
|
||||
"{work:?}"
|
||||
);
|
||||
assert_eq!(execution.input_position, Some((0, current_line)));
|
||||
assert_eq!(execution.state.count(42), 3);
|
||||
assert_eq!(updated.pages.len(), 4);
|
||||
assert!(updated.source_map.pages[2].entries.iter().any(|glyph| {
|
||||
glyph.source.tokens.iter().any(|origin| origin.span.start == glyph_offset)
|
||||
}));
|
||||
|
||||
if observe_delayed_line {
|
||||
// The write's tokens were saved in the preceding box. The
|
||||
// terminal line ends input before shipout, so no later checkpoint
|
||||
// can legitimately skip work after the delayed observation.
|
||||
assert_eq!(work.reused_suffix_steps, 0, "{work:?}");
|
||||
for (execution, line) in [(donor_execution, donor_line), (execution, current_line)] {
|
||||
let expected = format!("Suffix line {line}\n");
|
||||
assert!(execution.events.iter().any(|event| {
|
||||
matches!(event, texrra_tex_core::execution::Event::Write { text, .. } if text == &expected)
|
||||
}), "{expected:?}");
|
||||
}
|
||||
} else {
|
||||
assert!(work.reused_suffix_steps > 0, "{work:?}");
|
||||
assert!(updated.shipout_layout_work.reused_pages >= 2, "{work:?}");
|
||||
}
|
||||
assert!(
|
||||
updated.preview_since(Some(donor.revision())).unwrap().pages.is_empty(),
|
||||
"a physical source line moved without changing any page paint"
|
||||
);
|
||||
|
||||
let log = fs::read(cwd.join("job.log")).unwrap();
|
||||
let independent = NativeCompiler::default().compile(input).unwrap();
|
||||
assert_eq!(execution, &independent.execution.execution);
|
||||
assert_eq!(updated.execution.source_versions, independent.execution.source_versions);
|
||||
assert_eq!(updated.resources.trace, independent.resources.trace);
|
||||
assert_eq!(updated.resources.stream_io, independent.resources.stream_io);
|
||||
assert_eq!(updated.export_diagnostics, independent.export_diagnostics);
|
||||
assert_eq!(updated.pdf, independent.pdf);
|
||||
assert_eq!(updated.pages, independent.pages);
|
||||
assert_eq!(updated.source_map.sources, independent.source_map.sources);
|
||||
assert_eq!(updated.source_map.pages, independent.source_map.pages);
|
||||
assert_eq!(
|
||||
updated.preview_since(None).unwrap().pages,
|
||||
independent.preview_since(None).unwrap().pages
|
||||
);
|
||||
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
|
||||
}
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_length_line_edits_refresh_suffix_diagnostics_from_saved_prefix_tokens() {
|
||||
let cwd = directory("equal-length-suffix-line-diagnostic");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |before, after| {
|
||||
format!(
|
||||
"\n\
|
||||
\\TeXXeTstate=1\\relax\n\
|
||||
\\shipout\\hbox{{Cover}}\\relax\n\
|
||||
\\relax{before}\\afterassignment}}\\relax{after}\\relax\n\
|
||||
\\shipout\\hbox{{Checkpoint}}\\relax\n\
|
||||
\\endinput\\shipout\\hbox{{\\beginR X\\count0=1\\relax\\end\n"
|
||||
)
|
||||
};
|
||||
// The scheduled right brace keeps its byte offset and closes the last
|
||||
// box after the assignment. Its source line supplies the LR warning.
|
||||
let original = body(" ", "\n");
|
||||
let changed = body("\n", " ");
|
||||
let scheduled_brace = |body: &str| {
|
||||
body.find(r"\afterassignment}").unwrap() + r"\afterassignment".len()
|
||||
};
|
||||
let warning = |body: &str| {
|
||||
let line = body[..scheduled_brace(body)].matches('\n').count() + 1;
|
||||
format!("(1 missing, 0 extra) detected at line {line}\n")
|
||||
};
|
||||
assert_eq!(original.len(), changed.len());
|
||||
assert_eq!(scheduled_brace(&original), scheduled_brace(&changed));
|
||||
assert_ne!(warning(&original), warning(&changed));
|
||||
|
||||
let project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &original)).unwrap();
|
||||
let mut input = request(&cwd).observe_generated_initial();
|
||||
input.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
session.compile(input.clone().with_project(project.clone())).unwrap();
|
||||
let log_file = cwd.join("job.log");
|
||||
let donor_log = fs::read_to_string(&log_file).unwrap();
|
||||
assert!(donor_log.contains(&warning(&original)), "{donor_log}");
|
||||
|
||||
let source = format!("{HEADER}{changed}");
|
||||
let cover = source.find(r"\shipout\hbox{Cover}").unwrap();
|
||||
let project = project
|
||||
.with_file_edits(2, [(entry, Arc::from(source.into_bytes()))].into())
|
||||
.unwrap();
|
||||
let input = input.with_project(project);
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
assert!(work.reused_frontier.is_some_and(|frontier| frontier >= cover), "{work:?}");
|
||||
assert_eq!(work.reused_suffix_steps, 0, "{work:?}");
|
||||
let updated_log = fs::read_to_string(&log_file).unwrap();
|
||||
assert!(updated_log.contains(&warning(&changed)), "{updated_log}");
|
||||
assert!(!updated_log.contains(&warning(&original)), "{updated_log}");
|
||||
|
||||
let cold = NativeCompiler::default().compile(input).unwrap();
|
||||
assert_eq!(updated.execution.execution, cold.execution.execution);
|
||||
assert_eq!(updated_log, fs::read_to_string(log_file).unwrap());
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relocated_suffix_cannot_reuse_layouts_from_a_different_donor() {
|
||||
let cwd = directory("relocated-suffix-older-donor");
|
||||
let entry = cwd.join("main.tex");
|
||||
let middle = "\\shipout\\hbox{Middle}\\relax\n".repeat(5);
|
||||
let body = |early, early_comment, late, late_comment| format!(r"
|
||||
\tracingstats=2
|
||||
\shipout\hbox{{Cover ABCXYZ}}
|
||||
\setbox3=\hbox{{{early}}}\relax%{early_comment}
|
||||
\shipout\box3
|
||||
\relax
|
||||
{middle}\setbox3=\hbox{{{late}}}\relax%{late_comment}
|
||||
\shipout\box3
|
||||
\relax
|
||||
\shipout\hbox{{Checkpoint}}\relax
|
||||
\shipout\hbox{{Suffix glyphs}}\relax
|
||||
\shipout\hbox{{Final}}\relax
|
||||
\end
|
||||
");
|
||||
let original = body('A', "early", 'X', "late");
|
||||
let mut project = ProjectSnapshot::new(atomic_definition(&cwd, 1, &original)).unwrap();
|
||||
let mut request = request(&cwd).observe_generated_initial();
|
||||
request.world = project.configuration();
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
session.compile(request.clone().with_project(project.clone())).unwrap();
|
||||
|
||||
let early_edit = body('B', "expanded early comment", 'X', "late");
|
||||
project = project.with_file_edits(
|
||||
2, [(entry.clone(), Arc::from(format!("{HEADER}{early_edit}").into_bytes()))].into(),
|
||||
).unwrap();
|
||||
let latest = session.compile(request.clone().with_project(project.clone())).unwrap();
|
||||
let first_work = &latest.entry_checkpoint_work;
|
||||
assert!(first_work.reused_suffix_steps > 0, "{first_work:?}");
|
||||
|
||||
// Relative to the latest layout this changes two lines. Only the older
|
||||
// execution, which differs on the late line alone, can donate the suffix.
|
||||
let late_edit = body('A', "early", 'Y', "x");
|
||||
project = project.with_file_edits(
|
||||
3, [(entry, Arc::from(format!("{HEADER}{late_edit}").into_bytes()))].into(),
|
||||
).unwrap();
|
||||
let job = request.with_project(project);
|
||||
let updated = session.compile(job.clone()).unwrap();
|
||||
let work = &updated.entry_checkpoint_work;
|
||||
let layout = &updated.shipout_layout_work;
|
||||
assert!(work.reused_suffix_steps > 0, "{work:?}");
|
||||
assert_eq!(layout.reused_pages, 1, "{work:?} {layout:?}");
|
||||
assert_eq!(layout.lowered_pages, updated.pages.len() - 1);
|
||||
let changed: Vec<_> = updated.preview_since(Some(latest.revision())).unwrap()
|
||||
.pages.into_iter().map(|page| page.index).collect();
|
||||
assert_eq!(changed, [1, 7]);
|
||||
|
||||
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());
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_suffix_translates_step_counts_and_enforces_the_limit() {
|
||||
let cwd = directory("settled-step-counts");
|
||||
let entry = cwd.join("main.tex");
|
||||
let body = |command| {
|
||||
format!(
|
||||
r"
|
||||
\tracingstats=2
|
||||
\def\unitA{{\relax}}\def\unitB{{\relax\relax}}
|
||||
\unitA\unitB
|
||||
\shipout\hbox{{Cover}}\relax
|
||||
{command}
|
||||
\shipout\hbox{{Second}}\relax
|
||||
\shipout\hbox{{Third}}\relax
|
||||
\shipout\hbox{{Fourth}}\relax
|
||||
\end
|
||||
"
|
||||
)
|
||||
};
|
||||
let original = ProjectSnapshot::new(atomic_definition(&cwd, 1, &body(r"\unitA"))).unwrap();
|
||||
let mut request = request(&cwd).observe_generated_initial();
|
||||
request.world = original.configuration();
|
||||
let edited = original
|
||||
.with_file_edits(
|
||||
2,
|
||||
[(
|
||||
entry.clone(),
|
||||
Arc::from(format!("{HEADER}{}", body(r"\unitB")).into_bytes()),
|
||||
)]
|
||||
.into(),
|
||||
)
|
||||
.unwrap();
|
||||
let shorter = edited
|
||||
.with_file_edits(
|
||||
3,
|
||||
[(
|
||||
entry.clone(),
|
||||
Arc::from(format!("{HEADER}{}", body(r"\unitA")).into_bytes()),
|
||||
)]
|
||||
.into(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut old_steps = 0;
|
||||
for (seed, project, increased) in [
|
||||
(original.clone(), edited.clone(), true),
|
||||
(edited.clone(), shorter, false),
|
||||
] {
|
||||
// Each direction starts with a single donor so the decreasing
|
||||
// edit cannot pick an earlier completion with the same count.
|
||||
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let donor = session.compile(request.clone().with_project(seed)).unwrap();
|
||||
let donor_steps = donor.execution.execution.steps;
|
||||
let input = request.clone().with_project(project);
|
||||
let updated = session.compile(input.clone()).unwrap();
|
||||
assert!(
|
||||
updated.entry_checkpoint_work.reused_suffix_steps > 0,
|
||||
"{:?}",
|
||||
updated.entry_checkpoint_work
|
||||
);
|
||||
if increased {
|
||||
old_steps = donor_steps;
|
||||
assert!(updated.execution.execution.steps > old_steps);
|
||||
} else {
|
||||
assert!(updated.execution.execution.steps < donor_steps);
|
||||
assert_eq!(updated.execution.execution.steps, old_steps);
|
||||
}
|
||||
let log = fs::read(cwd.join("job.log")).unwrap();
|
||||
let full = NativeCompiler::default().compile(input).unwrap();
|
||||
assert_eq!(updated.execution.execution, full.execution.execution);
|
||||
assert_eq!(updated.pdf, full.pdf);
|
||||
assert_eq!(updated.source_map.pages, full.source_map.pages);
|
||||
assert_eq!(log, fs::read(cwd.join("job.log")).unwrap());
|
||||
}
|
||||
|
||||
request.limits.steps = old_steps;
|
||||
let limited = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||
let first = limited
|
||||
.compile(request.clone().with_project(original))
|
||||
.unwrap();
|
||||
let input = request.with_project(edited);
|
||||
let failure = limited.compile(input.clone()).err().unwrap().to_string();
|
||||
assert!(failure.contains("step limit exceeded"), "{failure}");
|
||||
assert_eq!(limited.latest().unwrap().revision(), first.revision());
|
||||
assert_eq!(
|
||||
fs::read(cwd.join("job.pdf")).unwrap().as_slice(),
|
||||
first.pdf.as_deref().unwrap()
|
||||
);
|
||||
let full = NativeCompiler::default()
|
||||
.compile(input)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert_eq!(failure, full);
|
||||
fs::remove_dir_all(cwd).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settled_suffix_replays_with_the_edited_prefix_and_discards_a_rejected_draft() {
|
||||
let cwd = directory("settled-suffix");
|
||||
|
||||
Reference in new issue
Block a user