Author SHA1 Message Date
gloamxun 31bf50806e Prototype cancellable GNU matching in native compilation sessions 2026-11-19 22:44:42 +08:00
14 changed files with 580 additions and 12 deletions

No files matched your search

Generated
+1
View File
@@ -1431,6 +1431,7 @@ version = "0.1.0"
dependencies = [
"flate2",
"hyphenate",
"libc",
"lopdf",
"rusttype",
"serde",
+3
View File
@@ -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"
@@ -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<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_outlines: Vec<crate::pdf_device::catalog::PdfOutline<Vec<Token>>>,
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)?;
@@ -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)?;
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,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)]
+14 -4
View File
@@ -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<RegexOutcome, String> {
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)))
}
@@ -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),
@@ -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]"))
);
}
+25
View File
@@ -0,0 +1,25 @@
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn main() -> Result<(), Box<dyn std::error::Error>> {
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
}
+2
View File
@@ -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;
+15 -6
View File
@@ -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<texrra_tex_core::execution::RegexOutcome, String> {
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);
+25
View File
@@ -151,6 +151,8 @@ struct DraftLedger {
pub struct Files {
world: FileWorld,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: Option<crate::native_regex::Worker>,
cwd: PathBuf,
inputs: BTreeMap<u8, Input>,
outputs: BTreeMap<u8, Output>,
@@ -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<PathBuf, String
}
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> {
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())
}
+99
View File
@@ -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<Sender<Vec<u8>>>,
answers: Receiver<Result<RegexOutcome, String>>,
pipe: Option<JoinHandle<()>>,
}
impl Worker {
pub(crate) fn start(path: &Path) -> Result<Self, String> {
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::<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();
}
}