Run cancellable pdfTeX matching in native frontends

This commit is contained in:
gloamxun committed 2026-11-20 16:43:48 +08:00
1 parent 091458d329
commit 6e573dc1ce
21 files changed
+665 -9

No files matched your search

Generated
+1
View File
@@ -1431,6 +1431,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"flate2", "flate2",
"hyphenate", "hyphenate",
"libc",
"lopdf", "lopdf",
"rusttype", "rusttype",
"serde", "serde",
+3
View File
@@ -13,3 +13,6 @@ serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0" serde_json = "1.0"
sha2 = "=0.10.9" sha2 = "=0.10.9"
hyphenate = { path = "../../vendor/hyphenate" } hyphenate = { path = "../../vendor/hyphenate" }
[target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies]
libc = "0.2"
@@ -26,6 +26,8 @@ mod pdf_color;
mod pdf_graphics; mod pdf_graphics;
mod pdf_image; mod pdf_image;
mod pdf_links; mod pdf_links;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub(super) mod pdf_match;
mod quantities; mod quantities;
mod restores; mod restores;
mod scanning; mod scanning;
@@ -215,6 +217,8 @@ pub struct Executor {
io: IoState, io: IoState,
pdf_colors: crate::pdf_device::PdfColorStacks, pdf_colors: crate::pdf_device::PdfColorStacks,
pdf_link_stack: Vec<pdf_links::ActiveLink>, pdf_link_stack: Vec<pdf_links::ActiveLink>,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>, pdf_catalog_tokens: Vec<Token>,
pdf_outlines: Vec<crate::pdf_device::catalog::PdfOutline<Vec<Token>>>, pdf_outlines: Vec<crate::pdf_device::catalog::PdfOutline<Vec<Token>>>,
pdf_outline_payload: usize, pdf_outline_payload: usize,
@@ -377,6 +381,8 @@ impl Executor {
io: IoState::default(), io: IoState::default(),
pdf_colors: Default::default(), pdf_colors: Default::default(),
pdf_link_stack: Vec::new(), pdf_link_stack: Vec::new(),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: None,
pdf_catalog_tokens: Vec::new(), pdf_catalog_tokens: Vec::new(),
pdf_outlines: Vec::new(), pdf_outlines: Vec::new(),
pdf_outline_payload: 0, pdf_outline_payload: 0,
@@ -844,6 +850,13 @@ impl Executor {
}; };
self.print_tokens(result, token)?; self.print_tokens(result, token)?;
} }
Pdfmatch | Pdflastmatch => {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
self.expand_pdf_match(primitive, token, files)?;
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
return self
.fail("pdfTeX regular expressions are unavailable on this host");
}
Pdfcolorstackinit => { Pdfcolorstackinit => {
let stack = self.init_pdf_color_stack(files)?; let stack = self.init_pdf_color_stack(files)?;
self.print_tokens(&stack.to_string(), token)?; self.print_tokens(&stack.to_string(), token)?;
@@ -44,7 +44,7 @@ impl Executor {
} }
} }
fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> { pub(super) fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> {
let tokens = self.scan_pdf_tokens(files)?; let tokens = self.scan_pdf_tokens(files)?;
self.pdf_token_bytes(&tokens) self.pdf_token_bytes(&tokens)
} }
@@ -0,0 +1,218 @@
use super::*;
use std::ffi::{CString, c_int};
use std::mem::MaybeUninit;
use std::ops::Range;
use std::ptr;
pub(super) struct PdfMatch {
input: Vec<u8>,
captures: Vec<Option<Range<usize>>>,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct RegexRequest {
pub pattern: Vec<u8>,
pub input: Vec<u8>,
pub count: usize,
pub insensitive: bool,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub enum RegexOutcome {
Match(Vec<Option<Range<usize>>>),
NoMatch,
InvalidPattern(String),
}
pub fn match_pdf_regex(request: &RegexRequest) -> Result<RegexOutcome, String> {
match search(
request.pattern.clone(),
request.input.clone(),
request.count,
request.insensitive,
) {
Ok(Some(matched)) => Ok(RegexOutcome::Match(matched.captures)),
Ok(None) => Ok(RegexOutcome::NoMatch),
Err(SearchError::Pattern(message)) => Ok(RegexOutcome::InvalidPattern(message)),
Err(SearchError::Runtime(message)) => Err(message),
}
}
impl Executor {
pub(super) fn expand_pdf_match(
&mut self,
primitive: Primitive,
origin: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if primitive == Primitive::Pdflastmatch {
let index = usize::try_from(self.integer(files)?)
.map_err(|_| self.error("Bad match number", self.current))?;
let text = self
.pdf_last_match
.as_ref()
.and_then(|last| {
let range = last.captures.get(index)?.as_ref()?;
let mut text = format!("{}->", range.start);
text.extend(last.input[range.clone()].iter().copied().map(char::from));
Some(text)
})
.unwrap_or_else(|| String::from("-1->"));
return self.print_tokens(&text, origin);
}
let insensitive = self.keyword("icase", files)?;
let count = if self.keyword("subcount", files)? {
usize::try_from(self.integer(files)?).unwrap_or(10)
} else {
10
};
let pattern = self.scan_pdf_bytes(files)?;
let input = self.scan_pdf_bytes(files)?;
self.check_cancellation()?;
let request = RegexRequest {
pattern,
input,
count,
insensitive,
};
let result = files.match_pdf_regex(&request, self.cancellation.as_ref());
self.check_cancellation()?;
let text = match result.map_err(|message| self.error(message, origin.span))? {
RegexOutcome::Match(captures) => {
let input = as_c_string(request.input).into_bytes();
if captures
.iter()
.flatten()
.any(|range| range.start > range.end || range.end > input.len())
{
return self.fail("regex backend supplied invalid captures");
}
self.pdf_last_match = Some(Arc::new(PdfMatch { input, captures }));
"1"
}
RegexOutcome::NoMatch => {
self.pdf_last_match = None;
"0"
}
RegexOutcome::InvalidPattern(message) => {
files
.observe_diagnostic(
WriteDestination::TerminalAndLog,
&format!("pdfTeX warning: pdftex: \\pdfmatch: {message}\n"),
)
.map_err(|error| self.error(error, origin.span))?;
"-1"
}
};
self.print_tokens(text, origin)
}
}
enum SearchError {
Pattern(String),
Runtime(String),
}
struct CLocale {
active: libc::locale_t,
previous: libc::locale_t,
}
impl CLocale {
fn enter() -> Result<Self, SearchError> {
// The reference engine treats matching as C-locale byte processing.
// Changing only this thread leaves concurrent jobs and the host alone.
let active = unsafe { libc::newlocale(libc::LC_ALL_MASK, c"C".as_ptr(), ptr::null_mut()) };
if active.is_null() {
return Err(SearchError::Runtime("cannot create pdfTeX C locale".into()));
}
let previous = unsafe { libc::uselocale(active) };
if previous.is_null() {
unsafe { libc::freelocale(active) };
return Err(SearchError::Runtime("cannot enter pdfTeX C locale".into()));
}
Ok(Self { active, previous })
}
}
impl Drop for CLocale {
fn drop(&mut self) {
// previous is the still-live locale returned by uselocale above.
unsafe {
libc::uselocale(self.previous);
libc::freelocale(self.active);
}
}
}
struct CompiledRegex(libc::regex_t);
impl Drop for CompiledRegex {
fn drop(&mut self) {
// This wrapper is created only after successful regcomp.
unsafe { libc::regfree(&mut self.0) };
}
}
fn regex_error(code: c_int) -> String {
// An error code can be described without referring to a compiled regex.
let length = unsafe { libc::regerror(code, ptr::null(), ptr::null_mut(), 0) };
let mut message = vec![0u8; length];
unsafe { libc::regerror(code, ptr::null(), message.as_mut_ptr().cast(), length) };
message.pop();
String::from_utf8_lossy(&message).into_owned()
}
fn as_c_string(mut bytes: Vec<u8>) -> CString {
// pdfTeX's makecstring passes the prefix through the first NUL.
if let Some(end) = bytes.iter().position(|&byte| byte == 0) {
bytes.truncate(end);
}
CString::new(bytes).expect("regex bytes were truncated at the first NUL")
}
fn search(
pattern: Vec<u8>,
input: Vec<u8>,
requested: usize,
insensitive: bool,
) -> Result<Option<PdfMatch>, SearchError> {
let _locale = CLocale::enter()?;
let pattern = as_c_string(pattern);
let input = as_c_string(input);
let flags = libc::REG_EXTENDED | if insensitive { libc::REG_ICASE } else { 0 };
let mut regex = MaybeUninit::uninit();
// regcomp initializes the regex storage on success. The pattern is
// NUL-terminated and valid throughout the call.
let status = unsafe { libc::regcomp(regex.as_mut_ptr(), pattern.as_ptr(), flags) };
if status != 0 {
return Err(SearchError::Pattern(regex_error(status)));
}
let regex = CompiledRegex(unsafe { regex.assume_init() });
// Group starts cannot outnumber pattern bytes. Requests beyond that
// bound are observable only as missing captures.
let count = requested.min(pattern.as_bytes().len() + 1);
let mut ranges = vec![
libc::regmatch_t {
rm_so: -1,
rm_eo: -1
};
count
];
// Both C strings and the initialized regex live through the call.
// A zero count asks regexec to skip writing capture positions.
let status = unsafe { libc::regexec(&regex.0, input.as_ptr(), count, ranges.as_mut_ptr(), 0) };
if status != 0 {
return Ok(None);
}
let input = input.into_bytes();
let captures = ranges
.into_iter()
.map(|range| {
let start = usize::try_from(range.rm_so).ok()?;
let end = usize::try_from(range.rm_eo).ok()?;
(start <= end && end <= input.len()).then_some(start..end)
})
.collect();
Ok(Some(PdfMatch { input, captures }))
}
@@ -8,8 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak}, sync::{Arc, Mutex, OnceLock, Weak},
}; };
const SCHEMA: u32 = 28; const SCHEMA: u32 = 31;
const PREVIOUS_SCHEMA: u32 = 27; const COMPATIBLE_SCHEMAS: [u32; 3] = [27, 28, SCHEMA];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
@@ -106,11 +106,11 @@ impl FormatImage {
schema: u32, schema: u32,
engine: String, engine: String,
} }
// Schema 28 adds primitive and node variants. All schema 27 state // The new schemas add primitive or node variants. Previously
// fields and variants remain readable with their original meanings. // published state fields and variants retain their meanings.
let identity: Identity = let identity: Identity =
serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?; serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?;
if !matches!(identity.schema, PREVIOUS_SCHEMA | SCHEMA) || identity.engine != ENGINE { if !COMPATIBLE_SCHEMAS.contains(&identity.schema) || identity.engine != ENGINE {
return Err("incompatible native format image".into()); return Err("incompatible native format image".into());
} }
let image: Self = let image: Self =
@@ -7,6 +7,8 @@ mod context;
mod device; mod device;
mod diagnostics; mod diagnostics;
mod engine; mod engine;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub use engine::pdf_match::{RegexOutcome, RegexRequest, match_pdf_regex};
mod font_catalog; mod font_catalog;
mod fonts; mod fonts;
mod format_image; mod format_image;
@@ -210,6 +212,15 @@ pub struct GeneratedInput {
/// File lookup belongs to the host. Execution never shells out to TeX or /// File lookup belongs to the host. Execution never shells out to TeX or
/// searches a different engine when a file/primitive is absent. /// searches a different engine when a file/primitive is absent.
pub trait SourceProvider { pub trait SourceProvider {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &RegexRequest,
_cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
match_pdf_regex(request)
}
/// Change the TeX diagnostic selector. Mode zero suppresses the terminal. /// Change the TeX diagnostic selector. Mode zero suppresses the terminal.
fn set_interaction_mode(&mut self, _mode: u8) -> Result<(), String> { fn set_interaction_mode(&mut self, _mode: u8) -> Result<(), String> {
Ok(()) Ok(())
@@ -313,6 +313,8 @@ pub enum Primitive {
Atopwithdelims, Atopwithdelims,
Abovewithdelims, Abovewithdelims,
Accent, Accent,
Pdfmatch,
Pdflastmatch,
} }
impl Primitive { impl Primitive {
@@ -363,6 +365,8 @@ impl Primitive {
| Pdfcreationdate | Pdfcreationdate
| Pdftexrevision | Pdftexrevision
| Pdfstrcmp | Pdfstrcmp
| Pdfmatch
| Pdflastmatch
| Pdfcolorstackinit | Pdfcolorstackinit
| Csname | Csname
| Unless | Unless
@@ -920,6 +924,10 @@ impl Default for State {
("pdfcreationdate", Pdfcreationdate), ("pdfcreationdate", Pdfcreationdate),
("pdfshellescape", Pdfshellescape), ("pdfshellescape", Pdfshellescape),
("pdfstrcmp", Pdfstrcmp), ("pdfstrcmp", Pdfstrcmp),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
("pdfmatch", Pdfmatch),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
("pdflastmatch", Pdflastmatch),
("pdfcolorstackinit", Pdfcolorstackinit), ("pdfcolorstackinit", Pdfcolorstackinit),
("pdfcolorstack", Pdfcolorstack), ("pdfcolorstack", Pdfcolorstack),
("pdfsave", Pdfsave), ("pdfsave", Pdfsave),
@@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value = let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 28); assert_eq!(payload["schema"], 31);
let state = State::initex().with_etex(); let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes) let loaded = FormatImage::decode(&bytes)
.unwrap() .unwrap()
@@ -0,0 +1,155 @@
#![cfg(all(target_os = "linux", target_env = "gnu"))]
use std::{fs, process::Command};
use texrra_tex_core::execution::*;
const SOURCE: &str = r#"
\catcode123=1 \catcode125=2 \catcode35=6 \catcode94=7
\def\probe#1{\message{!pdfmatch:#1:end!}}
\probe{before=[\pdflastmatch0]}
\def\dimpat{^([0-9]+([.,][0-9]+)?|[.,][0-9]+)(em|ex|cm|mm|in|pc|pt|dd|cc|bp|sp|nd|nc|px)? *$}
\def\value{12.5pt}
\probe{dim=[\pdfmatch{\dimpat}{\value}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]/[\pdflastmatch3]}
\probe{dim-fail=[\pdfmatch{\dimpat}{wd0}]/[\pdflastmatch0]}
\probe{longest=[\pdfmatch{(a|ab)}{cab}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{leftmost=[\pdfmatch{(a|bcde)}{abcde}]/[\pdflastmatch0]}
\probe{case=[\pdfmatch icase subcount 2{(a)(B)}{xAb}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]}
\probe{invalid=[\pdfmatch{[}{x}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{zero=[\pdfmatch subcount 0{(a)}{xax}]/[\pdflastmatch0]}
\probe{negative=[\pdfmatch subcount -2{(a)}{xax}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{optional=[\pdfmatch{(a)?(b*)}{x}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]}
\begingroup \edef\inside{\pdfmatch{(c)}{abc}}\endgroup
\probe{group=[\pdflastmatch0]/[\pdflastmatch1]}
\begingroup\escapechar=-1 \xdef\bs{\string\\}\endgroup
\probe{gnu-backref=[\pdfmatch{^(a)\bs1$}{aa}]/[\pdflastmatch1]}
\probe{gnu-class=[\pdfmatch{^\bs w+$}{a01}]/[\pdflastmatch0]}
\probe{byte-offset=[\pdfmatch{(q)}{^^c3^^a9q}]/[\pdflastmatch1]}
\def\capturedbyte#1->#2{\number`#2}
\edef\status{\pdfmatch{(.)}{^^ffq}}
\edef\capture{\pdflastmatch0}
\probe{nonutf8=[\status]/[\expandafter\capturedbyte\capture]}
\catcode0=12 \catcode10=12
\probe{nul-text=[\pdfmatch{c}{ab^^00cd}]/[\pdflastmatch0]}
\probe{nul-pattern=[\pdfmatch{a^^00b}{xa}]/[\pdflastmatch0]}
\probe{newline=[\pdfmatch{a.b}{a^^0ab}]}
\end
"#;
fn file(source: &str) -> SourceFile {
SourceFile {
name: "probe.tex".into(),
data: source.as_bytes().to_vec(),
}
}
#[test]
fn pdf_regex_matches_reference_bytes_and_retains_job_local_captures() {
let dir = std::env::temp_dir().join(format!("texrra-pdfmatch-{}", std::process::id()));
fs::create_dir(&dir).unwrap();
fs::write(dir.join("probe.tex"), SOURCE).unwrap();
let reference = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.env("LC_ALL", "C")
.env("max_print_line", "1000")
.current_dir(&dir)
.output()
.unwrap();
assert!(
reference.status.success(),
"{}",
String::from_utf8_lossy(&reference.stdout)
);
let log = fs::read(dir.join("probe.log")).unwrap();
let reference: String = log.into_iter().map(char::from).collect();
let expected: Vec<_> = reference
.split("!pdfmatch:")
.skip(1)
.map(|part| part.split_once(":end!").unwrap().0)
.collect();
assert_eq!(expected.len(), 18);
let native = Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.run(file(SOURCE), &mut NoFiles)
.unwrap();
let actual: Vec<_> = native
.events
.iter()
.filter_map(|event| match event {
Event::Message { text, .. } => text.strip_prefix("!pdfmatch:")?.strip_suffix(":end!"),
_ => None,
})
.collect();
assert_eq!(actual, expected);
let fresh = Executor::new(native.state, Limits::default())
.run(file(r"\message{\pdflastmatch0}\end"), &mut NoFiles)
.unwrap();
assert!(
fresh
.events
.iter()
.any(|event| { matches!(event, Event::Message { text, .. } if text == "-1->") })
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_negative_capture_index_is_a_scan_error() {
let error = Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.run(
file(r"\catcode123=1 \catcode125=2 \message{\pdflastmatch-1}\end"),
&mut NoFiles,
)
.unwrap_err();
assert!(error.message.contains("Bad match number"));
}
#[test]
fn capture_is_restored_after_editing_the_unread_suffix() {
let initial = r"\catcode123=1 \catcode125=2
\edef\status{\pdfmatch{(ab)}{zab}}
\message{original=[\pdflastmatch1]}
\end";
let edited = initial.replace("original", "edited");
let frontier = initial.find("\n\\message").unwrap();
let state = State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit);
let (original, captured) = Executor::new(state.clone(), Limits::default()).run_capturing_entry(
file(initial),
&mut NoFiles,
frontier,
|_| (),
);
original.unwrap();
let (checkpoint, ()) = captured.expect("capture after scanning the match");
let resumed = checkpoint
.resume_after_host_replay(file(&edited), &mut NoFiles, Cancellation::default())
.expect("edited suffix is beyond the checkpoint")
.unwrap();
let full = Executor::new(state, Limits::default())
.run(file(&edited), &mut NoFiles)
.unwrap();
assert_eq!(resumed.events, full.events);
assert!(
resumed
.events
.iter()
.any(|event| matches!(event, Event::Message { text, .. } if text == "edited=[1->ab]"))
);
}
@@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
let original: serde_json::Value = let original: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(original["schema"], 28); assert_eq!(original["schema"], 31);
for (schema, expected) in [ for (schema, expected) in [
(1, "incompatible native format"), (1, "incompatible native format"),
(2, "incompatible native format"), (2, "incompatible native format"),
@@ -365,6 +365,8 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
(27, "glyph_unicode"), (27, "glyph_unicode"),
(28, "glyph_unicode"), (28, "glyph_unicode"),
(29, "incompatible native format"), (29, "incompatible native format"),
(30, "incompatible native format"),
(31, "glyph_unicode"),
] { ] {
let mut payload = original.clone(); let mut payload = original.clone();
payload["schema"] = schema.into(); payload["schema"] = schema.into();
@@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() {
let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value = let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 28); assert_eq!(payload["schema"], 31);
let executor = FormatImage::decode(&bytes) let executor = FormatImage::decode(&bytes)
.unwrap() .unwrap()
.new_job( .new_job(
+41
View File
@@ -1126,6 +1126,47 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode
[原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿) [原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿)
[pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143) [pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143)
### 正常发布入口的可取消 pdfTeX 匹配
原生 `\pdfmatch` 和 `\pdflastmatch` 沿用已独立验证的 GNU 字节匹配。
Linux GNU 的 CLI 和预览通过正在运行的同一个可执行文件启动匹配进程,
支持以应用程序通常的入口部署。匹配结果进入当前作业,检查点保留
捕获,取消会终止并回收实际匹配进程。直接调用低层执行器由宿主
提供匹配,同平台可调用同一个 GNU 实现。
[pdfTeX 的字节匹配](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/utils.c#L762-L853)
实际未修改的 pdflatex.ini 产生 schema31,包含两项匹配原语、文本
重音和官方 firstaid 依赖。继续接受已发布的 schema27/28,保留
拒绝旧模式缺字段及未发布 schema29/30 的回归。匹配、捕获续跑、
格式和拒绝门禁共六项定向通过。只安装单个重命名 CLI 的作业也已
生成实际 PDF,正文验证了左端开始的最长匹配。
原样 arXiv 与 ACL 各55次 GNU 匹配,输入和捕获结果与已保存参考
逐字节一致。两份样稿均推进到 microtype 设置的
`\MT@protrudechars`,该控制序列指向尚待实现的原语
`\pdfprotrudechars`。使用既有 NeurIPS 分支结论,留待相关行为再次变化
或发布验收时复跑。
同一预览程序在旧作业进入真实 GNU 调用后收到新编辑,73.8 ms 后旧
请求返回409,匹配进程已经回收。新作业实际复用824330 / 904081步,
发布 PDF、SVG、来源映射和 aux 与独立的零复用全量结果一致。
一次受控取消时间独立于100 ms可见预览 p95 门禁。
完整候选及回执在 `target/p3-pdfmatch-integrated`,按19份代码、
锁文件和测试的确切指纹合入。
- 真实格式 `format/receipt.json` 为 `3d5ea7373e7a51b1289fb0d970247fc0d7efcaa564b26dea3fe1d119028f150d`
- 单程序发布 `installed-cli/receipt.json` 为 `70e04387ccbf1c76d5a7e40fe4da7fc77174ee70e900a8e60cf3a167c8e951ed`
- 原样模板 `publisher/receipt.json` 为 `40b71c04aa4a6d763c5cdd1f314381ad93ecc94154e91efd475703d3767cdc40`
- 编辑取消 `editor-cancellation/receipt.json` 为 `4a4461efd163723e65bfe814f92b1e737a268a511c008bb369b8e46065b4e0bd`
已为下一处版面能力冻结新 pdfTeX 对照。原样字体的同一段文字在
38 pt 宽度下,模式0/1各两行,模式2一行。五个实际盒包括正负
边缘 kern、嵌套盒和字体代码跨组。回执
`target/p3-pdf-protrusion-reference/frozen/receipt.json` 的 SHA-256 为
`d84266b5e2d731a06755420f7be74e598cb48b5aac4cbc876291f1368156b873`。
[pdfTeX 边缘宽度和节点](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L19387-L19430)
### TeX 输入的默认扩展名候选 ### TeX 输入的默认扩展名候选
默认 TeX 编译在每个搜索目录中为带未知后缀的输入先试附加 `.tex`,并保留 默认 TeX 编译在每个搜索目录中为带未知后缀的输入先试附加 `.tex`,并保留
+9
View File
@@ -424,6 +424,15 @@ Springer LNCS、CVPR 2026 共5份 PDF。成功项的页数、词框和逐轮 aux
`8a5c885e504171e88b6dae499c3403b99ddfe9d2c09b6aff0ef2a14c07ab4c23`。 `8a5c885e504171e88b6dae499c3403b99ddfe9d2c09b6aff0ef2a14c07ab4c23`。
[APS REVTeX](https://journals.aps.org/revtex) [APS REVTeX](https://journals.aps.org/revtex)
### arXiv 与 ACL 的原生微字体匹配
schema31 主线功能通过正常的单程序部署,在原样 arXiv 与 ACL 的
microtype 配置中分别执行55次匹配。实际 GNU 输入和捕获均与既有
pdfTeX 对照字节一致。两项编译随后在实际 `\pdfprotrudechars` 的别名
处停止。之前的 NeurIPS 官方样例在独立候选上同样推进到该边界。
本次主要核对正常部署及编辑取消,复用冻结对照。
[编译与取消证据](P2_M1_PROGRESS.md#正常发布入口的可取消-pdftex-匹配)
### IEEE 双栏期刊与 CVPR 会议的实时会话对照 ### IEEE 双栏期刊与 CVPR 会议的实时会话对照
使用矩阵中同一原样输入、TeX 格式和已验证的字体资源,验证编辑后 使用矩阵中同一原样输入、TeX 格式和已验证的字体资源,验证编辑后
+3
View File
@@ -169,6 +169,9 @@ struct Queue {
} }
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Some(status) = texrra_engine::native::dispatch_pdf_regex_worker() {
std::process::exit(status);
}
let mut args = std::env::args_os().skip(1).map(PathBuf::from); let mut args = std::env::args_os().skip(1).map(PathBuf::from);
let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...]"; let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...]";
let source = args.next().ok_or(usage)?.canonicalize()?; let source = args.next().ok_or(usage)?.canonicalize()?;
+2
View File
@@ -9,5 +9,7 @@ mod native_generated;
mod native_host; mod native_host;
mod native_job; mod native_job;
mod native_preview; mod native_preview;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod native_regex;
mod native_stream; mod native_stream;
pub mod rust_typeset; pub mod rust_typeset;
+3
View File
@@ -17,6 +17,9 @@ mod route_d;
use texrra_engine::rust_typeset; use texrra_engine::rust_typeset;
fn main() { fn main() {
if let Some(status) = texrra_engine::native::dispatch_pdf_regex_worker() {
std::process::exit(status);
}
if let Err(error) = run() { if let Err(error) = run() {
eprintln!("error: {error}"); eprintln!("error: {error}");
process::exit(1); process::exit(1);
+10
View File
@@ -73,6 +73,16 @@ pub struct CompileRequest {
pub terminal: bool, pub terminal: bool,
pub observer: Option<Arc<dyn CompileObserver>>, pub observer: Option<Arc<dyn CompileObserver>>,
} }
/// Register this executable as the isolated pdfTeX matcher and handle its
/// internal worker invocation. Call before parsing application arguments, and
/// exit with the returned status when the invocation was handled.
pub fn dispatch_pdf_regex_worker() -> Option<i32> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
return crate::native_regex::dispatch();
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
None
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompileStage { pub enum CompileStage {
Prepared, Prepared,
+11
View File
@@ -87,6 +87,17 @@ macro_rules! call {
} }
impl SourceProvider for RecordingHost<'_> { impl SourceProvider for RecordingHost<'_> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
// GNU matching consumes only kernel-supplied bytes and is pinned to
// this executable on registered frontends. Its result is kernel state.
self.files.match_pdf_regex(request, cancellation)
}
fn execution_resource_trace(&self) -> Option<&ResourceTrace> { fn execution_resource_trace(&self) -> Option<&ResourceTrace> {
self.files.execution_resource_trace() self.files.execution_resource_trace()
} }
+23
View File
@@ -151,6 +151,8 @@ struct DraftLedger {
pub struct Files { pub struct Files {
world: FileWorld, world: FileWorld,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: Option<crate::native_regex::Worker>,
cwd: PathBuf, cwd: PathBuf,
inputs: BTreeMap<u8, Input>, inputs: BTreeMap<u8, Input>,
outputs: BTreeMap<u8, Output>, outputs: BTreeMap<u8, Output>,
@@ -547,6 +549,8 @@ impl Files {
preparation.phase = HostPreparationPhase::Ready; preparation.phase = HostPreparationPhase::Ready;
Ok(Self { Ok(Self {
world: stored_world.take().unwrap(), world: stored_world.take().unwrap(),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: None,
cwd, cwd,
inputs: BTreeMap::new(), inputs: BTreeMap::new(),
outputs: BTreeMap::new(), outputs: BTreeMap::new(),
@@ -1404,6 +1408,25 @@ pub(crate) fn absolute_output(cwd: &Path, path: &Path) -> Result<PathBuf, String
} }
impl SourceProvider for Files { impl SourceProvider for Files {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
use crate::native_regex::{self, Worker};
if !native_regex::enabled() {
return texrra_tex_core::execution::match_pdf_regex(request);
}
if self.regex_worker.is_none() {
self.regex_worker = Some(Worker::start()?);
}
self.regex_worker
.as_mut()
.expect("native matcher was started")
.request(request, cancellation)
}
fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> { fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> {
Some(self.world.trace()) Some(self.world.trace())
} }
+143
View File
@@ -0,0 +1,143 @@
use std::{
ffi::OsStr,
io::{self, BufRead, BufReader, Write},
process::{Child, Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, Receiver, Sender},
},
thread::{self, JoinHandle},
time::Duration,
};
use texrra_tex_core::execution::{Cancellation, RegexOutcome, RegexRequest, match_pdf_regex};
const WORKER_ARGUMENT: &str = "--internal-pdf-regex-worker";
static WORKER_ENABLED: AtomicBool = AtomicBool::new(false);
pub(crate) fn dispatch() -> Option<i32> {
let mut args = std::env::args_os().skip(1);
if args.next().as_deref() != Some(OsStr::new(WORKER_ARGUMENT)) {
WORKER_ENABLED.store(true, Ordering::Relaxed);
return None;
}
Some(match serve() {
Ok(()) => 0,
Err(error) => {
eprintln!("pdfTeX regex worker: {error}");
1
}
})
}
pub(crate) fn enabled() -> bool {
WORKER_ENABLED.load(Ordering::Relaxed)
}
fn serve() -> Result<(), Box<dyn std::error::Error>> {
let mut input = io::stdin().lock();
let mut output = io::stdout().lock();
let mut request = Vec::new();
loop {
request.clear();
if input.read_until(b'\n', &mut request)? == 0 {
return Ok(());
}
let request: RegexRequest = serde_json::from_slice(&request)?;
serde_json::to_writer(&mut output, &match_pdf_regex(&request))?;
output.write_all(b"\n")?;
output.flush()?;
}
}
pub(crate) struct Worker {
child: Child,
requests: Option<Sender<Vec<u8>>>,
answers: Receiver<Result<RegexOutcome, String>>,
pipe: Option<JoinHandle<()>>,
}
impl Worker {
pub(crate) fn start() -> Result<Self, String> {
// Re-execute the current image, even if an installer has replaced its
// original path since the process opened the project.
let mut child = Command::new("/proc/self/exe")
.arg(WORKER_ARGUMENT)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(|e| format!("pdfTeX regex worker launch: {e}"))?;
let mut input = child.stdin.take().expect("worker stdin is piped");
let mut output = BufReader::new(child.stdout.take().expect("worker stdout is piped"));
let (requests, waiting) = mpsc::channel::<Vec<u8>>();
let (answer, answers) = mpsc::sync_channel(1);
let pipe = thread::spawn(move || {
let mut response = Vec::new();
for request in waiting {
let result = (|| {
input.write_all(&request).map_err(|e| e.to_string())?;
input.write_all(b"\n").map_err(|e| e.to_string())?;
response.clear();
if output
.read_until(b'\n', &mut response)
.map_err(|e| e.to_string())?
== 0
{
return Err("pdfTeX regex worker closed its response pipe".into());
}
serde_json::from_slice::<Result<RegexOutcome, String>>(&response)
.map_err(|e| format!("pdfTeX regex response: {e}"))?
})();
if answer.send(result).is_err() {
break;
}
}
});
Ok(Self {
child,
requests: Some(requests),
answers,
pipe: Some(pipe),
})
}
pub(crate) fn request(
&mut self,
request: &RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
let payload = serde_json::to_vec(request).map_err(|e| e.to_string())?;
self.requests
.as_ref()
.ok_or("pdfTeX regex worker has stopped")?
.send(payload)
.map_err(|_| "pdfTeX regex worker has stopped")?;
loop {
if cancellation.is_some_and(Cancellation::is_cancelled) {
self.stop();
return Err("native compilation cancelled".into());
}
match self.answers.recv_timeout(Duration::from_millis(2)) {
Ok(result) => return result,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("pdfTeX regex worker lost its response pipe".into());
}
}
}
}
fn stop(&mut self) {
self.requests.take();
if let Some(pipe) = self.pipe.take() {
let _ = self.child.kill();
let _ = self.child.wait();
let _ = pipe.join();
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.stop();
}
}