From 31bf50806e6e31bbc6dfe57ff680791c560060db Mon Sep 17 00:00:00 2001 From: GloamXun Date: Thu, 19 Nov 2026 22:44:42 +0800 Subject: [PATCH] Prototype cancellable GNU matching in native compilation sessions --- Cargo.lock | 1 + crates/texrra-tex-core/Cargo.toml | 3 + .../texrra-tex-core/src/execution/engine.rs | 13 ++ .../src/execution/engine/pdf_catalog.rs | 2 +- .../src/execution/engine/pdf_match.rs | 218 ++++++++++++++++++ .../src/execution/format_image.rs | 2 +- crates/texrra-tex-core/src/execution/mod.rs | 18 +- crates/texrra-tex-core/src/execution/state.rs | 8 + .../tests/execution_pdf_match.rs | 155 +++++++++++++ src/bin/pdf_regex_worker.rs | 25 ++ src/lib.rs | 2 + src/native_checkpoint_probe.rs | 21 +- src/native_job.rs | 25 ++ src/native_regex.rs | 99 ++++++++ 14 files changed, 580 insertions(+), 12 deletions(-) create mode 100644 crates/texrra-tex-core/src/execution/engine/pdf_match.rs create mode 100644 crates/texrra-tex-core/tests/execution_pdf_match.rs create mode 100644 src/bin/pdf_regex_worker.rs create mode 100644 src/native_regex.rs diff --git a/Cargo.lock b/Cargo.lock index 1ce0230..c9eb2ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1431,6 +1431,7 @@ version = "0.1.0" dependencies = [ "flate2", "hyphenate", + "libc", "lopdf", "rusttype", "serde", diff --git a/crates/texrra-tex-core/Cargo.toml b/crates/texrra-tex-core/Cargo.toml index 9441f2a..d52e5c3 100644 --- a/crates/texrra-tex-core/Cargo.toml +++ b/crates/texrra-tex-core/Cargo.toml @@ -13,3 +13,6 @@ serde = { version = "1.0", features = ["derive", "rc"] } serde_json = "1.0" sha2 = "=0.10.9" hyphenate = { path = "../../vendor/hyphenate" } + +[target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies] +libc = "0.2" diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 5ae3551..1ade568 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -26,6 +26,8 @@ mod pdf_color; mod pdf_graphics; mod pdf_image; mod pdf_links; +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub(super) mod pdf_match; mod quantities; mod restores; mod scanning; @@ -215,6 +217,8 @@ pub struct Executor { io: IoState, pdf_colors: crate::pdf_device::PdfColorStacks, pdf_link_stack: Vec, + #[cfg(all(target_os = "linux", target_env = "gnu"))] + pdf_last_match: Option>, pdf_catalog_tokens: Vec, pdf_outlines: Vec>>, pdf_outline_payload: usize, @@ -377,6 +381,8 @@ impl Executor { io: IoState::default(), pdf_colors: Default::default(), pdf_link_stack: Vec::new(), + #[cfg(all(target_os = "linux", target_env = "gnu"))] + pdf_last_match: None, pdf_catalog_tokens: Vec::new(), pdf_outlines: Vec::new(), pdf_outline_payload: 0, @@ -844,6 +850,13 @@ impl Executor { }; 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 => { let stack = self.init_pdf_color_stack(files)?; self.print_tokens(&stack.to_string(), token)?; diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs b/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs index 929d7a1..59f2e85 100644 --- a/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs +++ b/crates/texrra-tex-core/src/execution/engine/pdf_catalog.rs @@ -44,7 +44,7 @@ impl Executor { } } - fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result, Error> { + pub(super) fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result, Error> { let tokens = self.scan_pdf_tokens(files)?; self.pdf_token_bytes(&tokens) } diff --git a/crates/texrra-tex-core/src/execution/engine/pdf_match.rs b/crates/texrra-tex-core/src/execution/engine/pdf_match.rs new file mode 100644 index 0000000..c673817 --- /dev/null +++ b/crates/texrra-tex-core/src/execution/engine/pdf_match.rs @@ -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, + captures: Vec>>, +} + +#[derive(serde::Serialize, serde::Deserialize)] +pub struct RegexRequest { + pub pattern: Vec, + pub input: Vec, + pub count: usize, + pub insensitive: bool, +} + +#[derive(serde::Serialize, serde::Deserialize)] +pub enum RegexOutcome { + Match(Vec>>), + NoMatch, + InvalidPattern(String), +} + +pub fn match_pdf_regex(request: &RegexRequest) -> Result { + 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 { + // 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) -> 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, + input: Vec, + requested: usize, + insensitive: bool, +) -> Result, 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(®ex.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 })) +} diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index ead19be..0f87d2d 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,7 +8,7 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 27; +const SCHEMA: u32 = 30; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 7c28040..375bd5e 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -7,6 +7,8 @@ mod context; mod device; mod diagnostics; mod engine; +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub use engine::pdf_match::{RegexOutcome, RegexRequest, match_pdf_regex}; mod font_catalog; mod fonts; mod format_image; @@ -210,6 +212,15 @@ pub struct GeneratedInput { /// File lookup belongs to the host. Execution never shells out to TeX or /// searches a different engine when a file/primitive is absent. pub trait SourceProvider { + #[cfg(all(target_os = "linux", target_env = "gnu"))] + fn match_pdf_regex( + &mut self, + request: &RegexRequest, + _cancellation: Option<&Cancellation>, + ) -> Result { + match_pdf_regex(request) + } + /// Change the TeX diagnostic selector. Mode zero suppresses the terminal. fn set_interaction_mode(&mut self, _mode: u8) -> Result<(), String> { Ok(()) @@ -749,14 +760,13 @@ impl Execution { } NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) - | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => { - items.push(VerticalItem::StretchGlue(VerticalGlue::with_order( + | NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => items + .push(VerticalItem::StretchGlue(VerticalGlue::with_order( bp(g.width as i64), bp(g.stretch.amount as i64), bp(g.shrink.amount as i64), g.stretch.order, - ))) - } + ))), NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => { items.push(VerticalItem::Glue(bp(*n as i64))) } diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index a038cbe..05bfa80 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -102,6 +102,8 @@ pub enum Primitive { Ifpdfabsnum, Ifpdfabsdim, Pdfstrcmp, + Pdfmatch, + Pdflastmatch, Pdfcolorstackinit, Pdfcolorstack, Pdfsave, @@ -362,6 +364,8 @@ impl Primitive { | Pdfcreationdate | Pdftexrevision | Pdfstrcmp + | Pdfmatch + | Pdflastmatch | Pdfcolorstackinit | Csname | Unless @@ -918,6 +922,10 @@ impl Default for State { ("pdfcreationdate", Pdfcreationdate), ("pdfshellescape", Pdfshellescape), ("pdfstrcmp", Pdfstrcmp), + #[cfg(all(target_os = "linux", target_env = "gnu"))] + ("pdfmatch", Pdfmatch), + #[cfg(all(target_os = "linux", target_env = "gnu"))] + ("pdflastmatch", Pdflastmatch), ("pdfcolorstackinit", Pdfcolorstackinit), ("pdfcolorstack", Pdfcolorstack), ("pdfsave", Pdfsave), diff --git a/crates/texrra-tex-core/tests/execution_pdf_match.rs b/crates/texrra-tex-core/tests/execution_pdf_match.rs new file mode 100644 index 0000000..e547279 --- /dev/null +++ b/crates/texrra-tex-core/tests/execution_pdf_match.rs @@ -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]")) + ); +} diff --git a/src/bin/pdf_regex_worker.rs b/src/bin/pdf_regex_worker.rs new file mode 100644 index 0000000..0595503 --- /dev/null +++ b/src/bin/pdf_regex_worker.rs @@ -0,0 +1,25 @@ +#[cfg(all(target_os = "linux", target_env = "gnu"))] +fn main() -> Result<(), Box> { + use std::io::{self, BufRead, Write}; + use texrra_tex_core::execution::{RegexRequest, match_pdf_regex}; + + 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()?; + } +} + +#[cfg(not(all(target_os = "linux", target_env = "gnu")))] +fn main() -> std::process::ExitCode { + eprintln!("pdfTeX regular expressions require the GNU backend"); + std::process::ExitCode::FAILURE +} diff --git a/src/lib.rs b/src/lib.rs index 479cb9a..d978469 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,5 +9,7 @@ mod native_generated; mod native_host; mod native_job; mod native_preview; +#[cfg(all(target_os = "linux", target_env = "gnu"))] +mod native_regex; mod native_stream; pub mod rust_typeset; diff --git a/src/native_checkpoint_probe.rs b/src/native_checkpoint_probe.rs index 8938ebe..6513d60 100644 --- a/src/native_checkpoint_probe.rs +++ b/src/native_checkpoint_probe.rs @@ -83,6 +83,15 @@ macro_rules! call { } 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 { + self.files.match_pdf_regex(request, cancellation) + } + fn execution_resource_trace(&self) -> Option<&ResourceTrace> { self.files.execution_resource_trace() } @@ -259,12 +268,12 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() { files: &mut files, calls: Some(Vec::new()), }; - let (original_execution, captured) = executor.unwrap().run_capturing_entry( - source, - &mut record, - marker_start, - |host| host.calls.take().unwrap(), - ); + let (original_execution, captured) = + executor + .unwrap() + .run_capturing_entry(source, &mut record, marker_start, |host| { + host.calls.take().unwrap() + }); let original_execution = original_execution.expect("the original A3 job reaches its end"); let (checkpoint, calls) = captured.expect("a physical command boundary before the edited line"); assert!(checkpoint.frontier() <= marker_start); diff --git a/src/native_job.rs b/src/native_job.rs index ae3f022..5d7867a 100644 --- a/src/native_job.rs +++ b/src/native_job.rs @@ -151,6 +151,8 @@ struct DraftLedger { pub struct Files { world: FileWorld, + #[cfg(all(target_os = "linux", target_env = "gnu"))] + regex_worker: Option, cwd: PathBuf, inputs: BTreeMap, outputs: BTreeMap, @@ -547,6 +549,8 @@ impl Files { preparation.phase = HostPreparationPhase::Ready; Ok(Self { world: stored_world.take().unwrap(), + #[cfg(all(target_os = "linux", target_env = "gnu"))] + regex_worker: None, cwd, inputs: BTreeMap::new(), outputs: BTreeMap::new(), @@ -1399,6 +1403,27 @@ pub(crate) fn absolute_output(cwd: &Path, path: &Path) -> Result, + ) -> Result { + if self.regex_worker.is_none() { + let path = self + .runtime_observations + .borrow_mut() + .environment("TEXRRA_PDF_REGEX_WORKER"); + if let Some(path) = path { + self.regex_worker = Some(crate::native_regex::Worker::start(Path::new(&path))?); + } + } + match &mut self.regex_worker { + Some(worker) => worker.request(request, cancellation), + None => texrra_tex_core::execution::match_pdf_regex(request), + } + } + fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> { Some(self.world.trace()) } diff --git a/src/native_regex.rs b/src/native_regex.rs new file mode 100644 index 0000000..122f2c9 --- /dev/null +++ b/src/native_regex.rs @@ -0,0 +1,99 @@ +use std::{ + io::{BufRead, BufReader, Write}, + path::Path, + process::{Child, Command, Stdio}, + sync::mpsc::{self, Receiver, Sender}, + thread::{self, JoinHandle}, + time::Duration, +}; +use texrra_tex_core::execution::{Cancellation, RegexOutcome, RegexRequest}; + +pub(crate) struct Worker { + child: Child, + requests: Option>>, + answers: Receiver>, + pipe: Option>, +} + +impl Worker { + pub(crate) fn start(path: &Path) -> Result { + let mut child = Command::new(path) + .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::>(); + 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::>(&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 { + 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(); + } +}