From 1ad9c4db822366985fed822276d08ade300a9d5c Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 01:29:28 +0800 Subject: [PATCH] Bind native format inputs after moving a project tree --- .../src/execution/format_image.rs | 15 +- .../src/execution/format_image/location.rs | 192 ++++++++++++++++++ crates/texrra-tex-core/src/resources.rs | 39 +++- .../src/resources/named_fonts.rs | 1 + docs/P2_M1_PROGRESS.md | 37 ++++ src/native.rs | 65 ++++-- src/native_checkpoint_guard.rs | 5 + tests/native_pipeline.rs | 178 ++++++++++++++++ 8 files changed, 509 insertions(+), 23 deletions(-) create mode 100644 crates/texrra-tex-core/src/execution/format_image/location.rs diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index f0db472..ef0a323 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -6,6 +6,8 @@ use crate::{ }; pub(super) mod boxes; mod images; +mod location; +use location::FormatLocation; pub(super) use images::{FormatImageKind, FormatPdfImage}; use sha2::{Digest, Sha256}; use std::{ @@ -14,9 +16,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 92; -const COMPATIBLE_SCHEMAS: [u32; 58] = [ - 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, SCHEMA, +const SCHEMA: u32 = 93; +const COMPATIBLE_SCHEMAS: [u32; 59] = [ + 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -32,6 +34,8 @@ pub struct FormatImage { resources: Vec, stream_reads: Vec, file_dates: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + location: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pdf_images: Vec, #[serde(skip)] @@ -117,6 +121,7 @@ impl FormatImage { stream_reads, file_dates, pdf_images, + location: None, input_checks: OnceLock::new(), }) } @@ -157,6 +162,9 @@ impl FormatImage { { return Err("incompatible native format image".into()); } + if image.location.as_ref().is_some_and(|location| image.schema < 93 || !location.is_valid()) { + return Err("invalid native format project location".into()); + } if image.state.fonts.has_unrecorded_expansion_limits() { return Err("native format must be rebuilt to restore automatic expansion font identities".into()); } @@ -551,6 +559,7 @@ mod tests { from: "stream.tex".into(), value: Some("observed date".into()), }], + location: None, input_checks: OnceLock::new(), }; let encoded = image.encode().unwrap(); diff --git a/crates/texrra-tex-core/src/execution/format_image/location.rs b/crates/texrra-tex-core/src/execution/format_image/location.rs new file mode 100644 index 0000000..ac57fbb --- /dev/null +++ b/crates/texrra-tex-core/src/execution/format_image/location.rs @@ -0,0 +1,192 @@ +use super::FormatImage; +use crate::resources::{ResourceKind, ResourceTrace}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, BTreeSet}, + path::{Component, Path, PathBuf}, + sync::Arc, +}; + +#[derive(Serialize, Deserialize)] +pub(super) struct FormatLocation { + cwd: PathBuf, + format_directory: PathBuf, + inputs: BTreeMap>, +} + +impl FormatImage { + /// Save the region of the project tree that contains the format and its + /// relative file inputs. An absolute lookup keeps the physical binding. + pub fn with_project_location(mut self, output: &Path, trace: &ResourceTrace) -> Self { + let Some(directory) = output + .parent() + .and_then(|p| p.strip_prefix(&trace.cwd).ok()) + else { + return self; + }; + let checked = self.build_input_checks(); + let eager_images: BTreeSet<_> = self + .pdf_images + .iter() + .filter(|image| image.kind.reads_at_load()) + .map(|image| image.path()) + .collect(); + let mut inputs = BTreeMap::>::new(); + let mut pinned = BTreeSet::new(); + for lookup in &trace.lookups { + let Some(path) = &lookup.resolved else { + continue; + }; + if !path.starts_with(&trace.cwd) + || !(checked.contains_key(path) || eager_images.contains(path.as_path())) + { + continue; + } + match &lookup.lookup_path { + Some(spelling) + if matches!(lookup.kind, ResourceKind::Tex | ResourceKind::PdfImage) + && relative_tree_path(spelling) + && !spelling.as_os_str().is_empty() => + { + inputs + .entry(path.clone()) + .or_default() + .insert(spelling.clone()); + } + _ => { + pinned.insert(path); + } + } + } + inputs.retain(|path, _| !pinned.contains(path)); + if !inputs.is_empty() { + self.location = Some(FormatLocation { + cwd: trace.cwd.clone(), + format_directory: directory.to_owned(), + inputs, + }); + } + self + } + + /// Resolve a moved tree as a group. A format copied without its relative + /// inputs still uses the original tree. Once any moved input is present, + /// every recorded input and alias in the moved tree must be available. + pub fn input_bindings( + &self, + format: &Path, + mut resolve: impl FnMut(&Path) -> Result, String>, + ) -> Result, String> { + let Some(location) = &self.location else { + return Ok(BTreeMap::new()); + }; + let Some(mut root) = format.parent() else { + return Ok(BTreeMap::new()); + }; + for component in location.format_directory.components().rev() { + if root.file_name() != Some(component.as_os_str()) { + return Ok(BTreeMap::new()); + } + root = root.parent().ok_or("format path has no project root")?; + } + if root == location.cwd { + return Ok(BTreeMap::new()); + } + + let mut bindings = BTreeMap::new(); + let mut missing = None; + for (original, spellings) in &location.inputs { + let mut selected = None; + for spelling in spellings { + let candidate = root.join(spelling); + if let Some(bound) = resolve(&candidate)? { + if selected.as_ref().is_some_and(|prior| prior != &bound) { + return Err(format!( + "native format input aliases diverged: {}", + original.display() + )); + } + selected = Some(bound); + } else { + missing.get_or_insert(candidate); + } + } + if let Some(bound) = selected { + bindings.insert(original.clone(), bound); + } + } + if !bindings.is_empty() + && let Some(path) = missing + { + return Err(format!( + "native format relocated input not found: {}", + path.display() + )); + } + Ok(bindings) + } + + /// Bind decoded validation and provenance to the paths observed by the + /// loading job. All original byte and stream checks still run. + pub fn bind_inputs(&mut self, bindings: &BTreeMap) { + if bindings.is_empty() { + return; + } + for (id, source) in self.sources.iter_mut().enumerate() { + if !self.generated_inputs.contains_key(&id) + && let Some(path) = bindings.get(Path::new(&source.name)) + { + source.name = path.to_string_lossy().into_owned(); + } + } + for resource in &mut self.resources { + if let Some(path) = bindings.get(&resource.path) { + resource.path.clone_from(path); + } + } + for range in &mut self.stream_reads { + if let Some(path) = bindings.get(&range.path) { + range.path.clone_from(path); + } + } + for date in &mut self.file_dates { + if let Some(path) = bindings.get(Path::new(&date.from)) { + date.from = path.to_string_lossy().into_owned(); + } + } + for image in self + .pdf_images + .iter_mut() + .filter(|image| image.kind.reads_at_load()) + { + if let Some(path) = bindings.get(image.path()) { + let place = Arc::make_mut(&mut image.image); + Arc::make_mut(&mut place.image) + .version + .path + .clone_from(path); + } + } + self.input_checks.take(); + } +} + +impl FormatLocation { + pub(super) fn is_valid(&self) -> bool { + self.cwd.is_absolute() + && relative_tree_path(&self.format_directory) + && !self.inputs.is_empty() + && self.inputs.iter().all(|(path, spellings)| { + path.starts_with(&self.cwd) + && !spellings.is_empty() + && spellings + .iter() + .all(|name| relative_tree_path(name) && !name.as_os_str().is_empty()) + }) + } +} + +fn relative_tree_path(path: &Path) -> bool { + path.components() + .all(|part| matches!(part, Component::Normal(_) | Component::CurDir)) +} diff --git a/crates/texrra-tex-core/src/resources.rs b/crates/texrra-tex-core/src/resources.rs index adaec52..4ec61d8 100644 --- a/crates/texrra-tex-core/src/resources.rs +++ b/crates/texrra-tex-core/src/resources.rs @@ -214,6 +214,8 @@ pub struct ResourceLookup { pub from: PathBuf, pub candidates: Vec, pub resolved: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lookup_path: Option, pub error: Option, } /// Bytes delivered by a stream read, rather than a snapshot of the whole file. @@ -271,6 +273,8 @@ pub struct ResourceTrace { pub texmf_roots: Vec, pub paths: BTreeMap>, pub lookups: Vec, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub format_input_bindings: BTreeMap, /// Versions of bytes actually read, not hashes guessed from input strings. pub reads: Vec, pub stream_reads: Vec, @@ -531,6 +535,7 @@ impl InputSnapshot { pub struct FileWorld { config: WorldConfig, tex_suffix_fallback: bool, + capture_lookup_paths: bool, indexes: BTreeMap>, current_project_indexes: BTreeSet, index_failures: BTreeMap, @@ -670,6 +675,7 @@ impl FileWorld { Ok(Self { config, tex_suffix_fallback: true, + capture_lookup_paths: false, indexes: BTreeMap::new(), current_project_indexes: BTreeSet::new(), index_failures: BTreeMap::new(), @@ -697,6 +703,11 @@ impl FileWorld { } self.pinned = true; } + /// Record the selected lookup spelling for a persisted format's inputs. + pub fn capture_lookup_paths(&mut self) { + self.capture_lookup_paths = true; + } + pub fn from_project(project: Arc) -> Result { project.validate()?; let config = project.configuration(); @@ -713,6 +724,7 @@ impl FileWorld { Ok(Self { config, tex_suffix_fallback: true, + capture_lookup_paths: false, indexes: BTreeMap::new(), current_project_indexes: BTreeSet::new(), index_failures: BTreeMap::new(), @@ -793,6 +805,7 @@ impl FileWorld { Ok(Self { config, tex_suffix_fallback: snapshot.tex_suffix_fallback, + capture_lookup_paths: false, indexes: snapshot.indexes.clone(), current_project_indexes: BTreeSet::new(), index_failures: snapshot.index_failures.clone(), @@ -1219,6 +1232,10 @@ impl FileWorld { error }) } + pub fn record_format_input_bindings(&mut self, bindings: &BTreeMap) { + self.trace.format_input_bindings.clone_from(bindings); + } + pub fn trace(&self) -> &ResourceTrace { &self.trace } @@ -1463,9 +1480,11 @@ impl FileWorld { name: &str, from: &Path, variants: Vec, - mut lookup_path: Option<&mut PathBuf>, + lookup_path: Option<&mut PathBuf>, ) -> Result, String> { let mut candidates = Vec::new(); + let record_spelling = self.capture_lookup_paths || lookup_path.is_some(); + let mut spelling = None; let result = (|| { let paths = self.paths(kind, from); let mut found = None; @@ -1480,8 +1499,8 @@ impl FileWorld { let path = self.config.cwd.join(variant); candidates.push(path.clone()); if let Some(path) = self.probe(&path)? { - if let Some(lookup_path) = lookup_path.as_deref_mut() { - lookup_path.clone_from(variant); + if record_spelling { + spelling = Some(variant.clone()); } found = Some(path); break; @@ -1516,8 +1535,8 @@ impl FileWorld { let direct = root.join(suffix).join(variant); candidates.push(direct.clone()); if let Some(path) = self.probe(&direct)? { - if let Some(lookup_path) = lookup_path.as_deref_mut() { - *lookup_path = lookup_name(&self.config.cwd, &direct); + if record_spelling { + spelling = Some(lookup_name(&self.config.cwd, &direct)); } found = Some(path); break 'paths; @@ -1573,8 +1592,8 @@ impl FileWorld { } candidates.push(candidate.clone()); if let Some(path) = self.probe(&candidate)? { - if let Some(lookup_path) = lookup_path.as_deref_mut() { - *lookup_path = lookup_name(&self.config.cwd, &candidate); + if record_spelling { + spelling = Some(lookup_name(&self.config.cwd, &candidate)); } found = Some(path); break 'paths; @@ -1586,12 +1605,18 @@ impl FileWorld { } Ok(found) })(); + if let Some(lookup_path) = lookup_path + && let Some(selected) = &spelling + { + lookup_path.clone_from(selected); + } self.trace.lookups.push(ResourceLookup { kind, name: name.into(), from: from.into(), candidates, resolved: result.as_ref().ok().cloned().flatten(), + lookup_path: spelling.filter(|_| self.capture_lookup_paths), error: result.as_ref().err().cloned(), }); result diff --git a/crates/texrra-tex-core/src/resources/named_fonts.rs b/crates/texrra-tex-core/src/resources/named_fonts.rs index 68c6ce1..25fb39c 100644 --- a/crates/texrra-tex-core/src/resources/named_fonts.rs +++ b/crates/texrra-tex-core/src/resources/named_fonts.rs @@ -191,6 +191,7 @@ impl FileWorld { .ok() .and_then(|result| result.as_ref()) .map(|font| font.resource.version.path.clone()), + lookup_path: None, error: result.as_ref().err().cloned(), }); result diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 5a949af..a107579 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -744,6 +744,43 @@ PDF、SVG 和逐页来源映射与独立全量相同。六项图像回归通过 新目录,原版生成三页,原生在校验转储输入时查找旧 seed.tex 并报告缺失。该复现及旧路径诊断在 next-format-source-location。 +### 原生格式的项目输入路径迁移 + +schema93 保留格式所在目录在生成项目中的位置,以及已读取的相对 +TeX 输入和需在载入时重开的 pdfTeX 图像路径。格式和项目保持原有相对目录 +布局时,新作业通过实际的资源命名空间选择整个迁移后的输入组。 +目标位置缺少整组输入时可继续使用原位置。目标位置命中部分输入 +时,报告缺失或分叉的路径,避免跨树拼装同一个格式。显式绝对 +路径、绝对搜索命中的资源和旧格式使用原有的文件身份。 + +已绑定的 TeX 来源、资源版本、读取区间和文件时间查询来源进入 +现有加载校验。文件字节、读取区间与 EOF 条件继续与转储时的实际 +观测比较。来源映射使用当前已绑定路径。格式缓存和执行检查点 +同时比较原生格式本身的版本与加载时实际选中的输入路径。 +[原版 XeTeX 格式读写入口](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/xetex.web#L26504-L26557) + +原样 XeTeX 对照把格式放在子目录,再将格式、转储源码、 +PDF 和 PNG 一同移至新树。三页的 144 DPI 光栅与原版一致,来源 +映射和资源追踪确认从新树读取。pdfTeX 对照把两个需在载入时重开 +的装箱图像与格式一同移动,两个页面逐像素一致。实际 schema92 +格式仍生成同样的三页。单独复制格式会读取原输入组,加入部分 +迁移输入后会报告缺失的新路径,补齐后恢复相同的光栅。 + +六项格式相关回归通过。迁移后的两页项目修改正文时复用检查点, +只更新第 2 页。PDF、测量页面、完整 SVG 与来源映射等于独立全量。 +修改已消费的流首行或子文件会拒绝加载并保留上一版本,改变未消费 +的流尾部可通过原读取区间校验。另核对旧目录的显式绝对输入仍从 +原址实际读取。 + +证据在 target/p3-format-input-relocation。relocated-reference.log 为 +e087f421d4f52a9e9509023c16116a9410b62db06ad800aa431e6a228b8eef42, +pdftex-eager.log 为 cf0693d6382cab49b219018676dad1e21ac6e296ef7816ec59fb217e0e1558d3。 +第一轮流变更触发来源前缀诊断的回执保留于 release-tests-first.log。 +项目局部 TFM 和格式一起移动时,原版加载并输出保存的 21.8056 pt +盒宽,原生仍在旧 TFM 路径的校验处拒绝。下一入口和原输出在 +next-local-tfm,逐步接通格式字体本身、已装盒字形及后续设备读取 +使用的资源版本。 + ### XeTeX 纸张指令进入实际发页 XeTeX 每页隐式纸张设置与文档内的 `pdf:pagesize` 按发页顺序生效。 diff --git a/src/native.rs b/src/native.rs index f59ba0e..c1e4d30 100644 --- a/src/native.rs +++ b/src/native.rs @@ -24,7 +24,8 @@ pub use crate::native_stream::{ use checkpoint_guard::CheckpointCache; pub use checkpoint_guard::EntryCheckpointWork; use std::{ - path::PathBuf, + collections::BTreeMap, + path::{Path, PathBuf}, sync::{Arc, Mutex}, }; pub use texrra_tex_core::resources::{ProjectDefinition, ProjectSnapshot, ProjectVersion}; @@ -578,23 +579,24 @@ pub struct NativeCompiler { #[derive(Default)] struct FormatCache(Mutex>); +#[derive(Clone)] struct CachedFormat { version: ResourceVersion, image: Arc, + bindings: Arc>, } impl FormatCache { - fn get(&self, version: &ResourceVersion) -> Option> { + fn get(&self, version: &ResourceVersion) -> Option { let cache = self.0.lock().expect("decoded native format cache poisoned"); cache .as_ref() .filter(|old| old.version == *version) - .map(|old| old.image.clone()) + .cloned() } - fn insert(&self, version: ResourceVersion, image: Arc) { - *self.0.lock().expect("decoded native format cache poisoned") = - Some(CachedFormat { version, image }); + fn insert(&self, format: CachedFormat) { + *self.0.lock().expect("decoded native format cache poisoned") = Some(format); } } pub struct CompileJob { @@ -738,6 +740,9 @@ fn prepare_checked( world.capture_inputs(); world }; + if dump { + world.capture_lookup_paths(); + } let prepared = (|| -> Result<_, CompileError> { evidence.host_preparation.phase = HostPreparationPhase::OutputPaths; let output = evidence @@ -791,15 +796,46 @@ fn prepare_checked( check(cancellation).map_err(|e| e.to_string())?; file_modification_date(world, name, from) }; + let bindings_for = |image: &FormatImage, world: &mut FileWorld| { + let bindings = image.input_bindings(&loaded.version.path, |candidate: &Path| { + check(cancellation).map_err(|e| e.to_string())?; + world.resolve(ResourceKind::Tex, &candidate.to_string_lossy(), &path) + })?; + world.record_format_input_bindings(&bindings); + Ok::<_, CompileError>(bindings) + }; match format_cache { Some(cache) => { - let (image, preparation) = match cache.get(&loaded.version) { - Some(image) => (image, FormatPreparation::Reused), - None => ( - Arc::new(FormatImage::decode(&loaded.data)?), + let (cached, preparation) = if let Some(cached) = cache.get(&loaded.version) { + let bindings = bindings_for(&cached.image, &mut world)?; + if *cached.bindings == bindings { + (cached, FormatPreparation::Reused) + } else { + let mut image = FormatImage::decode(&loaded.data)?; + image.bind_inputs(&bindings); + ( + CachedFormat { + version: loaded.version, + image: Arc::new(image), + bindings: Arc::new(bindings), + }, + FormatPreparation::Decoded, + ) + } + } else { + let mut image = FormatImage::decode(&loaded.data)?; + let bindings = bindings_for(&image, &mut world)?; + image.bind_inputs(&bindings); + ( + CachedFormat { + version: loaded.version, + image: Arc::new(image), + bindings: Arc::new(bindings), + }, FormatPreparation::Decoded, - ), + ) }; + let image = &cached.image; let executor = if kernel == KernelPreparation::Resume { image.validate_shared_job_inputs( state.profile(), @@ -822,12 +858,14 @@ fn prepare_checked( }; check(cancellation)?; if preparation == FormatPreparation::Decoded { - cache.insert(loaded.version, image); + cache.insert(cached); } (executor, Some(preparation)) } None => { - let image = FormatImage::decode(&loaded.data)?; + let mut image = FormatImage::decode(&loaded.data)?; + let bindings = bindings_for(&image, &mut world)?; + image.bind_inputs(&bindings); let executor = if kernel == KernelPreparation::Resume { image.validate_shared_job_inputs( state.profile(), @@ -1360,6 +1398,7 @@ fn dump_format_observed( // Keep the completed kernel result available if format validation/encoding // fails. This extra offline copy is not part of interactive compilation. let bytes = FormatImage::from_dump_with_trace(execution.execution.clone(), trace)? + .with_project_location(&output, trace) .encode()?; evidence.phase = AttemptPhase::Finishing; let finished = files.finish(); diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index 9745b39..c2e01fe 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -615,6 +615,7 @@ struct PrefixInputGuard { immutable: BTreeSet, generated: BTreeSet, lookups: Vec, + format_input_bindings: BTreeMap, clock_environment: Option<[Option; 3]>, } @@ -696,6 +697,7 @@ impl PrefixInputGuard { immutable, generated, lookups: trace.lookups.clone(), + format_input_bindings: trace.format_input_bindings.clone(), clock_environment: (!trace.file_modifications.is_empty()).then(date_environment), }) } @@ -765,6 +767,9 @@ impl PrefixInputGuard { preparation: &HostPreparation, ) -> Result<(), String> { let current = self.verify_project(request)?; + 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) { return Err("checkpoint entry resolved to a different path".into()); } diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 7caa810..1d77227 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -1554,6 +1554,184 @@ fn format_seed_reuse_restarts_execution_and_checks_live_dependencies() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn relocated_format_checks_current_sources_and_consumed_stream_ranges() { + let root = directory("format-relocation").canonicalize().unwrap(); + let origin = root.join("origin"); + let project = root.join("project"); + for directory in [&origin, &project] { + fs::create_dir_all(directory.join("formats")).unwrap(); + fs::create_dir_all(directory.join("parts")).unwrap(); + } + let fixed = origin.join("pinned.tex"); + let seed = format!( + "\\catcode123=1 \\catcode125=2 \\pdfoutput=1\n\ + \\input parts/layout.tex\n\ + \\input \"{}\"\n\ + \\openin3=range.tex \\read3 to\\storedwidth \\closein3\n\ + \\dump\n", + fixed.display() + ); + let layout = br"\def\savedrule{\vrule width\storedwidth height\fixedheight depth0pt}"; + fs::write(origin.join("seed.tex"), &seed).unwrap(); + fs::write(origin.join("parts/layout.tex"), layout).unwrap(); + fs::write(origin.join("range.tex"), b"8pt\nunread before move\n").unwrap(); + fs::write(&fixed, br"\def\fixedheight{4pt}").unwrap(); + + let mut build = request(&origin); + build.input = "seed.tex".into(); + build.output = "formats/seed.tfx".into(); + let dumped = dump_format(build, Cancellation::default()).unwrap(); + assert!(dumped.resources.trace.stream_reads.iter().any(|range| { + range.path == origin.join("range.tex") && range.offset == 0 && range.bytes == 4 + })); + + let seed_path = project.join("seed.tex"); + let library = project.join("parts/layout.tex"); + let stream = project.join("range.tex"); + let format = project.join("formats/seed.tfx"); + let entry = project.join("entry.tex"); + let padding = format!("{}\n", "\\relax ".repeat(30)).repeat(42); + let prefix = "\\shipout\\hbox{\\savedrule}\n"; + let source = |width| { + format!( + "{prefix}{padding}\\shipout\\hbox{{\\vrule width{width}pt height3pt depth0pt}}\\end\n" + ) + }; + + let world = WorldConfig::new(&project); + let snapshot = ProjectSnapshot::new(ProjectDefinition { + configuration: world.clone(), + revision: 1, + roots: [root.clone()].into(), + files: [ + (seed_path.clone(), Arc::from(seed.as_bytes())), + (library.clone(), Arc::from(layout.as_slice())), + ( + stream.clone(), + Arc::from(b"8pt\nunread after move\n".as_slice()), + ), + ( + format.clone(), + fs::read(origin.join("formats/seed.tfx")).unwrap().into(), + ), + (entry.clone(), Arc::from(source(3).into_bytes())), + (fixed.clone(), fs::read(&fixed).unwrap().into()), + ( + project.join("pinned.tex"), + Arc::from(br"\def\fixedheight{99pt}".as_slice()), + ), + ] + .into(), + directories: Default::default(), + aliases: Default::default(), + generated_roots: [project.clone()].into(), + generated: Default::default(), + }) + .unwrap(); + + let mut job = request(&project); + job.world = world; + job.input = entry.clone(); + job.entry = Entry::Format(format); + let compiler = NativeCompiler::default().with_entry_checkpoints(prefix.len() + 48); + let first = compiler + .compile(job.clone().with_project(snapshot.clone())) + .unwrap(); + assert!( + first + .execution + .execution + .sources + .iter() + .any(|source| source.name == library.to_string_lossy()) + ); + assert!( + first + .resources + .trace + .reads + .iter() + .any(|resource| resource.path == fixed) + ); + assert_eq!( + first + .resources + .trace + .format_input_bindings + .get(&origin.join("parts/layout.tex")), + Some(&library) + ); + assert_eq!( + first + .resources + .trace + .format_input_bindings + .get(&origin.join("range.tex")), + Some(&stream) + ); + assert!( + !first + .resources + .trace + .format_input_bindings + .contains_key(&fixed) + ); + + let changed = snapshot + .with_file_edits(2, [(entry, source(5).into_bytes().into())].into()) + .unwrap(); + let revised = job.clone().with_project(changed.clone()); + let next = compiler.compile(revised.clone()).unwrap(); + assert!( + next.entry_checkpoint_work.reused_steps > 0, + "{:?}", + next.entry_checkpoint_work + ); + let delta = next.preview_since(Some(first.revision())).unwrap(); + assert_eq!( + delta + .pages + .iter() + .map(|page| page.index) + .collect::>(), + [1] + ); + let full = NativeCompiler::default().compile(revised).unwrap(); + assert_eq!(next.pdf, full.pdf); + assert_eq!(next.pages, full.pages); + assert_eq!(next.source_map.pages, full.source_map.pages); + assert_eq!(next.source_map.sources, full.source_map.sources); + assert_eq!( + next.preview_since(None).unwrap().pages, + full.preview_since(None).unwrap().pages + ); + + for (path, bytes) in [ + ( + &library, + br"\def\savedrule{\vrule width5pt height4pt}".as_slice(), + ), + (&stream, b"9pt\nunread after move\n".as_slice()), + ] { + let edited = changed + .with_file_edits(3, [(path.clone(), Arc::from(bytes))].into()) + .unwrap(); + let failure = compiler + .compile_detailed(job.clone().with_project(edited)) + .err() + .unwrap(); + let message = failure.error.to_string(); + assert!( + message.contains("native format source changed") + && message.contains(path.to_str().unwrap()), + "{message}" + ); + assert!(Arc::ptr_eq(&next, &compiler.latest().unwrap())); + } + fs::remove_dir_all(root).unwrap(); +} + #[test] fn shared_format_build_load_and_cancelled_build_preserve_real_output_policy() { let p = directory("format");