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
@@ -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 }))
|
||||
}
|
||||
Reference in new issue
Block a user