From 509f229a5237b6cd2e40cf69360215281f91f8ef Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 28 Nov 2026 09:55:09 +0800 Subject: [PATCH] Apply Web2C TCX tables to native byte streams --- .../src/execution/byte_translation.rs | 110 ++++++++++++++++++ .../texrra-tex-core/src/execution/engine.rs | 59 ++++++---- .../src/execution/format_image.rs | 6 +- crates/texrra-tex-core/src/execution/mod.rs | 13 +++ crates/texrra-tex-core/src/execution/mouth.rs | 6 +- crates/texrra-tex-core/src/execution/state.rs | 12 ++ docs/P2_M1_PROGRESS.md | 45 +++++++ src/main.rs | 13 ++- src/native.rs | 17 +++ src/native_checkpoint_guard.rs | 1 + src/native_checkpoint_probe.rs | 12 ++ src/native_job.rs | 45 +++++-- tests/native_job_io.rs | 92 +++++++++++++++ 13 files changed, 393 insertions(+), 38 deletions(-) create mode 100644 crates/texrra-tex-core/src/execution/byte_translation.rs diff --git a/crates/texrra-tex-core/src/execution/byte_translation.rs b/crates/texrra-tex-core/src/execution/byte_translation.rs new file mode 100644 index 0000000..aa1abec --- /dev/null +++ b/crates/texrra-tex-core/src/execution/byte_translation.rs @@ -0,0 +1,110 @@ +//! Web2C character translation and printability for physical TeX byte I/O. +#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +pub struct ByteTranslation { + input: [[u8; 32]; 8], + output: [[u8; 32]; 8], + printable: [u64; 4], +} + +impl Default for ByteTranslation { + fn default() -> Self { + let identity = + std::array::from_fn(|row| std::array::from_fn(|column| (row * 32 + column) as u8)); + Self { + input: identity, + output: identity, + printable: [u64::MAX << 32, u64::MAX >> 1, 0, 0], + } + } +} + +impl ByteTranslation { + pub fn from_tcx(data: &[u8]) -> Result { + let mut table = Self::default(); + for (line, bytes) in data.split(|&b| b == b'\n').enumerate() { + let record = bytes.split(|&b| b == b'%').next().unwrap_or_default(); + let record = std::str::from_utf8(record) + .map_err(|_| format!("invalid TCX entry on line {}", line + 1))?; + let mut fields = record.split_ascii_whitespace(); + let Some(field) = fields.next() else { + continue; + }; + let parse = |field| { + number(field).ok_or_else(|| format!("invalid TCX entry on line {}", line + 1)) + }; + let external = parse(field)?; + let internal = if let Some(field) = fields.next() { + let internal = parse(field)?; + table.input[usize::from(external) / 32][usize::from(external) % 32] = internal; + table.output[usize::from(internal) / 32][usize::from(internal) % 32] = external; + internal + } else { + external + }; + let printable = match fields.next() { + Some(field) => match parse(field)? { + 0 => false, + 1 => true, + _ => return Err(format!("invalid TCX printable flag on line {}", line + 1)), + }, + None => true, + }; + let mask = 1_u64 << (internal % 64); + let entry = &mut table.printable[usize::from(internal) / 64]; + if printable || (32..=126).contains(&internal) { + *entry |= mask; + } else { + *entry &= !mask; + } + } + Ok(table) + } + + pub(super) fn input(&self, value: u8) -> u8 { + self.input[usize::from(value) / 32][usize::from(value) % 32] + } + + pub(super) fn output(&self, value: u8) -> u8 { + self.output[usize::from(value) / 32][usize::from(value) % 32] + } + + pub(super) fn printable(&self, value: u8) -> bool { + self.printable[usize::from(value) / 64] & (1_u64 << (value % 64)) != 0 + } +} + +fn number(field: &str) -> Option { + let field = field.strip_prefix('+').unwrap_or(field); + if let Some(hex) = field + .strip_prefix("0x") + .or_else(|| field.strip_prefix("0X")) + { + u8::from_str_radix(hex, 16).ok() + } else if field.len() > 1 && field.starts_with('0') { + u8::from_str_radix(field, 8).ok() + } else { + field.parse().ok() + } +} + +pub(super) fn diagnostic_text(bytes: &[u8]) -> String { + let mut text = String::new(); + let mut remaining = bytes; + loop { + match std::str::from_utf8(remaining) { + Ok(valid) => { + text.push_str(valid); + return text; + } + Err(error) => { + let start = error.valid_up_to(); + let end = start + error.error_len().unwrap_or(remaining.len() - start); + text.push_str(std::str::from_utf8(&remaining[..start]).unwrap()); + for &byte in &remaining[start..end] { + text.push_str(&super::context::encoded_character(char::from(byte))); + } + remaining = &remaining[end..]; + } + } + } +} diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 398ab1a..be41933 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -369,6 +369,11 @@ impl EntryCheckpoint { } impl Executor { + pub fn with_byte_translation(mut self, table: ByteTranslation) -> Self { + self.state.byte_translation = Some(Arc::new(table)); + self + } + // Native jobs enforce the no-shell-escape policy for immediate and shipped writes. const SHELL_ESCAPE: i32 = 0; // Compatibility level for the eight-bit native PDF interface. @@ -2919,7 +2924,7 @@ impl Executor { }, ))? .map(|(offset, value)| xe_encoding::Character { - value, + value: self.state.translate_input_character(value), start: base + offset, end: base + offset + profile.width(value), }) @@ -3155,18 +3160,21 @@ impl Executor { OutputOperation::Write { stream, tokens } => { let expanded = self.fully_expand(tokens.clone(), files)?; let text = self.token_list_text(&expanded); - let mut text = self.external_print(&text); + let mut bytes = self.external_print_bytes(&text); if *stream == 18 { - text = format!("runsystem({text})...disabled.\n"); + let mut message = b"runsystem(".to_vec(); + message.extend_from_slice(&bytes); + message.extend_from_slice(b")...disabled.\n"); + bytes = message; } else { - text.push('\n'); + bytes.push(b'\n'); } if (0..16).contains(stream) { self.reads.insert(Dependency::OutputStream(*stream as u8)); } if (0..16).contains(stream) && self.io.outputs.contains(&(*stream as u8)) { files - .write_out(*stream as u8, &text) + .write_out_bytes(*stream as u8, &bytes) .map_err(|e| self.error(e, node.span))?; } else { let destination = if matches!(*stream, 17 | 18) { @@ -3175,11 +3183,11 @@ impl Executor { WriteDestination::TerminalAndLog }; files - .diagnostic(destination, &text) + .diagnostic_bytes(destination, &bytes) .map_err(|e| self.error(e, node.span))?; self.events.push(Event::Write { destination, - text, + text: super::byte_translation::diagnostic_text(&bytes), span: node.span, }); } @@ -3261,27 +3269,33 @@ impl Executor { /// terminal/log/file printers encode ASCII controls unless newlinechar /// selects that code as a physical output line break. fn external_print(&mut self, text: &str) -> std::string::String { + super::byte_translation::diagnostic_text(&self.external_print_bytes(text)) + } + + fn external_print_bytes(&mut self, text: &str) -> Vec { self.reads.insert(Dependency::NewLineChar); let newline = u8::try_from(self.state.newlinechar).ok().map(char::from); - let mut printed = std::string::String::new(); + let byte_mode = self.state.input_profile() == super::InputProfile::TeX8Bit; + let table = self.state.byte_translation.as_deref().filter(|_| byte_mode); + let mut bytes = Vec::with_capacity(text.len()); for c in text.chars() { if Some(c) == newline { - printed.push('\n'); - } else if self.state.input_profile() == super::InputProfile::TeX8Bit - && (c as u32) >= 128 - && (c as u32) <= 255 + bytes.push(b'\n'); + } else if let Some(table) = table + && let Ok(value) = u8::try_from(c as u32) { - printed.push_str(&super::context::encoded_character(c)); - } else if c < ' ' { - printed.push_str("^^"); - printed.push(char::from(c as u8 + 64)); - } else if c == '\u{7f}' { - printed.push_str("^^?"); + if table.printable(value) { + bytes.push(table.output(value)); + } else { + bytes.extend(super::context::encoded_character(c).bytes().map(|b| table.output(b))); + } + } else if c < ' ' || c == '\u{7f}' || (byte_mode && ('\u{80}'..='\u{ff}').contains(&c)) { + bytes.extend_from_slice(super::context::encoded_character(c).as_bytes()); } else { - printed.push(c); + bytes.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()); } } - printed + bytes } fn meaning_string(&mut self, token: &Token) -> Result { self.reads.insert(Dependency::EscapeChar); @@ -4174,7 +4188,8 @@ impl Executor { Message | Errmessage => { let expanded = self.scan_expanded_group(files)?; let text = self.token_list_text(&expanded); - let text = self.external_print(&text); + let bytes = self.external_print_bytes(&text); + let text = super::byte_translation::diagnostic_text(&bytes); if primitive == Errmessage { let mut error = self.error( format!("TeX errmessage: {text}"), @@ -4191,7 +4206,7 @@ impl Executor { return Err(error); } files - .observe_message(&text) + .observe_message_bytes(&bytes) .map_err(|e| self.error(e, token.span))?; self.events.push(Event::Message { text, diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index a21a8a0..c3cded3 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -16,9 +16,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 96; -const COMPATIBLE_SCHEMAS: [u32; 62] = [ - 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, 93, 94, 95, SCHEMA, +const SCHEMA: u32 = 97; +const COMPATIBLE_SCHEMAS: [u32; 63] = [ + 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, 93, 94, 95, 96, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 0feeca0..b7a33c1 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -1,6 +1,8 @@ //! Route-D-owned TeX execution. No semantic renderer, source rewriting or VM //! adapter participates in this path. Unsupported commands are errors. mod boxes; +mod byte_translation; +pub use byte_translation::ByteTranslation; mod cancellation; mod case; mod context; @@ -347,6 +349,9 @@ pub trait SourceProvider { fn observe_message(&mut self, _text: &str) -> Result<(), String> { Ok(()) } + fn observe_message_bytes(&mut self, text: &[u8]) -> Result<(), String> { + self.observe_message(&byte_translation::diagnostic_text(text)) + } /// Optional live observer for retained engine diagnostics. Unlike an /// explicit write, a pure library consumer can inspect the typed event. fn observe_diagnostic( @@ -422,12 +427,20 @@ pub trait SourceProvider { fn write_out(&mut self, _stream: u8, _text: &str) -> Result<(), String> { Err("host output streams unavailable".into()) } + /// Hosts that persist byte-mode TeX output must accept arbitrary bytes. + fn write_out_bytes(&mut self, stream: u8, bytes: &[u8]) -> Result<(), String> { + let text = std::str::from_utf8(bytes).map_err(|_| "host output stream requires UTF-8")?; + self.write_out(stream, text) + } fn close_out(&mut self, _stream: u8) -> Result<(), String> { Err("host output streams unavailable".into()) } fn diagnostic(&mut self, _destination: WriteDestination, _text: &str) -> Result<(), String> { Err("host diagnostic sink unavailable".into()) } + fn diagnostic_bytes(&mut self, destination: WriteDestination, bytes: &[u8]) -> Result<(), String> { + self.diagnostic(destination, &byte_translation::diagnostic_text(bytes)) + } } pub struct NoFiles; diff --git a/crates/texrra-tex-core/src/execution/mouth.rs b/crates/texrra-tex-core/src/execution/mouth.rs index f2a8898..a62a236 100644 --- a/crates/texrra-tex-core/src/execution/mouth.rs +++ b/crates/texrra-tex-core/src/execution/mouth.rs @@ -497,7 +497,11 @@ impl Mouth { self.line = match self.profile.characters(&self.data[start..trimmed]) { Ok(characters) => characters .map(|(index, value)| Character { - value, + value: if matches!(self.line_breaks, LineBreaks::Generated(_)) { + value + } else { + state.translate_input_character(value) + }, start: start + index, end: start + index + self.profile.width(value), }) diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 206d3f5..2dc7609 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -748,6 +748,8 @@ pub struct State { initex: bool, #[serde(default)] input_profile: super::InputProfile, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(super) byte_translation: Option>, #[serde(default)] pub(super) xe_default_encoding: super::xe_encoding::Encoding, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -977,6 +979,7 @@ impl Default for State { pdftex_revision: PdftexRevision::R24, initex: false, input_profile: super::InputProfile::default(), + byte_translation: None, xe_default_encoding: super::xe_encoding::Encoding::Auto, xe_line_break_locale: None, endlinechar: 13, @@ -1987,6 +1990,15 @@ impl State { pub fn input_profile(&self) -> super::InputProfile { self.input_profile } + pub(super) fn translate_input_character(&self, value: char) -> char { + if let Some(table) = &self.byte_translation + && self.input_profile == super::InputProfile::TeX8Bit + && let Ok(byte) = u8::try_from(value as u32) + { + return char::from(table.input(byte)); + } + value + } pub fn catcode(&self, character: char) -> CatCode { self.catcodes .get(&character) diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 9a928d2..cc5aba9 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -819,6 +819,51 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。 [原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492) [原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696) +### pdfTeX 字节输入与写出的 TCX 字符表 + +官方 BibLaTeX 20-indexing-single.tex 使用未修改的文档和文献库。 +原生首轮的 .bcf、.aux、.idx、一页光栅及 12 个词框与参考一致。 +两端独立运行实际 Biber 2.22,得出相同的 203,554 字节 .bbl。 +原生读取自身的 .bbl 复编,六页的全部词框已一致。 +旧版 .idx 八位字符写成 ^^ 转义,208 条中有 19 条不同。 +最早差异位于第 5 条,MakeIndex 需要实际字节排序。 +差异与两端输入及输出指纹保存在 +target/p3-actual-biber/pre-tcx-audit.json。 + +TeX 8-bit 作业可通过 --translate-file 指定实际 TCX 文件, +例如发行版 pdfLaTeX 的 cp227.tcx。物理读取保留原字节偏移, +读取字符先映射至内部代码。常规 \write 和 \message 按表中的 +可打印状态和输出映射传送实际字节,受 \newlinechar 和真实 +流状态控制。二进制写出进入既有文件效果记录和检查点重放。 +实际表作为版本化资源读取,schema97 镜像保存生效的表并继续 +兼容旧镜像。后续继续核对文件名和上下文诊断的字节通路。 +[Web2C 上游字符表实现](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/lib/texmfmp.c) + +实际 cp227 的写出文件和消息字节与 pdfTeX 一致。非恒等映射 +对照覆盖读入字符数值、可打印与不可打印标志、\readline、 +延迟写出、日志及换行字符。七项作业 I/O 回归通过。 +用独立小格式转储和重新加载证实 schema97 保留真实映射。 + +跨文件编辑复用 127 步和五次实际宿主调用,其中包含原始字节 +写出,只更新第 2 页。修改同一路径下的字符表使旧检查点失效, +改变生成文件字节且预览保持一致。两个有效修订的文件、PDF、 +测量页面、SVG 和来源映射与独立全量一致。 + +按同一实际 aux 初态复编后,六页的 2,137 个词框和 .bcf、.bbl、 +.idx、.aux 一致。全部 208 条索引直接用于 MakeIndex,得到与参考 +字节相同的 .ind 和 .ilg。后续两轮原生 LaTeX 生成九页,逐轮 +.aux、.bcf、.bbl、.idx 一致。最终前六页灰度光栅一致。 +第 7–9 页的索引正文仍有断行差异,最早出现在第 7 页右栏, +la tradition grècque 的词落到不同的行。保留原页和词框, +下一步对照实际索引条目的段落参数、行宽及断行代价。 + +首轮回执 target/p3-actual-biber/pass-1-audit.json 的 SHA-256 +为 7d8d8c571746e6797ba3574e0a421ec7247981307f05352baba82124b029aa60。 +TCX 及相同初态续编回执 target/p3-pdftex-write-bytes/receipt.json +的 SHA-256 为 c9fc43b943d60d2043cecfad67da0f0ec54c8c18d6f43abbc2f91b3b4617f60f。 +末轮对照 target/p3-actual-biber/final-comparison.json 的 SHA-256 +为 9814ecc8b0c5be200df5abc81b8db0f40bdc76a762d4803af84d0598affbec2b。 + ### 实际 MakeIndex 多轮作业与索引文件修订 原样 makeidx.sty 与 hyperref 在实际 pdfLaTeX 镜像下执行。 diff --git a/src/main.rs b/src/main.rs index 8113434..2b20b0d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,7 +30,7 @@ fn run() -> Result<(), String> { let mut args = env::args().skip(1); let Some(command) = args.next() else { return Err( - "usage: texrra serve [input.tex] [port] | texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode|xetex] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf|output.dvi]".into(), + "usage: texrra serve [input.tex] [port] | texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode|xetex] [--translate-file FILE] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf|output.dvi]".into(), ); }; if command == "native" { @@ -49,6 +49,7 @@ fn run() -> Result<(), String> { let mut generated_initial = None; let mut observe_generated_initial = false; let mut input_policy_explicit = false; + let mut translation_file = None; let mut input_policy = texrra_tex_core::resources::InputPolicy::Project; let input = loop { match args.next().as_deref() { @@ -60,6 +61,11 @@ fn run() -> Result<(), String> { _ => return Err("--input-profile requires tex8bit, unicode or xetex".into()), }; } + Some("--translate-file") => { + translation_file = Some(PathBuf::from( + args.next().ok_or("--translate-file requires a TCX filename")?, + )); + } Some("--job") => native_job_target = true, Some("--initex") => initex = true, Some("--etex") => etex = true, @@ -146,7 +152,7 @@ fn run() -> Result<(), String> { .map(PathBuf::from) .unwrap_or_else(|| input.with_extension(if dump_format { "tfx" } else { "pdf" })); if args.next().is_some() { - return Err("usage: texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode|xetex] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf|output.dvi]".into()); + return Err("usage: texrra native [--job] [--initex] [--etex] [--dump-format | --load-format FILE] [--step-limit N] [--input-profile tex8bit|unicode|xetex] [--translate-file FILE] [--texmf-root DIR] [--input-policy tex|project] [--project-snapshot FILE] [--generated-initial JSON | --observe-generated-initial] [--resource-manifest JSON] [--layout-manifest JSON] [--failure-manifest JSON] input.tex [output.pdf|output.dvi]".into()); } let diagnostic = native_compile( &input, @@ -162,6 +168,7 @@ fn run() -> Result<(), String> { observe_generated_initial, input_policy, input_profile, + translation_file.as_deref(), native_job_target, dump_format, load_format.as_deref(), @@ -245,6 +252,7 @@ fn native_compile( observe_generated_initial: bool, input_policy: texrra_tex_core::resources::InputPolicy, input_profile: texrra_tex_core::execution::InputProfile, + translation_file: Option<&Path>, native_job_target: bool, dump_format: bool, load_format: Option<&Path>, @@ -299,6 +307,7 @@ fn native_compile( }; request.etex = etex; request.input_profile = input_profile; + request.translation_file = translation_file.map(Path::to_owned); request.limits = limits; request.resource_manifest = manifest.map(Path::to_owned); request.layout_manifest = layout_manifest.map(Path::to_owned); diff --git a/src/native.rs b/src/native.rs index a5f6e49..b109eb2 100644 --- a/src/native.rs +++ b/src/native.rs @@ -65,6 +65,7 @@ pub struct CompileRequest { pub target: Target, pub etex: bool, pub input_profile: InputProfile, + pub translation_file: Option, pub time: JobTime, pub limits: Limits, pub resource_manifest: Option, @@ -164,6 +165,7 @@ impl CompileRequest { target: Target::Shipouts, etex: false, input_profile: InputProfile::TeX8Bit, + translation_file: None, time, limits: Limits::default(), resource_manifest: None, @@ -336,6 +338,8 @@ pub struct AttemptRequest { pub target: Target, pub etex: bool, pub input_profile: InputProfile, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub translation_file: Option, pub time: JobTime, pub limits: Limits, pub resource_manifest: Option, @@ -358,6 +362,7 @@ impl From<&CompileRequest> for AttemptRequest { target: r.target, etex: r.etex, input_profile: r.input_profile, + translation_file: r.translation_file.clone(), time: r.time, limits: r.limits, resource_manifest: r.resource_manifest.clone(), @@ -784,6 +789,14 @@ fn prepare_checked( } else { state }; + let translation = request.translation_file.as_ref().map(|name| { + if request.input_profile != InputProfile::TeX8Bit { + return Err("a TCX file requires the TeX 8-bit profile".to_owned()); + } + let loaded = world.read_shared(ResourceKind::Tex, &name.to_string_lossy(), &path)?; + texrra_tex_core::execution::ByteTranslation::from_tcx(&loaded.data) + .map_err(|e| format!("TCX {}: {e}", loaded.version.path.display())) + }).transpose()?; let (executor, format_preparation) = if let Entry::Format(name) = &request.entry { let loaded = world.read_shared(ResourceKind::Tex, &name.display().to_string(), &path)?; @@ -896,6 +909,10 @@ fn prepare_checked( (kernel == KernelPreparation::Fresh).then(|| Executor::new(state, request.limits)); (executor, None) }; + let executor = match (executor, translation) { + (Some(executor), Some(table)) => Some(executor.with_byte_translation(table)), + (executor, _) => executor, + }; check(cancellation)?; Ok((path, source, executor, output, format_preparation)) })(); diff --git a/src/native_checkpoint_guard.rs b/src/native_checkpoint_guard.rs index c2e01fe..49db48c 100644 --- a/src/native_checkpoint_guard.rs +++ b/src/native_checkpoint_guard.rs @@ -713,6 +713,7 @@ impl PrefixInputGuard { || old.target != request.target || old.etex != request.etex || old.input_profile != request.input_profile + || old.translation_file != request.translation_file || old.time != request.time || old.limits != request.limits || old.terminal != request.terminal diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index b5d1efc..174a283 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -222,6 +222,10 @@ impl SourceProvider for RecordingHost<'_> { let text = text.to_owned(); call!(self, observe_message(&text)) } + fn observe_message_bytes(&mut self, bytes: &[u8]) -> Result<(), String> { + let bytes = bytes.to_owned(); + call!(self, observe_message_bytes(&bytes)) + } fn observe_diagnostic( &mut self, destination: WriteDestination, @@ -282,6 +286,10 @@ impl SourceProvider for RecordingHost<'_> { let text = text.to_owned(); call!(self, write_out(stream, &text)) } + fn write_out_bytes(&mut self, stream: u8, bytes: &[u8]) -> Result<(), String> { + let bytes = bytes.to_owned(); + call!(self, write_out_bytes(stream, &bytes)) + } fn close_out(&mut self, stream: u8) -> Result<(), String> { call!(self, close_out(stream)) } @@ -289,6 +297,10 @@ impl SourceProvider for RecordingHost<'_> { let text = text.to_owned(); call!(self, diagnostic(destination, &text)) } + fn diagnostic_bytes(&mut self, destination: WriteDestination, bytes: &[u8]) -> Result<(), String> { + let bytes = bytes.to_owned(); + call!(self, diagnostic_bytes(destination, &bytes)) + } } fn digest(bytes: &[u8]) -> String { diff --git a/src/native_job.rs b/src/native_job.rs index 2e1fe21..74a5d05 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -1066,6 +1066,23 @@ impl Files { text: &str, start_line: bool, ) -> Result<(), String> { + self.emit_diagnostic_bytes(destination, text.as_bytes(), start_line) + } + + fn emit_diagnostic_bytes( + &mut self, + destination: WriteDestination, + bytes: &[u8], + start_line: bool, + ) -> Result<(), String> { + let column = |previous| { + let previous = if start_line { 0 } else { previous }; + match std::str::from_utf8(bytes) { + Ok(text) => output_column(previous, text), + Err(_) => bytes.iter().rposition(|&b| b == b'\n') + .map_or(previous + bytes.len(), |at| bytes.len() - at - 1), + } + }; if destination != WriteDestination::TerminalOnly { if self.log.is_none() { self.log = Some( @@ -1081,17 +1098,16 @@ impl Files { if start_line && self.log_column != 0 { log.write_all(b"\n").map_err(|e| e.to_string())?; } - log.write_all(text.as_bytes()) - .map_err(|e| format!("native log: {e}"))?; - self.log_column = output_column(if start_line { 0 } else { self.log_column }, text); + log.write_all(bytes).map_err(|e| format!("native log: {e}"))?; + self.log_column = column(self.log_column); } if self.terminal_sink && self.terminal_enabled && destination != WriteDestination::Log { + let mut terminal = io::stderr().lock(); if start_line && self.terminal_column != 0 { - eprintln!(); + terminal.write_all(b"\n").map_err(|e| e.to_string())?; } - eprint!("{text}"); - self.terminal_column = - output_column(if start_line { 0 } else { self.terminal_column }, text); + terminal.write_all(bytes).map_err(|e| e.to_string())?; + self.terminal_column = column(self.terminal_column); } Ok(()) } @@ -1615,6 +1631,9 @@ impl SourceProvider for Files { fn observe_message(&mut self, text: &str) -> Result<(), String> { self.emit_diagnostic(WriteDestination::TerminalAndLog, text, false) } + fn observe_message_bytes(&mut self, bytes: &[u8]) -> Result<(), String> { + self.emit_diagnostic_bytes(WriteDestination::TerminalAndLog, bytes, false) + } fn observe_diagnostic_pair(&mut self, log: &str, terminal: &str) -> Result<(), String> { if self.log_column != 0 || self.terminal_column != 0 { self.emit_diagnostic(WriteDestination::TerminalAndLog, "\n", false)?; @@ -1871,13 +1890,16 @@ impl SourceProvider for Files { result } fn write_out(&mut self, stream: u8, text: &str) -> Result<(), String> { + self.write_out_bytes(stream, text.as_bytes()) + } + fn write_out_bytes(&mut self, stream: u8, bytes: &[u8]) -> Result<(), String> { let Some(output) = self.outputs.get_mut(&stream) else { let error = "host output stream is not open".to_owned(); self.stream_io.push(StreamEffect::Write { stream, handle: None, accepted_before: None, - requested: std::sync::Arc::from(text.as_bytes()), + requested: std::sync::Arc::from(bytes), accepted: 0, attempts: Vec::new(), error: Some(error.clone()), @@ -1885,7 +1907,7 @@ impl SourceProvider for Files { return Err(error); }; let before = output.accepted; - let transfer = native_stream::write_all(&mut output.file, text.as_bytes()); + let transfer = native_stream::write_all(&mut output.file, bytes); output.accepted += transfer.accepted as u64; let error = transfer .error @@ -1894,7 +1916,7 @@ impl SourceProvider for Files { stream, handle: Some(output.handle), accepted_before: Some(before), - requested: std::sync::Arc::from(text.as_bytes()), + requested: std::sync::Arc::from(bytes), accepted: transfer.accepted as u64, attempts: transfer.attempts, error: error.clone(), @@ -1935,6 +1957,9 @@ impl SourceProvider for Files { fn diagnostic(&mut self, destination: WriteDestination, text: &str) -> Result<(), String> { self.emit_diagnostic(destination, text, true) } + fn diagnostic_bytes(&mut self, destination: WriteDestination, bytes: &[u8]) -> Result<(), String> { + self.emit_diagnostic_bytes(destination, bytes, true) + } } #[derive(PartialEq, Eq)] diff --git a/tests/native_job_io.rs b/tests/native_job_io.rs index 07f81ea..10d86b6 100644 --- a/tests/native_job_io.rs +++ b/tests/native_job_io.rs @@ -70,6 +70,98 @@ const CASES: &[(&str, &str)] = &[ ), ]; +#[test] +fn tcx_streams_match_pdftex_for_nonidentity_input_and_raw_output() { + let root = directory(); + let native = root.join("native"); + let reference = root.join("reference"); + let mut source = br"\catcode123=1 \catcode125=2 \catcode94=7 +\catcode144=12 \catcode145=12 \catcode169=12 +\newlinechar=-1 \endlinechar=-1 +\immediate\openout0=result.dat +\immediate\write0{CODE=\number" + .to_vec(); + source.push(96); // TeX alphabetic constant introducer + source.push(0x80); + source.extend_from_slice( + br"; PRINT=^^90; HIDDEN=^^91} +\openin1=data.txt +\readline1 to\line +\immediate\write0{DATA=\line} +\newlinechar=169 +\shipout\hbox{\write0{LATE^^a9^^90}\vrule width1pt height1pt} +\message{MESSAGE-^^90} +\immediate\write17{LOG-^^90} +\immediate\closeout0 +\end +", + ); + for side in [&native, &reference] { + fs::create_dir(side).unwrap(); + fs::write(side.join("probe.tex"), &source).unwrap(); + fs::write(side.join("data.txt"), [0x80, b'\n']).unwrap(); + fs::write(side.join("table.tcx"), b"0x80 0x90 1\n0x97 0x91 0\n").unwrap(); + } + let ran = Command::new("pdftex") + .args([ + "-ini", + "-etex", + "-interaction=nonstopmode", + "-halt-on-error", + ]) + .arg(format!( + "-translate-file={}", + reference.join("table.tcx").display() + )) + .arg("probe.tex") + .current_dir(&reference) + .output() + .unwrap(); + assert!( + ran.status.success(), + "{}", + String::from_utf8_lossy(&ran.stdout) + ); + let ran = Command::new(env!("CARGO_BIN_EXE_texrra")) + .args([ + "native", + "--job", + "--initex", + "--etex", + "--input-profile", + "tex8bit", + "--translate-file", + "table.tcx", + "probe.tex", + "native.pdf", + ]) + .current_dir(&native) + .output() + .unwrap(); + assert!( + ran.status.success(), + "{}", + String::from_utf8_lossy(&ran.stderr) + ); + let bytes = fs::read(native.join("result.dat")).unwrap(); + assert_eq!(bytes, fs::read(reference.join("result.dat")).unwrap()); + assert_eq!( + bytes, + b"CODE=144; PRINT=\x80; HIDDEN=^^91\nDATA=\x80\nLATE\n\x80\n" + ); + for marker in [b"MESSAGE-\x80".as_slice(), b"LOG-\x80".as_slice()] { + for log in [native.join("native.log"), reference.join("probe.log")] { + assert!( + fs::read(log) + .unwrap() + .windows(marker.len()) + .any(|part| part == marker) + ); + } + } + fs::remove_dir_all(root).unwrap(); +} + #[test] fn actual_stream_file_bytes_match_real_pdftex_initex() { let root = directory();