From 651fab42f1257c9f00bebd82708a40a02b1d2644 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 11:58:23 +0800 Subject: [PATCH] Expand native Unicode character primitives and definitions --- .../texrra-tex-core/src/execution/engine.rs | 81 ++++++++++--- .../src/execution/engine/math.rs | 17 +-- .../src/execution/engine/paragraphs.rs | 4 +- .../src/execution/format_image.rs | 6 +- crates/texrra-tex-core/src/execution/state.rs | 14 ++- .../tests/execution_unicode_characters.rs | 109 ++++++++++++++++++ docs/P2_M1_PROGRESS.md | 27 +++++ 7 files changed, 227 insertions(+), 31 deletions(-) create mode 100644 crates/texrra-tex-core/tests/execution_unicode_characters.rs diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index fd93081..4617682 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -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 { + 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::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 { 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 })); } diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 962f8a6..9616f01 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -105,11 +105,12 @@ impl Executor { } fn math_code_char( &mut self, - c: char, + c: u32, token: &Token, ) -> Result, 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"); }; diff --git a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs index 0d42480..8be608e 100644 --- a/crates/texrra-tex-core/src/execution/engine/paragraphs.rs +++ b/crates/texrra-tex-core/src/execution/engine/paragraphs.rs @@ -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(|_| { diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index ecd265e..b6911b6 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -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")); diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index 06d38e1..785f43b 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -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), diff --git a/crates/texrra-tex-core/tests/execution_unicode_characters.rs b/crates/texrra-tex-core/tests/execution_unicode_characters.rs new file mode 100644 index 0000000..f308e95 --- /dev/null +++ b/crates/texrra-tex-core/tests/execution_unicode_characters.rs @@ -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 + ); + } +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index c45b753..dabaa4e 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,33 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### Unicode 字符定义和展开 + +原生 Unicode 入口的 \chardef 可保存并查询 0–U+10FFFF 的字符编号。 +\Uchar 生成普通字符或空格,\Ucharcat 保留指定的类别,类别 13 进入 +实际活动命令的名字空间。生成的 token 保留调用来源。\char 在水平列表 +接受完整的 Unicode 字符编号,在数学列表按 XeTeX 扫描 16 位编号。 +数学中的 \chardef 别名独立使用它保存的完整编号。8 位入口保有原范围, +新命令只安装在 Unicode 入口。代理码点可以通过 \chardef 保存为数值, +要求实际生成标量 token 时会报告错误。 + +24 项定向回归通过。schema59 的真实格式写入和重载覆盖宽定义、活动 +字符和普通字符的区别,未改动的 schema58 仍可重载。以相同的源码和 +实际 Latin Modern Math 字体对照 XeTeX 0.999998,字符展开输出逐项一致, +两个盒的 sp 尺寸及七个字形的编号、位置一致,一页 600 dpi 灰度图一致。 +证据位于 target/p3-xetex-unicode-chars,含原始 XDV、原生布局清单、 +geometry-receipt.json、各次参考结果和首轮参考缺少数学字体的失败记录。 + +原样 xelatex.ini 越过此前 latex.ltx 第 397 行的 \chardef=256,在 +执行 11418041 步后停于 expl3-code.tex 第 35859 行的数据读取。 +expl3 通过 \Umathcode 选择 Unicode 生成路径,通过引擎识别分支计算 +的字符上限仍是 255,因此 U+0100 触发 out-of-range。完整现场见 +target/p3-xetex-unicode-chars/xelatex-native/failure.json。接续核对 +XeTeX profile、版本和后端选择所需的实际原语,以及其对格式与项目 +身份的影响。原样 XeLaTeX 格式、类包矩阵和实时性能门禁仍待完成。 +[XeTeX 字符生成](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L10457-L10472) +[XeTeX token 类别](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L10049-L10086) + ### Unicode 数学编码和实际数学字形 Unicode 入口的经典 \mathcode 与 \Umathcode、\Umathcodenum 共用