Normalize native XeTeX physical input before tokenization

This commit is contained in:
gloamxun committed 2026-11-26 13:02:38 +08:00
1 parent 048478c346
commit 76df2d6832
10 files changed
+214 -63

No files matched your search

@@ -2860,11 +2860,9 @@ impl Executor {
let chars: Vec<xe_encoding::Character> = if let Some(encoding) = &encoding {
let (resolved, bom) = encoding.resolve(&line);
let (length, _) = resolved.framing().line_boundary(&line[bom..]);
let (mut chars, warnings) = resolved.decode(&line[bom..bom + length], base + bom)
let (chars, warnings) = resolved
.decode_line(&line[bom..bom + length], base + bom, &self.state, &mut self.reads)
.map_err(|e| self.error(e, Span { source, start: base + bom, end }))?;
while chars.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) {
chars.pop();
}
if warnings > 0 {
self.observe_xe_utf8_warnings(
vec![(self.input_position.map_or(1, |(_, line)| line), warnings)],
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 76;
const COMPATIBLE_SCHEMAS: [u32; 43] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, SCHEMA,
const SCHEMA: u32 = 77;
const COMPATIBLE_SCHEMAS: [u32; 44] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
+57 -19
View File
@@ -112,6 +112,39 @@ mod tests {
);
assert!(mouth.next(&state, &mut reads).unwrap().is_none());
}
#[test]
fn xe_normalization_preserves_reordered_bytes_and_control_word_extent() {
use super::super::{InputProfile, Parameter, ParameterValue, state::Key};
let mut state = State::default().with_input_profile(InputProfile::XeTeX);
state.assign_integer(Key::Endlinechar, -1, false);
for mark in ['\u{0300}', '\u{0315}'] {
state.assign_catcode(mark, CatCode::Letter, false);
}
let mut mouth = Mouth::new(0, "é\n\\a\u{0315}\u{0300}!\na\u{0315}\u{0300}é".into(), InputProfile::XeTeX);
let mut reads = BTreeSet::new();
let first = mouth.next(&state, &mut reads).unwrap().unwrap();
assert!(matches!(first.kind, TokenKind::Character('é', _)));
assert_eq!((first.span.start, first.span.end), (0, 2));
state.assign_parameter(Parameter::XeTeXinputnormalization, ParameterValue::Integer(2), false);
let name = mouth.next(&state, &mut reads).unwrap().unwrap();
assert_eq!(name.kind, TokenKind::Command(CommandName::Control("a\u{0300}\u{0315}".into())));
assert_eq!((name.span.start, name.span.end), (3, 9));
for (value, range) in [
('!', (9, 10)),
('a', (11, 12)),
('\u{0300}', (14, 16)),
('\u{0315}', (12, 14)),
('e', (16, 18)),
('\u{0301}', (16, 18)),
] {
let token = mouth.next(&state, &mut reads).unwrap().unwrap();
assert!(matches!(token.kind, TokenKind::Character(c, _) if c == value));
assert_eq!((token.span.start, token.span.end), range);
}
assert!(reads.contains(&Dependency::Parameter(Parameter::XeTeXinputnormalization)));
}
#[test]
fn disabled_endlinechar_does_not_merge_control_names_across_lines() {
let mut mouth = Mouth::new(
@@ -369,8 +402,15 @@ impl Mouth {
pub(super) fn xe_location(&self, offset: usize) -> Option<(usize, usize)> {
let xe = self.xe.as_ref()?;
(xe.line_start <= offset && offset <= self.offset && self.line_number > 0)
.then(|| (self.line_number, 1 + self.line.partition_point(|c| c.end <= offset && c.start < offset)))
(xe.line_start <= offset && offset <= self.offset && self.line_number > 0).then(|| {
// Canonical ordering can move a mark ahead of an earlier byte range.
let preceding = self
.line
.iter()
.filter(|c| c.end <= offset && c.start < offset)
.count();
(self.line_number, 1 + preceding)
})
}
pub(super) fn take_utf8_warnings(&mut self) -> Vec<(usize, usize)> {
@@ -518,12 +558,10 @@ impl Mouth {
self.line_number += 1;
self.line.clear();
self.cursor = 0;
let (mut chars, invalid_utf8) = xe.encoding.decode(&self.data[start..content_end], start)
let (characters, invalid_utf8) = xe.encoding
.decode_line(&self.data[start..content_end], start, state, reads)
.map_err(|message| (Span { source: self.source, start, end: content_end }, message))?;
while chars.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) {
chars.pop();
}
self.line = chars;
self.line = characters;
if invalid_utf8 > 0 {
self.invalid_utf8.push((self.line_number, invalid_utf8));
}
@@ -607,15 +645,11 @@ impl Mouth {
let Some((value, extra)) = self.expanded_superscript(c.value, self.cursor + 1) else {
return Some(c);
};
let end = self.line[self.cursor + extra].end;
self.line.splice(
self.cursor..=self.cursor + extra,
[Character {
value,
start: c.start,
end,
}],
);
let mut replacement = Character { value, ..c };
for &part in &self.line[self.cursor + 1..=self.cursor + extra] {
replacement.cover(part);
}
self.line.splice(self.cursor..=self.cursor + extra, [replacement]);
}
}
/// get_next's ordinary ^^ conversion changes cur_chr and advances loc.
@@ -629,8 +663,10 @@ impl Mouth {
break;
};
c.value = value;
for &part in &self.line[self.cursor..self.cursor + extra] {
c.cover(part);
}
self.cursor += extra;
c.end = self.line[self.cursor - 1].end;
}
c
}
@@ -688,7 +724,8 @@ impl Mouth {
let mut name = String::new();
if let Some(next) = self.peek(state, reads) {
self.cursor += 1;
span.end = next.end;
span.start = span.start.min(next.start);
span.end = span.end.max(next.end);
name.push(next.value);
let code = Self::catcode(state, reads, next.value);
if code == CatCode::Letter {
@@ -697,7 +734,8 @@ impl Mouth {
break;
}
name.push(next.value);
span.end = next.end;
span.start = span.start.min(next.start);
span.end = span.end.max(next.end);
self.cursor += 1;
}
self.state = LineState::Skip;
@@ -130,6 +130,7 @@ pub enum Parameter {
XeTeXinterwordspaceshaping,
XeTeXlinebreakskip,
XeTeXlinebreakpenalty,
XeTeXinputnormalization,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -162,7 +163,7 @@ impl Parameter {
)
}
pub(super) const XETEX: [Self; 10] = [
pub(super) const XETEX: [Self; 11] = [
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
Self::Suppressfontnotfounderror,
@@ -173,6 +174,7 @@ impl Parameter {
Self::XeTeXinterwordspaceshaping,
Self::XeTeXlinebreakskip,
Self::XeTeXlinebreakpenalty,
Self::XeTeXinputnormalization,
];
pub const ALL: &'static [Self] = &[
@@ -301,6 +303,7 @@ impl Parameter {
Self::XeTeXinterwordspaceshaping,
Self::XeTeXlinebreakskip,
Self::XeTeXlinebreakpenalty,
Self::XeTeXinputnormalization,
];
pub fn name(self) -> String {
match self {
@@ -314,6 +317,7 @@ impl Parameter {
Self::XeTeXinterwordspaceshaping => "XeTeXinterwordspaceshaping".into(),
Self::XeTeXlinebreakskip => "XeTeXlinebreakskip".into(),
Self::XeTeXlinebreakpenalty => "XeTeXlinebreakpenalty".into(),
Self::XeTeXinputnormalization => "XeTeXinputnormalization".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}
@@ -1,5 +1,7 @@
//! XeTeX physical input encodings. Decoded units retain their source bytes.
use std::sync::Arc;
use std::{collections::BTreeSet, sync::Arc};
use super::{Dependency, Parameter, ParameterValue, State};
pub(super) mod icu;
@@ -68,6 +70,13 @@ pub(super) struct Character {
pub end: usize,
}
impl Character {
pub fn cover(&mut self, other: Self) {
self.start = self.start.min(other.start);
self.end = self.end.max(other.end);
}
}
impl Encoding {
pub fn parse(name: &str) -> Result<Option<Self>, String> {
let builtin = match name.to_ascii_lowercase().as_str() {
@@ -106,7 +115,29 @@ impl Encoding {
(encoding, bom)
}
pub fn decode(&self, data: &[u8], base: usize) -> Result<(Vec<Character>, usize), String> {
/// Decode a complete physical line before TeX looks at any of its catcodes.
pub fn decode_line(
&self,
data: &[u8],
base: usize,
state: &State,
reads: &mut BTreeSet<Dependency>,
) -> Result<(Vec<Character>, usize), String> {
let (mut characters, warnings) = self.decode(data, base)?;
let parameter = Parameter::XeTeXinputnormalization;
reads.insert(Dependency::Parameter(parameter));
match state.parameter(parameter) {
ParameterValue::Integer(1) => characters = normalize(characters, true),
ParameterValue::Integer(2) => characters = normalize(characters, false),
_ => {}
}
while characters.last().is_some_and(|c| matches!(c.value, ' ' | '\r' | '\n')) {
characters.pop();
}
Ok((characters, warnings))
}
fn decode(&self, data: &[u8], base: usize) -> Result<(Vec<Character>, usize), String> {
let mut invalid_utf8 = 0;
let chars = match self {
Self::Auto => unreachable!("resolve the encoding at file open"),
@@ -174,6 +205,22 @@ impl Encoding {
}
}
fn normalize(characters: Vec<Character>, composed: bool) -> Vec<Character> {
use unicode_normalization::char::decompose_canonical;
if characters.iter().all(|character| character.value.is_ascii()) {
return characters;
}
let mut decomposed = Vec::with_capacity(characters.len());
for character in characters {
decompose_canonical(character.value, |value| decomposed.push((value, character)));
}
crate::normalization::order_and_compose(decomposed, composed, Character::cover)
.into_iter()
.map(|(value, source)| Character { value, ..source })
.collect()
}
fn decode_utf8_character(input: &[u8]) -> (char, usize, bool) {
let first = input[0];
let (mut value, continuation) = match first {
+12 -34
View File
@@ -483,9 +483,7 @@ fn push(output: &mut Vec<Entry>, value: u32, source: &PaintSource) -> Result<(),
}
fn normalize(input: Vec<Entry>, composed: bool) -> Result<Vec<Entry>, &'static str> {
use unicode_normalization::char::{
canonical_combining_class as ccc, compose, decompose_canonical,
};
use unicode_normalization::char::decompose_canonical;
let mut decomposed = Vec::with_capacity(input.len());
for entry in input {
@@ -498,35 +496,15 @@ fn normalize(input: Vec<Entry>, composed: bool) -> Result<Vec<Entry>, &'static s
return Err("mapped OpenType word capacity exceeded");
}
}
let mut marks = 0;
for i in 0..decomposed.len() {
if ccc(decomposed[i].0) == 0 {
decomposed[marks..i].sort_by_key(|(c, _)| ccc(*c));
marks = i + 1;
}
}
decomposed[marks..].sort_by_key(|(c, _)| ccc(*c));
let mut output: Vec<Entry> = Vec::with_capacity(decomposed.len());
let mut starter: Option<usize> = None;
let mut last_class = 0;
for (character, source) in decomposed {
let class = ccc(character);
if composed
&& (last_class == 0 || last_class < class)
&& let Some(index) = starter
&& let Some(joined) = compose(char::from_u32(output[index].value).unwrap(), character)
{
output[index].value = joined.into();
output[index].source.merge(&source);
output[index].source =
std::mem::take(&mut output[index].source).derived(Derivation::FontMapping);
continue;
}
if class == 0 {
starter = Some(output.len());
}
last_class = class;
push(&mut output, character.into(), &source)?;
}
Ok(output)
let normalized = crate::normalization::order_and_compose(decomposed, composed, |starter, mark| {
starter.merge(&mark);
*starter = std::mem::take(starter).derived(Derivation::FontMapping);
});
Ok(normalized
.into_iter()
.map(|(character, source)| Entry {
value: character.into(),
source,
})
.collect())
}
+1
View File
@@ -5,6 +5,7 @@ pub mod math;
pub mod math_engine_tex;
pub mod math_font;
mod font_mapping;
mod normalization;
pub mod opentype;
pub mod native_font;
pub mod output;
@@ -0,0 +1,42 @@
use unicode_normalization::char::{canonical_combining_class, compose};
/// Canonically order decomposed characters and optionally recompose them.
/// Each payload follows its own character across reordering.
pub(crate) fn order_and_compose<T>(
mut decomposed: Vec<(char, T)>,
composed: bool,
mut merge: impl FnMut(&mut T, T),
) -> Vec<(char, T)> {
let mut marks = 0;
for i in 0..decomposed.len() {
if canonical_combining_class(decomposed[i].0) == 0 {
decomposed[marks..i].sort_by_key(|(c, _)| canonical_combining_class(*c));
marks = i + 1;
}
}
decomposed[marks..].sort_by_key(|(c, _)| canonical_combining_class(*c));
if !composed {
return decomposed;
}
let mut output: Vec<(char, T)> = Vec::with_capacity(decomposed.len());
let mut starter: Option<usize> = None;
let mut last_class = 0;
for (character, payload) in decomposed {
let class = canonical_combining_class(character);
if (last_class == 0 || last_class < class)
&& let Some(index) = starter
&& let Some(joined) = compose(output[index].0, character)
{
output[index].0 = joined;
merge(&mut output[index].1, payload);
continue;
}
if class == 0 {
starter = Some(output.len());
}
last_class = class;
output.push((character, payload));
}
output
}