Expand native Unicode character primitives and definitions

This commit is contained in:
gloamxun committed 2026-11-21 11:58:23 +08:00
1 parent d17680fcd8
commit 651fab42f1
7 files changed
+227 -31

No files matched your search

+67 -14
View File
@@ -674,6 +674,64 @@ impl Executor {
.collect(),
)
}
// XeTeX scans a 16-bit code for \char in math and a full Unicode
// character number for shorthand definitions and text character commands.
fn character_number(
&mut self,
command: &str,
unicode_maximum: i32,
files: &mut impl SourceProvider,
) -> Result<u32, Error> {
let number = self.integer(files)?;
let maximum = if self.state.input_profile() == super::InputProfile::UnicodeScalar {
unicode_maximum
} else {
255
};
if !(0..=maximum).contains(&number) {
return self.fail(format!("{command} must be in 0..{maximum}"));
}
Ok(number as u32)
}
fn scalar_character(&self, number: u32, span: Span) -> Result<char, Error> {
char::from_u32(number)
.ok_or_else(|| self.error(format!("character U+{number:04X} is not a Unicode scalar"), span))
}
fn expand_unicode_character(
&mut self,
primitive: Primitive,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use CatCode::*;
let c = self.character_number("Unicode character", 0x10FFFF, files)?;
let c = self.scalar_character(c, token.span)?;
let cat = if primitive == Primitive::Ucharcat {
let category = self.integer(files)?;
if !matches!(category, 1..=4 | 6..=8 | 10..=13) {
return self.fail(format!("invalid category code for Ucharcat: {category}"));
}
CatCode::from_number(category).expect("validated category")
} else if c == ' ' {
Space
} else {
Other
};
let kind = if cat == Active {
TokenKind::Command(CommandName::Active(c))
} else {
TokenKind::Character(c, cat)
};
self.push(vec![Token {
kind,
span: token.span,
invocation: token.invocation,
}
.into()])
}
fn roman_numeral(&self, mut number: usize) -> Result<String, Error> {
let mut text = String::new();
for (value, symbol) in [
@@ -802,6 +860,7 @@ impl Executor {
let value = self.integer(files)?;
self.print_tokens(&value.to_string(), token)?;
}
Uchar | Ucharcat => self.expand_unicode_character(primitive, token, files)?,
Romannumeral => {
let value = self.integer(files)?;
if value > 0 {
@@ -1908,10 +1967,7 @@ impl Executor {
self.define_traced(name.clone(), Meaning::Primitive(Relax), global, files)?;
self.optional_equals(files)?;
let value = match primitive {
Chardef => Meaning::CharGiven(
u8::try_from(self.integer(files)?)
.map_err(|_| self.error("chardef must be in 0..255", self.current))?,
),
Chardef => Meaning::CharGiven(self.character_number("chardef", 0x10FFFF, files)?),
Mathchardef => {
let code = self.integer(files)?;
if !(0..32768).contains(&code) {
@@ -3071,6 +3127,8 @@ impl Executor {
Primitive::ItalicCorrection => "/".into(),
Primitive::Etexversion => "eTeXversion".into(),
Primitive::Etexrevision => "eTeXrevision".into(),
Primitive::Uchar => "Uchar".into(),
Primitive::Ucharcat => "Ucharcat".into(),
Primitive::Umathcode => "Umathcode".into(),
Primitive::Umathcodenum => "Umathcodenum".into(),
Primitive::Umathchar => "Umathchar".into(),
@@ -3831,14 +3889,8 @@ impl Executor {
Patterns => self.patterns(files)?,
Setlanguage => self.set_language(files)?,
Char => {
let n = self.integer(files)?;
let c = if self.state.input_profile() == super::InputProfile::UnicodeScalar {
u32::try_from(n).ok().and_then(char::from_u32)
.ok_or_else(|| self.error("char requires a Unicode scalar", token.span))?
} else {
char::from(u8::try_from(n)
.map_err(|_| self.error("char must be in 0..255", token.span))?)
};
let c = self.character_number("char", 0x10FFFF, files)?;
let c = self.scalar_character(c, token.span)?;
self.text_character(c, CatCode::Other, &token, files)?;
self.events.push(Event::Character(Token {
kind: TokenKind::Character(c, CatCode::Other),
@@ -3902,9 +3954,10 @@ impl Executor {
self.finish_assignment()?;
}
Meaning::CharGiven(c) => {
self.text_character(c as char, CatCode::Other, &token, files)?;
let c = self.scalar_character(c, token.span)?;
self.text_character(c, CatCode::Other, &token, files)?;
self.events.push(Event::Character(Token {
kind: TokenKind::Character(c as char, CatCode::Other),
kind: TokenKind::Character(c, CatCode::Other),
..token
}));
}
@@ -105,11 +105,12 @@ impl Executor {
}
fn math_code_char(
&mut self,
c: char,
c: u32,
token: &Token,
) -> Result<Option<(NoadClass, MathChar)>, Error> {
let code = self.read_math_code(c as u32);
let code = self.read_math_code(c);
if code.is_active() {
let c = self.scalar_character(c, token.span)?;
let mut t = token.clone();
t.kind = TokenKind::Command(CommandName::Active(c));
self.unread(t.into())?;
@@ -523,14 +524,14 @@ impl Executor {
});
}
CatCode::Letter | CatCode::Other => {
if let Some((class, c)) = self.math_code_char(*c, token)? {
if let Some((class, c)) = self.math_code_char(*c as u32, token)? {
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
_ => return self.fail("unsupported native math category"),
},
Meaning::CharGiven(c) => {
if let Some((class, c)) = self.math_code_char(*c as char, token)? {
if let Some((class, c)) = self.math_code_char(*c, token)? {
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
@@ -574,11 +575,9 @@ impl Executor {
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token));
}
Mathchar | Char | Delimiter => {
let n = self.integer(files)?;
if *p == Char {
let c = u8::try_from(n)
.map_err(|_| self.error("char must be in 0..255", token.span))?;
if let Some((class, c)) = self.math_code_char(c as char, token)? {
let c = self.character_number("char", 0xFFFF, files)?;
if let Some((class, c)) = self.math_code_char(c, token)? {
self.accept_math_field(
MathField::Char(c),
class,
@@ -586,12 +585,14 @@ impl Executor {
)
}
} else if *p == Delimiter {
let n = self.integer(files)?;
if !(0..1 << 27).contains(&n) {
return self.fail("delimiter must be in 0..134217727");
}
let (class, c) = self.decode_math_char((n >> 12) as u16);
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token));
} else {
let n = self.integer(files)?;
if !(0..32768).contains(&n) {
return self.fail("mathchar must be in 0..32767");
};
@@ -59,7 +59,7 @@ impl Executor {
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => {
Some(i32::try_from(u32::from(c)).expect("a Unicode scalar fits i32"))
}
Meaning::CharGiven(c) => Some(i32::from(c)),
Meaning::CharGiven(c) => Some(c as i32),
Meaning::Primitive(Primitive::Char) => Some(self.integer(files)?),
_ => None,
};
@@ -716,7 +716,7 @@ impl Executor {
continue;
}
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => c,
Meaning::CharGiven(c) => char::from(c),
Meaning::CharGiven(c) => self.scalar_character(c, t.span)?,
Meaning::Primitive(Primitive::Char) => {
let n = self.integer(files)?;
char::from(u8::try_from(n).map_err(|_| {
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 58;
const COMPATIBLE_SCHEMAS: [u32; 27] = [
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, SCHEMA,
const SCHEMA: u32 = 59;
const COMPATIBLE_SCHEMAS: [u32; 28] = [
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, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
+10 -4
View File
@@ -359,6 +359,8 @@ pub enum Primitive {
Umathcharnum,
Umathchardef,
Umathcharnumdef,
Uchar,
Ucharcat,
}
impl Primitive {
@@ -394,6 +396,8 @@ impl Primitive {
| Noexpand
| Expandafter
| Number
| Uchar
| Ucharcat
| Romannumeral
| Fontname
| The
@@ -484,7 +488,7 @@ pub enum Meaning {
Count(u16),
Toks(u16),
TokenParameter(TokenParameter),
CharGiven(u8),
CharGiven(u32),
MathCharGiven(u16),
Register(Register),
Parameter(Parameter),
@@ -1132,7 +1136,7 @@ impl Default for State {
] {
state.parameters.insert(p, v);
}
state.install_unicode_math_commands();
state.install_unicode_commands();
state
}
}
@@ -1552,13 +1556,15 @@ impl State {
}
}
}
self.install_unicode_math_commands();
self.install_unicode_commands();
self
}
fn install_unicode_math_commands(&mut self) {
fn install_unicode_commands(&mut self) {
use Primitive::*;
for (name, primitive) in [
("Uchar", Uchar),
("Ucharcat", Ucharcat),
("Umathcode", Umathcode),
("XeTeXmathcode", Umathcode),
("Umathcodenum", Umathcodenum),
@@ -0,0 +1,109 @@
use texrra_tex_core::execution::*;
fn source(text: &str) -> SourceFile {
SourceFile {
name: "characters.tex".into(),
data: text.as_bytes().into(),
}
}
fn state(profile: InputProfile) -> State {
State::initex().with_etex().with_input_profile(profile)
}
const SEED: &str = r#"
\catcode123=1 \catcode125=2
\chardef\allocation=256 \chardef\greek="03B1 \chardef\high="1D6FC
\chardef\surrogate="D800
\edef\letterToken{\Ucharcat"03B1 11 }
\edef\otherToken{\Uchar"03B1 }
\edef\highToken{\Uchar"1D6FC }
\expandafter\def\Ucharcat"03B1 13 {active}
\edef\activeToken{\Ucharcat"03B1 13 }
\edef\spaced{a\Uchar32 b}
\edef\noncanonical{a\Ucharcat65 10 b}
\dump
"#;
#[test]
fn wide_character_definitions_and_generated_tokens_survive_a_format_roundtrip() {
let state = state(InputProfile::UnicodeScalar);
let dump = Executor::new(state.clone(), Limits::default())
.run(source(SEED), &mut NoFiles)
.unwrap();
let data = FormatImage::from_dump(dump, Vec::new(), Vec::new())
.unwrap()
.encode()
.unwrap();
let result = FormatImage::decode(&data)
.unwrap()
.new_job(
state.profile(),
state.input_profile(),
JobTime::new(2026, 1, 1, 0).unwrap(),
Limits::default(),
|_| Ok(SEED.as_bytes().to_vec()),
)
.unwrap()
.run(
source(
r"\message{\number\allocation/\number\greek/\number\high}
\message{\meaning\high}
\message{\meaning\letterToken/\meaning\otherToken/\meaning\highToken}
\message{\ifx\letterToken\otherToken same\else distinct\fi}
\message{\activeToken/\spaced/\noncanonical/\number\surrogate}
\end",
),
&mut NoFiles,
)
.unwrap();
let messages: Vec<_> = result
.events
.iter()
.filter_map(|event| match event {
Event::Message { text, .. } => Some(text.as_str()),
_ => None,
})
.collect();
assert_eq!(
messages,
[
"256/945/120572",
r#"\char"1D6FC"#,
"macro:->α/macro:->α/macro:->𝛼",
"distinct",
"active/a b/aAb/55296",
]
);
}
#[test]
fn character_ranges_and_primitive_availability_follow_the_input_profile() {
for (profile, input, expected) in [
(InputProfile::TeX8Bit, r"\chardef\x=256", "0..255"),
(
InputProfile::TeX8Bit,
r"\Uchar65 ",
"undefined native control sequence",
),
(
InputProfile::UnicodeScalar,
r"\chardef\x=1114112",
"0..1114111",
),
(
InputProfile::UnicodeScalar,
r"\Ucharcat65 14 ",
"invalid category code",
),
] {
let error = Executor::new(state(profile), Limits::default())
.run(source(input), &mut NoFiles)
.unwrap_err();
assert!(
error.message.contains(expected),
"{input}: {}",
error.message
);
}
}