Run cancellable pdfTeX matching in native frontends
This commit is contained in:
1 parent
091458d329
commit
6e573dc1ce
21 files changed
+665
-9
No files matched your search
@@ -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(®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 }))
|
||||
}
|
||||
@@ -8,8 +8,8 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 28;
|
||||
const PREVIOUS_SCHEMA: u32 = 27;
|
||||
const SCHEMA: u32 = 31;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 3] = [27, 28, SCHEMA];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
@@ -106,11 +106,11 @@ impl FormatImage {
|
||||
schema: u32,
|
||||
engine: String,
|
||||
}
|
||||
// Schema 28 adds primitive and node variants. All schema 27 state
|
||||
// fields and variants remain readable with their original meanings.
|
||||
// The new schemas add primitive or node variants. Previously
|
||||
// published state fields and variants retain their meanings.
|
||||
let identity: Identity =
|
||||
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());
|
||||
}
|
||||
let image: Self =
|
||||
|
||||
@@ -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(())
|
||||
|
||||
@@ -313,6 +313,8 @@ pub enum Primitive {
|
||||
Atopwithdelims,
|
||||
Abovewithdelims,
|
||||
Accent,
|
||||
Pdfmatch,
|
||||
Pdflastmatch,
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
@@ -363,6 +365,8 @@ impl Primitive {
|
||||
| Pdfcreationdate
|
||||
| Pdftexrevision
|
||||
| Pdfstrcmp
|
||||
| Pdfmatch
|
||||
| Pdflastmatch
|
||||
| Pdfcolorstackinit
|
||||
| Csname
|
||||
| Unless
|
||||
@@ -920,6 +924,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),
|
||||
|
||||
Reference in new issue
Block a user