Execute TECkit font mappings in native XeLaTeX jobs

This commit is contained in:
gloamxun committed 2026-11-21 12:39:29 +08:00
1 parent 752af43f32
commit c548ca8e9f
12 files changed
+1098 -17

No files matched your search

@@ -0,0 +1,310 @@
use super::{Derivation, Entry, INVALID, Reader, Table, push, source_of};
use std::ops::Range;
const SCALAR_MASK: u32 = 0x001f_ffff;
const CLASS: u8 = 1;
const GROUP: u8 = 2;
const END_GROUP: u8 = 3;
const ALTERNATIVE: u8 = 4;
const ANY: u8 = 5;
const END_OF_TEXT: u8 = 6;
const COPY: u8 = 7;
const UNMAPPED: u8 = 15;
pub(super) struct Rule<'a> {
forward: Reader<'a>,
previous: Reader<'a>,
replacement: Reader<'a>,
matched_elements: usize,
}
impl<'a> Rule<'a> {
pub(super) fn parse(data: Reader<'a>) -> Result<Self, &'static str> {
let matched_elements = usize::from(data.byte(0)?);
let forward = 4 * (matched_elements + usize::from(data.byte(1)?));
let previous = 4 * usize::from(data.byte(2)?);
let replacement = 4 * usize::from(data.byte(3)?);
Ok(Self {
forward: Reader(data.data(4, forward)?),
previous: Reader(data.data(4 + forward, previous)?),
replacement: Reader(data.data(4 + forward + previous, replacement)?),
matched_elements,
})
}
pub(super) fn find(
&self,
table: &Table<'_>,
input: &[Entry],
start: usize,
budget: &mut usize,
) -> Result<Option<Hit>, &'static str> {
let Some(hit) = (Pattern {
table,
elements: self.forward,
input,
step: 1,
capture_count: self.matched_elements,
})
.find(start as isize, budget)?
else {
return Ok(None);
};
if hit.end < start || hit.end > input.len() {
return Err(INVALID);
}
if !self.previous.0.is_empty()
&& (Pattern {
table,
elements: self.previous,
input,
step: -1,
capture_count: 0,
})
.find(start as isize - 1, budget)?
.is_none()
{
return Ok(None);
}
Ok(Some(hit))
}
pub(super) fn emit(
&self,
table: &Table<'_>,
input: &[Entry],
start: usize,
hit: &Hit,
output: &mut Vec<Entry>,
) -> Result<(), &'static str> {
let claimed = if start == hit.end {
start..start + 1
} else {
start..hit.end
};
let rule_source = source_of(input, claimed).derived(Derivation::FontMapping);
for element in self.replacement.0.chunks_exact(4) {
let capture = || hit.captures.get(usize::from(element[1])).ok_or(INVALID);
match element[0] {
0 => push(
output,
u32::from_be_bytes(element.try_into().unwrap()),
&rule_source,
)?,
CLASS => {
let capture = capture()?;
if !capture.span.is_empty() {
let index = capture.class_index.ok_or(INVALID)?;
let class = usize::from(u16::from_be_bytes([element[2], element[3]]));
let value = table.replace_class(class, index)?;
let source =
source_of(input, capture.span.clone()).derived(Derivation::FontMapping);
push(output, value, &source)?;
}
}
COPY => {
for entry in input.get(capture()?.span.clone()).ok_or(INVALID)? {
push(output, entry.value, &entry.source)?;
}
}
UNMAPPED => push(
output,
table.unmatched(input[start].value),
&input[start].source,
)?,
_ => return Err(INVALID),
}
}
Ok(())
}
}
struct Pattern<'a> {
table: &'a Table<'a>,
elements: Reader<'a>,
input: &'a [Entry],
step: isize,
capture_count: usize,
}
#[derive(Clone, Default)]
struct Capture {
span: Range<usize>,
class_index: Option<usize>,
}
pub(super) struct Hit {
pub(super) end: usize,
captures: Vec<Capture>,
}
#[derive(Clone)]
struct Cursor {
index: usize,
position: isize,
repeat: u8,
end: usize,
captures: Vec<Capture>,
groups: Vec<(usize, u8)>,
}
impl Pattern<'_> {
fn find(&self, position: isize, budget: &mut usize) -> Result<Option<Hit>, &'static str> {
let count = self.elements.0.len() / 4;
let mut pending = vec![Cursor {
index: 0,
position,
repeat: 0,
end: position.max(0) as usize,
captures: vec![Capture::default(); self.capture_count],
groups: Vec::new(),
}];
while let Some(mut cursor) = pending.pop() {
loop {
*budget = budget
.checked_sub(1)
.ok_or("TECkit rule matching step limit exceeded")?;
let index = cursor.index;
if cursor.repeat == 0 {
if index == self.capture_count {
cursor.end = cursor.position.max(0) as usize;
}
if let Some(capture) = cursor.captures.get_mut(index) {
let start = cursor.position.max(0) as usize;
capture.span = start..start;
capture.class_index = None;
}
}
if index == count {
return Ok(Some(Hit {
end: cursor.end,
captures: cursor.captures,
}));
}
let [repeat, tag, a, b] = self.elements.data(index * 4, 4)?.try_into().unwrap();
let minimum = repeat >> 4;
let maximum = repeat & 0x0f;
if minimum > maximum {
return Err(INVALID);
}
let kind = if tag & 0x40 == 0 { 0 } else { tag & 0x3f };
match kind {
GROUP => {
let after = index + usize::from(b);
if after > count || after <= index + 1 {
return Err(INVALID);
}
if cursor.repeat >= minimum {
let mut continuation = cursor.clone();
continuation.index = after;
continuation.repeat = 0;
finish_capture(&mut continuation, index);
pending.push(continuation);
}
if cursor.repeat >= maximum {
break;
}
let mut alternatives = vec![index + 1];
let mut delimiter = index;
loop {
let distance = usize::from(self.elements.byte(delimiter * 4 + 2)?);
delimiter += distance;
if distance == 0 || delimiter >= after {
return Err(INVALID);
}
let tag = self.elements.byte(delimiter * 4 + 1)? & 0x7f;
if tag == 0x40 | END_GROUP {
break;
}
if tag != 0x40 | ALTERNATIVE {
return Err(INVALID);
}
alternatives.push(delimiter + 1);
}
cursor.groups.push((index, cursor.repeat + 1));
cursor.repeat = 0;
for &alternative in alternatives[1..].iter().rev() {
let mut next = cursor.clone();
next.index = alternative;
pending.push(next);
}
cursor.index = alternatives[0];
}
END_GROUP | ALTERNATIVE => {
let (group, repeat) = cursor.groups.pop().ok_or(INVALID)?;
if index.checked_sub(usize::from(b)) != Some(group) {
return Err(INVALID);
}
cursor.index = group;
cursor.repeat = repeat;
}
0 | CLASS | ANY | END_OF_TEXT => {
if cursor.repeat < maximum {
let value = usize::try_from(cursor.position)
.ok()
.and_then(|at| self.input.get(at))
.map(|entry| entry.value);
let class_index = if kind == CLASS {
value
.map(|value| {
self.table.match_class(
usize::from(u16::from_be_bytes([a, b])),
value,
)
})
.transpose()?
.flatten()
} else {
None
};
let matches = match kind {
0 => {
value
== Some(
u32::from_be_bytes([repeat, tag, a, b]) & SCALAR_MASK,
)
}
CLASS => class_index.is_some(),
ANY => value.is_some(),
END_OF_TEXT => value.is_none(),
_ => unreachable!(),
};
if matches != (tag & 0x80 != 0) {
if cursor.repeat >= minimum {
let mut continuation = cursor.clone();
advance(&mut continuation);
pending.push(continuation);
}
if cursor.repeat == 0
&& let Some(capture) = cursor.captures.get_mut(index)
{
capture.class_index = class_index;
}
cursor.position += self.step;
cursor.repeat += 1;
continue;
}
}
if cursor.repeat < minimum {
break;
}
advance(&mut cursor);
}
_ => return Err(INVALID),
}
}
}
Ok(None)
}
}
fn finish_capture(cursor: &mut Cursor, index: usize) {
if let Some(capture) = cursor.captures.get_mut(index) {
capture.span.end = cursor.position.max(0) as usize;
}
}
fn advance(cursor: &mut Cursor) {
finish_capture(cursor, cursor.index);
cursor.index += 1;
cursor.repeat = 0;
}