From d17680fcd86dbb228fd16eb84474ffe50afdfda9 Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 11:47:56 +0800 Subject: [PATCH] Execute Unicode math codes and measured OpenType math characters --- .../src/execution/diagnostics/math.rs | 8 +- .../texrra-tex-core/src/execution/engine.rs | 62 +++++++----- .../src/execution/engine/display.rs | 4 + .../src/execution/engine/fonts.rs | 23 ++--- .../src/execution/engine/math.rs | 75 +++++++++------ .../src/execution/engine/math_codes.rs | 88 +++++++++++++++++ .../src/execution/engine/quantities.rs | 3 + .../src/execution/engine/restores.rs | 7 +- crates/texrra-tex-core/src/execution/fonts.rs | 2 +- .../src/execution/format_image.rs | 9 +- crates/texrra-tex-core/src/execution/math.rs | 69 +++++++++----- .../src/execution/math_accent.rs | 8 +- .../src/execution/math_code.rs | 77 +++++++++++++++ .../src/execution/math_delimiter.rs | 4 +- .../texrra-tex-core/src/execution/math_op.rs | 8 +- .../texrra-tex-core/src/execution/math_ord.rs | 13 ++- crates/texrra-tex-core/src/execution/mod.rs | 3 + crates/texrra-tex-core/src/execution/state.rs | 85 ++++++++++++++--- crates/texrra-tex-core/src/opentype.rs | 47 +++++++++ .../texrra-tex-core/tests/execution_math.rs | 5 +- .../tests/execution_paragraphs.rs | 2 +- .../tests/execution_unicode_math_codes.rs | 95 +++++++++++++++++++ docs/P2_M1_PROGRESS.md | 29 ++++++ tests/native_pipeline.rs | 84 ++++++++++++++++ 24 files changed, 687 insertions(+), 123 deletions(-) create mode 100644 crates/texrra-tex-core/src/execution/engine/math_codes.rs create mode 100644 crates/texrra-tex-core/src/execution/math_code.rs create mode 100644 crates/texrra-tex-core/tests/execution_unicode_math_codes.rs diff --git a/crates/texrra-tex-core/src/execution/diagnostics/math.rs b/crates/texrra-tex-core/src/execution/diagnostics/math.rs index 4fa0f51..6a6d4fe 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics/math.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics/math.rs @@ -11,7 +11,13 @@ impl Printer<'_> { fn math_character(&mut self, character: MathChar) { self.command("fam"); self.literal(&format!("{} ", character.family)); - self.ascii(character.slot); + if let Ok(byte) = u8::try_from(character.slot) { + self.ascii(byte); + } else if let Some(c) = char::from_u32(character.slot) { + self.literal(&c.to_string()); + } else { + self.literal(&format!("U+{:04X}", character.slot)); + } } fn math_field(&mut self, field: &MathField, parent: &str, part: char) -> Result<(), String> { diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 3bf707c..fd93081 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -18,6 +18,7 @@ mod input; mod list_tail; mod marks; mod math; +mod math_codes; mod nesting; mod page; mod paragraphs; @@ -1224,6 +1225,7 @@ impl Executor { && !matches!( meaning, Meaning::Character(_) | Meaning::CharGiven(_) | Meaning::MathCharGiven(_) + | Meaning::UnicodeMathCharGiven(_) ) && let TokenKind::Command(CommandName::Active(c)) = input.token.kind { @@ -1917,6 +1919,9 @@ impl Executor { } Meaning::MathCharGiven(code as u16) } + Umathchardef | Umathcharnumdef => Meaning::UnicodeMathCharGiven( + self.scan_unicode_math_code(primitive == Umathchardef, files)?, + ), Countdef => Meaning::Count(self.register_index(files)?), Toksdef => Meaning::Toks(self.register_index(files)?), Dimendef | Skipdef | Muskipdef => { @@ -2008,10 +2013,14 @@ impl Executor { Ok(Key::Delcode(c)) } Meaning::Primitive(Primitive::Mathcode) => { - let c = self.integer(files)?; - let c = u8::try_from(c) - .map_err(|_| self.error("mathcode index must be in 0..255", self.current))?; - Ok(Key::Mathcode(c)) + Ok(Key::Mathcode(self.scan_math_code_index(files)?)) + } + Meaning::Primitive(Primitive::Umathcodenum) => { + Ok(Key::Mathcodenum(self.scan_math_code_index(files)?)) + } + Meaning::Primitive(Primitive::Umathcode) => { + self.scan_math_code_index(files)?; + self.fail(r"Can't use \Umathcode as a number (try \Umathcodenum)") } Meaning::Primitive(Primitive::Catcode) => { let number = self.integer(files)?; @@ -2042,10 +2051,12 @@ impl Executor { self.reads.insert(Dependency::DelCode(*c)); self.state.delcode(*c) } - Key::Mathcode(c) => { - self.reads.insert(Dependency::MathCode(*c)); - self.state.mathcode(*c) as i32 - } + Key::Mathcode(c) => i32::from( + self.read_math_code(*c).legacy().ok_or_else(|| { + self.error("Extended mathchar used as mathchar", self.current) + })? + ), + Key::Mathcodenum(c) => self.read_math_code(*c).word(), Key::Parameter(p) => self.read_parameter(*p).width(), Key::Spacefactor => { if self.writing || !self.math.is_empty() { @@ -2166,6 +2177,7 @@ impl Executor { } Meaning::CharGiven(c) => Ok(c as i32), Meaning::MathCharGiven(c) => Ok(c as i32), + Meaning::UnicodeMathCharGiven(code) => Ok(code.word()), Meaning::Parameter(p) if p.kind() == Some(RegisterKind::Muskip) => { self.fail("incompatible mu units in integer scan") } @@ -2429,7 +2441,7 @@ impl Executor { } if matches!(first.token.kind, TokenKind::Command(_)) { let value = self.internal_integer_from(first, files)?; - return self.bounded(sign * value as i64); + return if sign > 0 { Ok(value) } else { self.bounded(-i64::from(value)) }; } let radix = match first.token.kind { TokenKind::Character('\'', CatCode::Other) => 8, @@ -3059,6 +3071,12 @@ impl Executor { Primitive::ItalicCorrection => "/".into(), Primitive::Etexversion => "eTeXversion".into(), Primitive::Etexrevision => "eTeXrevision".into(), + Primitive::Umathcode => "Umathcode".into(), + Primitive::Umathcodenum => "Umathcodenum".into(), + Primitive::Umathchar => "Umathchar".into(), + Primitive::Umathcharnum => "Umathcharnum".into(), + Primitive::Umathchardef => "Umathchardef".into(), + Primitive::Umathcharnumdef => "Umathcharnumdef".into(), _ => format!("{p:?}").to_ascii_lowercase(), }; format!("{escape}{name}") @@ -3068,6 +3086,9 @@ impl Executor { Meaning::TokenParameter(p) => format!("{escape}{}", p.name()), Meaning::CharGiven(c) => format!("{escape}char\"{c:X}"), Meaning::MathCharGiven(c) => format!("{escape}mathchar\"{c:X}"), + Meaning::UnicodeMathCharGiven(code) => format!( + "{escape}Umathchar\"{:X}\"{:X}\"{:X}", code.class(), code.family(), code.slot() + ), Meaning::Register(r) => format!("{escape}{}{}", r.kind.name(), r.index), Meaning::Parameter(p) => format!("{escape}{}", p.name()), Meaning::Font(font) => format!( @@ -3887,7 +3908,7 @@ impl Executor { ..token })); } - Meaning::MathCharGiven(_) => { + Meaning::MathCharGiven(_) | Meaning::UnicodeMathCharGiven(_) => { return self.fail("native math character execution requires math mode"); } Meaning::Undefined => { @@ -4160,19 +4181,8 @@ impl Executor { state.assign_delcode(c, n, global); })?; } - Some(Mathcode) => { - let c = self.integer(files)?; - let c = u8::try_from(c) - .map_err(|_| self.error("mathcode index must be in 0..255", self.current))?; - self.optional_equals(files)?; - let n = self.integer(files)?; - if !(0..=32768).contains(&n) { - return self.fail("mathcode must be in 0..32768"); - }; - let equivalent = self.state.mathcode(c) == n as u16; - self.assign_equivalence(Key::Mathcode(c), global, equivalent, files, |state| { - state.assign_mathcode(c, n as u16, global); - })?; + Some(p @ (Mathcode | Umathcode | Umathcodenum)) => { + self.scan_math_code_assignment(p, global, files)?; } Some(Parshape) => self.scan_paragraph_shape(global, files)?, Some(Setbox) => { @@ -4279,7 +4289,8 @@ impl Executor { )?; } Some( - p @ (Chardef | Mathchardef | Countdef | Toksdef | Dimendef | Skipdef | Muskipdef), + p @ (Chardef | Mathchardef | Umathchardef | Umathcharnumdef + | Countdef | Toksdef | Dimendef | Skipdef | Muskipdef), ) => { self.define_shorthand(p, global, files)?; } @@ -4359,7 +4370,8 @@ impl Executor { let key = self.integer_variable(files)?; if matches!( key, - Key::Catcode(_) | Key::Mathcode(_) | Key::Sfcode(_) | Key::CaseCode(_, _) + Key::Catcode(_) | Key::Mathcode(_) | Key::Mathcodenum(_) | Key::Sfcode(_) + | Key::CaseCode(_, _) ) { return self.fail("expected assignable integer register, not a code table"); } diff --git a/crates/texrra-tex-core/src/execution/engine/display.rs b/crates/texrra-tex-core/src/execution/engine/display.rs index f60f14c..2d2a5ff 100644 --- a/crates/texrra-tex-core/src/execution/engine/display.rs +++ b/crates/texrra-tex-core/src/execution/engine/display.rs @@ -378,11 +378,15 @@ impl Executor { | Futurelet | Chardef | Mathchardef + | Umathchardef + | Umathcharnumdef | Catcode | Lccode | Uccode | Sfcode | Mathcode + | Umathcode + | Umathcodenum | Delcode | Count | Countdef diff --git a/crates/texrra-tex-core/src/execution/engine/fonts.rs b/crates/texrra-tex-core/src/execution/engine/fonts.rs index ac76688..b8bee3c 100644 --- a/crates/texrra-tex-core/src/execution/engine/fonts.rs +++ b/crates/texrra-tex-core/src/execution/engine/fonts.rs @@ -117,20 +117,14 @@ impl Executor { Meaning::Primitive( p @ (Primitive::Textfont | Primitive::Scriptfont | Primitive::Scriptscriptfont), ) => { - let family = self.integer(files)?; - if !(0..16).contains(&family) { - return self.fail("native math family must be in 0..15"); - } + let family = self.scan_math_family(files)?; let size = match p { Primitive::Textfont => 0, Primitive::Scriptfont => 1, _ => 2, }; - self.reads.insert(Dependency::MathFamily { - size, - family: family as u8, - }); - self.state.math_font(size, family as u8) + self.reads.insert(Dependency::MathFamily { size, family }); + self.state.math_font(size, family) } _ => return self.fail("expected native font identifier"), }; @@ -140,10 +134,11 @@ impl Executor { pub(super) fn missing_glyph( &mut self, font: FontId, - slot: u8, + slot: impl Into, span: Span, files: &mut impl SourceProvider, ) -> Result<(), Error> { + let slot = slot.into(); let tracing = self.read_parameter(Parameter::Tracinglostchars).width(); let online = self.read_parameter(Parameter::Tracingonline).width(); let destination = if tracing <= 0 { @@ -156,14 +151,16 @@ impl Executor { // TeX print_ASCII renders nonprinting bytes in ^^ notation. This is // the requested slot, not a Unicode-to-font substitution. self.reads.insert(Dependency::NewLineChar); - let printed = if u8::try_from(self.state.newlinechar).ok() == Some(slot) { + let printed = if u32::try_from(self.state.newlinechar).ok() == Some(slot) { "\n".into() } else { match slot { - 0..=31 => format!("^^{}", char::from(slot + 64)), + 0..=31 => format!("^^{}", char::from(slot as u8 + 64)), 127 => "^^?".into(), 128..=255 => format!("^^{slot:02x}"), - _ => char::from(slot).to_string(), + _ => char::from_u32(slot) + .map(|c| c.to_string()) + .unwrap_or_else(|| format!("U+{slot:04X}")), } }; let newline = u8::try_from(self.state.newlinechar).ok().map(char::from); diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 7fed210..962f8a6 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -83,10 +83,7 @@ impl Executor { global: bool, files: &mut impl SourceProvider, ) -> Result<(), Error> { - let family = self.integer(files)?; - if !(0..16).contains(&family) { - return self.fail("native math family must be in 0..15"); - }; + let family = self.scan_math_family(files)?; self.optional_equals(files)?; let font = self.font_identifier(files)?; let size = match p { @@ -94,7 +91,6 @@ impl Executor { Primitive::Scriptfont => 1, _ => 2, }; - let family = family as u8; let equivalent = self.state.math_font(size, family) == font; self.assign_equivalence( Key::Mathfont(size, family), @@ -112,37 +108,46 @@ impl Executor { c: char, token: &Token, ) -> Result, Error> { - let c = u8::try_from(c as u32).map_err(|_| { - self.error( - "native 8-bit mathcode requires a byte character", - token.span, - ) - })?; - self.reads.insert(Dependency::MathCode(c)); - let code = self.state.mathcode(c); - if code == 32768 { + let code = self.read_math_code(c as u32); + if code.is_active() { let mut t = token.clone(); - t.kind = TokenKind::Command(CommandName::Active(c as char)); + t.kind = TokenKind::Command(CommandName::Active(c)); self.unread(t.into())?; return Ok(None); } - Ok(Some(self.decode_math_char(code))) + Ok(Some(self.decode_math_code(code))) } + fn decode_math_char(&mut self, code: u16) -> (NoadClass, MathChar) { - let raw = (code >> 12) as u8; - let fam = self.read_parameter(Parameter::Fam).width(); + self.decode_math_code(MathCode::from_legacy(code)) + } + + fn decode_math_code(&mut self, code: MathCode) -> (NoadClass, MathChar) { + let class = code.class(); + let mut family = code.family(); + if class == 7 { + let current = self.read_parameter(Parameter::Fam).width(); + if (0..self.state.math_family_count()).contains(¤t) { + family = current as u8; + } + } + if family >= 16 { + for size in 0..3 { + self.reads.insert(Dependency::MathFamily { size, family }); + } + } ( - NoadClass::from_code(if raw == 7 { 0 } else { raw }), - MathChar { - family: if raw == 7 && (0..16).contains(&fam) { - fam as u8 - } else { - ((code >> 8) & 15) as u8 - }, - slot: code as u8, - }, + NoadClass::from_code(if class == 7 { 0 } else { class }), + MathChar { family, slot: code.slot() }, ) } + fn explicit_math_code(&mut self, code: MathCode) -> Result<(NoadClass, MathChar), Error> { + if code.is_active() { + return self.fail("active math code requires a character table entry"); + } + Ok(self.decode_math_code(code)) + } + pub(super) fn start_math( &mut self, token: &Token, @@ -482,7 +487,8 @@ impl Executor { Meaning::Character(TokenKind::Character(_, CatCode::Letter | CatCode::Other)) | Meaning::CharGiven(_) | Meaning::MathCharGiven(_) - | Meaning::Primitive(Mathchar | Char | Delimiter) => {} + | Meaning::UnicodeMathCharGiven(_) + | Meaning::Primitive(Mathchar | Umathchar | Umathcharnum | Char | Delimiter) => {} _ => return self.fail("expected a native math field character or group"), } } @@ -532,6 +538,10 @@ impl Executor { let (class, c) = self.decode_math_char(*code); self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token)) } + Meaning::UnicodeMathCharGiven(code) => { + let (class, c) = self.explicit_math_code(*code)?; + self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token)); + } Meaning::Primitive(p) => match p { Halign => self.start_alignment(*p, token.span, files)?, Mathchoice => self.start_math_choice(token.span, files)?, @@ -558,6 +568,11 @@ impl Executor { self.math.last_mut().unwrap().nodes.push(MathNode::Rule(r)); } Left | Right => self.left_right(*p == Left, token.span, files)?, + Umathchar | Umathcharnum => { + let code = self.scan_unicode_math_code(*p == Umathchar, files)?; + let (class, c) = self.explicit_math_code(code)?; + self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token)); + } Mathchar | Char | Delimiter => { let n = self.integer(files)?; if *p == Char { @@ -778,8 +793,10 @@ impl Executor { } Noboundary => {} Global | Long | Outer | Protected | Def | Gdef | Edef | Xdef | Let | Futurelet - | Afterassignment | Aftergroup | Immediate | Chardef | Mathchardef | Catcode + | Afterassignment | Aftergroup | Immediate | Chardef | Mathchardef + | Umathchardef | Umathcharnumdef | Catcode | Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode + | Umathcode | Umathcodenum | Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip | Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline | Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand diff --git a/crates/texrra-tex-core/src/execution/engine/math_codes.rs b/crates/texrra-tex-core/src/execution/engine/math_codes.rs new file mode 100644 index 0000000..b04094e --- /dev/null +++ b/crates/texrra-tex-core/src/execution/engine/math_codes.rs @@ -0,0 +1,88 @@ +use super::*; + +impl Executor { + pub(super) fn scan_math_code_index( + &mut self, + files: &mut impl SourceProvider, + ) -> Result { + let value = self.integer(files)?; + match self.state.input_profile() { + InputProfile::TeX8Bit if !(0..=255).contains(&value) => { + self.fail("mathcode index must be in 0..255") + } + InputProfile::UnicodeScalar if !(0..=0x10_ffff).contains(&value) => { + self.fail("Bad character code") + } + _ => Ok(value as u32), + } + } + + pub(super) fn scan_math_family( + &mut self, + files: &mut impl SourceProvider, + ) -> Result { + let value = self.integer(files)?; + let count = self.state.math_family_count(); + if !(0..count).contains(&value) { + return self.fail(format!("native math family must be in 0..{}", count - 1)); + } + Ok(value as u8) + } + + pub(super) fn scan_unicode_math_code( + &mut self, + fields: bool, + files: &mut impl SourceProvider, + ) -> Result { + let value = self.integer(files)?; + if !fields { + return MathCode::from_word(value).map_err(|message| self.error(message, self.current)); + } + if !(0..=7).contains(&value) { + return self.fail("Bad math class"); + } + let family = self.scan_math_family(files)?; + let character = self.scan_math_code_index(files)?; + Ok(MathCode::new(value as u8, family, character)) + } + + pub(super) fn read_math_code(&mut self, character: u32) -> MathCode { + self.reads.insert(match u8::try_from(character) { + Ok(slot) => Dependency::MathCode(slot), + Err(_) => Dependency::UnicodeMathCode(character), + }); + self.state.math_code(character) + } + + pub(super) fn scan_math_code_assignment( + &mut self, + primitive: Primitive, + global: bool, + files: &mut impl SourceProvider, + ) -> Result<(), Error> { + let character = self.scan_math_code_index(files)?; + self.optional_equals(files)?; + let code = match primitive { + Primitive::Mathcode => { + let value = self.integer(files)?; + if !(0..=32768).contains(&value) { + return self.fail("mathcode must be in 0..32768"); + } + MathCode::from_legacy(value as u16) + } + Primitive::Umathcode => self.scan_unicode_math_code(true, files)?, + Primitive::Umathcodenum => self.scan_unicode_math_code(false, files)?, + _ => unreachable!(), + }; + let equivalent = self.state.math_code(character) == code; + self.assign_equivalence( + Key::Mathcode(character), + global, + equivalent, + files, + |state| { + state.assign_mathcode(character, code, global); + }, + ) + } +} diff --git a/crates/texrra-tex-core/src/execution/engine/quantities.rs b/crates/texrra-tex-core/src/execution/engine/quantities.rs index 43a8209..1bf5c74 100644 --- a/crates/texrra-tex-core/src/execution/engine/quantities.rs +++ b/crates/texrra-tex-core/src/execution/engine/quantities.rs @@ -191,12 +191,15 @@ impl Executor { Meaning::Count(_) | Meaning::CharGiven(_) | Meaning::MathCharGiven(_) + | Meaning::UnicodeMathCharGiven(_) | Meaning::Primitive( Primitive::Count | Primitive::Lccode | Primitive::Uccode | Primitive::Sfcode | Primitive::Mathcode + | Primitive::Umathcode + | Primitive::Umathcodenum | Primitive::Catcode | Primitive::Endlinechar | Primitive::Newlinechar diff --git a/crates/texrra-tex-core/src/execution/engine/restores.rs b/crates/texrra-tex-core/src/execution/engine/restores.rs index e47403f..93fa5f7 100644 --- a/crates/texrra-tex-core/src/execution/engine/restores.rs +++ b/crates/texrra-tex-core/src/execution/engine/restores.rs @@ -218,7 +218,12 @@ impl Executor { let (_, value) = rendered.split_once('=').expect("box diagnostic header"); (format!("box{index}"), value.trim_end_matches('\n').into()) } - Key::Mathcode(c) => (format!("mathcode{c}"), self.state.mathcode(*c).to_string()), + Key::Mathcode(c) => { + let code = self.state.math_code(*c); + let value = code.legacy().map_or(code.word(), i32::from); + (format!("mathcode{c}"), value.to_string()) + } + Key::Mathcodenum(_) => unreachable!("packed math code reads do not create save records"), Key::Delcode(c) => (format!("delcode{c}"), self.state.delcode(*c).to_string()), Key::Sfcode(c) => (format!("sfcode{c}"), self.state.sfcode(*c).to_string()), Key::CaseCode(kind, c) => ( diff --git a/crates/texrra-tex-core/src/execution/fonts.rs b/crates/texrra-tex-core/src/execution/fonts.rs index fa79306..fd8c627 100644 --- a/crates/texrra-tex-core/src/execution/fonts.rs +++ b/crates/texrra-tex-core/src/execution/fonts.rs @@ -81,7 +81,7 @@ pub(super) fn text_glyph_from_font( #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct MissingGlyph { pub font: FontId, - pub slot: u8, + pub slot: u32, pub tracing: i32, pub destination: Option, pub message: Option, diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 2219666..ecd265e 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 = 57; -const COMPATIBLE_SCHEMAS: [u32; 26] = [ - 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, SCHEMA, +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 ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -133,6 +133,9 @@ impl FormatImage { if image.schema < 55 { image.state.restore_legacy_font_map_commands(); } + if image.schema < 58 { + image.state.restore_legacy_mathcodes()?; + } image.schema = SCHEMA; Ok(image) } diff --git a/crates/texrra-tex-core/src/execution/math.rs b/crates/texrra-tex-core/src/execution/math.rs index 956a2bc..f373482 100644 --- a/crates/texrra-tex-core/src/execution/math.rs +++ b/crates/texrra-tex-core/src/execution/math.rs @@ -36,7 +36,7 @@ impl NoadClass { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct MathChar { pub family: u8, - pub slot: u8, + pub slot: u32, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct Delimiter { @@ -69,11 +69,11 @@ impl Delimiter { Self { small: MathChar { family: ((code >> 20) & 15) as u8, - slot: (code >> 12) as u8, + slot: (code >> 12) & 255, }, large: MathChar { family: ((code >> 8) & 15) as u8, - slot: code as u8, + slot: code & 255, }, } } @@ -341,7 +341,7 @@ pub(super) struct Converter<'a> { pub state: &'a State, pub horizontal_packs: std::cell::Cell, pub last_pack_badness: std::cell::Cell>, - pub missing: std::cell::RefCell>, + pub missing: std::cell::RefCell>, pub delimiter_glyphs: std::cell::Cell, pub delimiter_glyph_limit: usize, pub steps: std::cell::Cell, @@ -355,11 +355,14 @@ impl Converter<'_> { style: MathStyle, ) -> Result<&std::sync::Arc, String> { let id = self.state.math_font(style.size_index() as u8, family); - self.state.fonts.glyph_font(id).map_err(|_| { - format!( + if id == FontId::NULL { + return Err(format!( "native math family {family} size {} is nullfont", style.size_index() - ) + )); + } + self.state.fonts.glyph_font(id).map_err(|_| { + format!("native math family {family} size {} requires OpenType math layout here", style.size_index()) }) } pub fn validate(&self) -> Result<(), String> { @@ -392,20 +395,37 @@ impl Converter<'_> { |n| i64::from(extension[n]), )) } + pub(super) fn has_math_char(&self, id: FontId, slot: u32) -> Result { + if let Some(font) = self.state.fonts.font(id)?.opentype() { + let face = font.face()?; + Ok(char::from_u32(slot).is_some_and(|c| face.glyph_index(c).is_some())) + } else { + Ok(u8::try_from(slot).is_ok_and(|slot| self.state.font_has_slot(id, slot))) + } + } + pub(super) fn glyph( &self, c: MathChar, style: MathStyle, source: &PaintSource, ) -> Result<(MathGeometry, i64), String> { - let id = self.font(c.family, style)?; - let f = id.metrics(); - let slot = char::from(c.slot); let font = self.state.math_font(style.size_index() as u8, c.family); - if !self.state.font_has_slot(font, c.slot) { + if font == FontId::NULL { + // Keep the same diagnostic as the legacy fetch path. + self.font(c.family, style)?; + } + if !self.has_math_char(font, c.slot)? { self.missing.borrow_mut().push((font, c.slot)); return Ok((MathGeometry::default(), 0)); } + if let Some(face) = self.state.fonts.font(font)?.opentype() { + return crate::opentype::math_glyph(face, char::from_u32(c.slot).unwrap(), source); + } + let id = self.font(c.family, style)?; + let f = id.metrics(); + let byte = u8::try_from(c.slot).expect("available TFM character is a byte"); + let slot = char::from(byte); let italic = f.italic(slot); Ok(( MathGeometry { @@ -419,9 +439,9 @@ impl Converter<'_> { x: 0, y: 0, item: MathItem::NativeGlyph { - character: char::from(c.slot), + character: slot, font: id.clone(), - slot: c.slot, + slot: byte, size: id.size_sp(), }, }], @@ -550,7 +570,7 @@ impl Converter<'_> { let font = self .state .math_font(style.size_index() as u8, accent.family); - if !self.state.font_has_slot(font, accent.slot) { + if !self.has_math_char(font, accent.slot)? { self.missing.borrow_mut().push((font, accent.slot)); n.accent = None; } @@ -560,9 +580,11 @@ impl Converter<'_> { && n.class != NoadClass::Op && let MathField::Char(c) | MathField::TextChar(c) = n.nucleus { - let _ = self.font(c.family, style)?; let font = self.state.math_font(style.size_index() as u8, c.family); - if !self.state.font_has_slot(font, c.slot) { + if font == FontId::NULL { + self.font(c.family, style)?; + } + if !self.has_math_char(font, c.slot)? { self.missing.borrow_mut().push((font, c.slot)); n.nucleus = MathField::Empty; } @@ -576,7 +598,7 @@ impl Converter<'_> { let suppress = if let MathField::TextChar(c) = n.nucleus { self.state .fonts - .font(self.font(c.family, style)?.id)? + .font(self.state.math_font(style.size_index() as u8, c.family))? .space() .width != 0 @@ -614,11 +636,14 @@ impl Converter<'_> { && n.sup.is_none() && let MathField::Char(c) | MathField::TextChar(c) = n.nucleus { - let italic = g.metrics.width - - self - .font(c.family, style)? - .metrics() - .width(char::from(c.slot)); + let advance = match g.items.first().map(|item| &item.item) { + Some(MathItem::OpenType(run)) => run.width, + _ => { + let slot = u8::try_from(c.slot).expect("fetched TFM character is a byte"); + self.font(c.family, style)?.metrics().width(char::from(slot)) + } + }; + let italic = g.metrics.width - advance; g.metrics.width -= italic; noad_nodes.push(TextNode::MathChar(math_box(g))); if italic != 0 { diff --git a/crates/texrra-tex-core/src/execution/math_accent.rs b/crates/texrra-tex-core/src/execution/math_accent.rs index 805e676..34855ad 100644 --- a/crates/texrra-tex-core/src/execution/math_accent.rs +++ b/crates/texrra-tex-core/src/execution/math_accent.rs @@ -13,11 +13,11 @@ impl Converter<'_> { if let MathField::Char(c) = n.nucleus { let base_id = self.font(c.family, style)?; let base_font = self.state.math_font(style.size_index() as u8, c.family); - if !self.state.font_has_slot(base_font, c.slot) { + if !self.has_math_char(base_font, c.slot)? { self.missing.borrow_mut().push((base_font, c.slot)); n.nucleus = MathField::Empty; } else if let Ok(code) = u8::try_from(self.state.font_integers(base_font).skew) { - skew = base_id.metrics().kern(char::from(c.slot), char::from(code)); + skew = base_id.metrics().kern(char::from(c.slot as u8), char::from(code)); } } let mut base = self.field(&n.nucleus, style.cramped_style(), &n.source.nucleus)?; @@ -26,14 +26,14 @@ impl Converter<'_> { // Larger accents are chosen by actual TFM list tags and advance widths. let metrics = id.metrics(); let mut visited = std::collections::BTreeSet::new(); - while let Some(next) = metrics.next_larger(char::from(accent.slot)) { + while let Some(next) = metrics.next_larger(char::from(accent.slot as u8)) { if !visited.insert(accent.slot) { return Err("cyclic native accent size list".into()); } if !self.state.font_has_slot(font, next) || metrics.width(char::from(next)) > width { break; } - accent.slot = next; + accent.slot = u32::from(next); } let mut delta = height.min(i64::from(self.state.fonts.font(font)?.x_height())); if matches!(n.nucleus, MathField::Char(_)) && (n.sub.is_some() || n.sup.is_some()) { diff --git a/crates/texrra-tex-core/src/execution/math_code.rs b/crates/texrra-tex-core/src/execution/math_code.rs new file mode 100644 index 0000000..f20a27a --- /dev/null +++ b/crates/texrra-tex-core/src/execution/math_code.rs @@ -0,0 +1,77 @@ +//! One code table for the classic and Unicode views of math characters. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct MathCode(u32); + +impl MathCode { + pub(super) const ACTIVE: Self = Self(0x1f_ffff); + + pub(super) fn new(class: u8, family: u8, slot: u32) -> Self { + Self((u32::from(family) << 24) | (u32::from(class) << 21) | slot) + } + + pub(super) fn default_for(character: u32) -> Self { + match character { + 65..=90 | 97..=122 => Self::new(7, 1, character), + 48..=57 => Self::new(7, 0, character), + _ => Self::new(0, 0, character), + } + } + + pub(super) fn from_legacy(value: u16) -> Self { + if value == 0x8000 { + Self::ACTIVE + } else { + Self::new( + (value >> 12) as u8, + ((value >> 8) & 15) as u8, + u32::from(value & 255), + ) + } + } + + pub(super) fn from_word(value: i32) -> Result { + let code = Self(value as u32); + if code == Self::ACTIVE || code.slot() <= 0x10_ffff { + Ok(code) + } else if code.is_active() { + Err("Bad active XeTeX math code") + } else { + Err("Bad XeTeX math character code") + } + } + + pub(super) fn legacy(self) -> Option { + if self.is_active() { + Some(0x8000) + } else if self.slot() <= 255 && self.family() < 16 { + Some( + (u16::from(self.class()) << 12) + | (u16::from(self.family()) << 8) + | self.slot() as u16, + ) + } else { + None + } + } + + pub fn word(self) -> i32 { + self.0 as i32 + } + + pub fn is_active(self) -> bool { + self.slot() == Self::ACTIVE.0 + } + + pub fn slot(self) -> u32 { + self.0 & Self::ACTIVE.0 + } + + pub fn class(self) -> u8 { + ((self.0 >> 21) & 7) as u8 + } + + pub fn family(self) -> u8 { + (self.0 >> 24) as u8 + } +} diff --git a/crates/texrra-tex-core/src/execution/math_delimiter.rs b/crates/texrra-tex-core/src/execution/math_delimiter.rs index 641c142..4f4e708 100644 --- a/crates/texrra-tex-core/src/execution/math_delimiter.rs +++ b/crates/texrra-tex-core/src/execution/math_delimiter.rs @@ -107,7 +107,9 @@ impl Converter<'_> { continue; }; let m = id.metrics(); - let mut slot = c.slot; + let Ok(mut slot) = u8::try_from(c.slot) else { + continue; + }; let mut visited = std::collections::BTreeSet::new(); while id.has_slot(slot) { if !visited.insert(slot) { diff --git a/crates/texrra-tex-core/src/execution/math_op.rs b/crates/texrra-tex-core/src/execution/math_op.rs index c8293cc..7dda038 100644 --- a/crates/texrra-tex-core/src/execution/math_op.rs +++ b/crates/texrra-tex-core/src/execution/math_op.rs @@ -87,21 +87,21 @@ impl Converter<'_> { let (mut body, italic) = if let MathField::Char(mut c) = n.nucleus { let face = self.font(c.family, style)?; let mut source = n.source.nucleus.clone(); - let (mut b, italic) = if !self.state.font_has_slot(face.id, c.slot) { + let (mut b, italic) = if !self.has_math_char(face.id, c.slot)? { self.missing.borrow_mut().push((face.id, c.slot)); (self.pack_field(Vec::new())?, 0) } else { if style.display() { - if let Some(next) = face.metrics().next_larger(char::from(c.slot)) { + if let Some(next) = face.metrics().next_larger(char::from(c.slot as u8)) { if self.state.font_has_slot(face.id, next) { - c.slot = next; + c.slot = u32::from(next); source.paint = source .paint .derived(crate::provenance::Derivation::MathVariant); } } } - let italic = face.metrics().italic(char::from(c.slot)); + let italic = face.metrics().italic(char::from(c.slot as u8)); ( self.owned_field(&MathField::Char(c), style, &source)?, italic, diff --git a/crates/texrra-tex-core/src/execution/math_ord.rs b/crates/texrra-tex-core/src/execution/math_ord.rs index 2f229ba..2bb0975 100644 --- a/crates/texrra-tex-core/src/execution/math_ord.rs +++ b/crates/texrra-tex-core/src/execution/math_ord.rs @@ -37,14 +37,21 @@ impl Converter<'_> { if self.steps.get() > self.step_limit { return Err("native math ligature instruction limit exceeded".into()); } + let font = self.state.math_font(style.size_index() as u8, a.family); + if self.state.fonts.font(font)?.opentype().is_some() { + return Ok(()); + } q.nucleus = MathField::TextChar(a); let face = self.font(a.family, style)?; - if !self.state.font_has_slot(face.id, a.slot) { + if !self.has_math_char(face.id, a.slot)? { self.missing.borrow_mut().push((face.id, a.slot)); q.nucleus = MathField::Empty; return Ok(()); } - match face.metrics().lig_kern(Some(a.slot), b.slot) { + let Ok(right) = u8::try_from(b.slot) else { + return Ok(()); + }; + match face.metrics().lig_kern(Some(a.slot as u8), right) { Some(LigKernCommand::Kern(amount)) => { if processed + pending.len() + 2 > self.node_limit { return Err("native math noad capacity exceeded".into()); @@ -67,7 +74,7 @@ impl Converter<'_> { source.merge(&p.source.nucleus.paint); let source = FieldSource::paint(source.derived(Derivation::FontProgram)); let c = MathChar { - slot: replacement, + slot: u32::from(replacement), ..a }; match operation { diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 0341433..87a4501 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -22,6 +22,7 @@ mod ligature; mod marks; mod math; mod math_accent; +mod math_code; mod math_delimiter; mod math_fraction; mod math_op; @@ -74,6 +75,7 @@ pub use math::{ Delimiter, FieldSource, FractionSpec, MathChar, MathField, MathNode, MathRulePosition, NativeDisplay, NativeMath, Noad, NoadClass, NoadSource, OperatorLimits, }; +pub use math_code::MathCode; pub use page_builder::{NativePageState, PageTrace, PageTraceReport}; pub use paragraph::{LineBreakCache, LineBreakWork, NativeParagraph, ParagraphMode, TextNode}; pub use paragraph_trace::{ParagraphBreakKind, ParagraphTrace, ParagraphTraceReport}; @@ -448,6 +450,7 @@ pub enum Dependency { InputPosition(usize), OutputStream(u8), ParagraphToken, + UnicodeMathCode(u32), } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index d12beb9..06d38e1 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -353,6 +353,12 @@ pub enum Primitive { Rightmarginkern, Pdflastlink, Special, + Umathcode, + Umathcodenum, + Umathchar, + Umathcharnum, + Umathchardef, + Umathcharnumdef, } impl Primitive { @@ -483,6 +489,7 @@ pub enum Meaning { Register(Register), Parameter(Parameter), Font(FontId), + UnicodeMathCharGiven(super::MathCode), } /// Explicit bootstrap language selection. EtexBootstrap implements the native @@ -517,11 +524,12 @@ pub(super) enum Key { ParagraphShape, Spacefactor, Box(u16), - Mathcode(u8), + Mathcode(u32), Delcode(u8), Sfcode(u8), CaseCode(super::CaseCode, char), Mathfont(u8, u8), + Mathcodenum(u32), } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] @@ -537,7 +545,7 @@ pub(super) enum Saved { ParagraphShape(std::sync::Arc<[super::paragraph::ParagraphShapeLine]>), Font(FontId), Box(Option), - Mathcode(Option), + Mathcode(Option), Delcode(Option), Sfcode(Option), CaseCode(Option), @@ -654,7 +662,7 @@ pub struct State { boxes: BTreeMap, pub(super) split_marks: BTreeMap, pub(super) page_marks: BTreeMap, - mathcodes: BTreeMap, + mathcodes: BTreeMap, delcodes: BTreeMap, #[serde(default)] sfcodes: BTreeMap, @@ -1124,6 +1132,7 @@ impl Default for State { ] { state.parameters.insert(p, v); } + state.install_unicode_math_commands(); state } } @@ -1543,8 +1552,36 @@ impl State { } } } + self.install_unicode_math_commands(); self } + + fn install_unicode_math_commands(&mut self) { + use Primitive::*; + for (name, primitive) in [ + ("Umathcode", Umathcode), + ("XeTeXmathcode", Umathcode), + ("Umathcodenum", Umathcodenum), + ("XeTeXmathcodenum", Umathcodenum), + ("Umathchar", Umathchar), + ("XeTeXmathchar", Umathchar), + ("Umathcharnum", Umathcharnum), + ("XeTeXmathcharnum", Umathcharnum), + ("Umathchardef", Umathchardef), + ("XeTeXmathchardef", Umathchardef), + ("Umathcharnumdef", Umathcharnumdef), + ("XeTeXmathcharnumdef", Umathcharnumdef), + ] { + let name = CommandName::Control(name.into()); + let meaning = Meaning::Primitive(primitive); + if self.input_profile == super::InputProfile::UnicodeScalar { + self.commands.insert(name, meaning); + } else if self.commands.get(&name) == Some(&meaning) { + self.commands.remove(&name); + } + } + } + pub fn input_profile(&self) -> super::InputProfile { self.input_profile } @@ -1583,16 +1620,35 @@ impl State { .cloned() .unwrap_or(Meaning::Undefined) } - pub fn mathcode(&self, c: u8) -> u16 { - self.mathcodes.get(&c).copied().unwrap_or_else(|| { - if c.is_ascii_alphabetic() { - 0x7100 + c as u16 - } else if c.is_ascii_digit() { - 0x7000 + c as u16 - } else { - c as u16 - } - }) + /// Classic projection for byte-table consumers. A code outside the + /// representable classic range has TeX's recovery value of zero. + pub fn mathcode(&self, character: u8) -> u16 { + self.math_code(u32::from(character)).legacy().unwrap_or(0) + } + + pub fn math_code(&self, character: u32) -> super::MathCode { + self.mathcodes + .get(&character) + .copied() + .unwrap_or_else(|| super::MathCode::default_for(character)) + } + + pub(super) fn restore_legacy_mathcodes(&mut self) -> Result<(), String> { + for value in self.mathcodes.values_mut() { + let legacy = u16::try_from(value.word()) + .ok() + .filter(|&code| code <= 0x8000) + .ok_or("invalid legacy mathcode in native format")?; + *value = super::MathCode::from_legacy(legacy); + } + Ok(()) + } + + pub(super) fn math_family_count(&self) -> i32 { + match self.input_profile { + super::InputProfile::TeX8Bit => 16, + super::InputProfile::UnicodeScalar => 256, + } } pub fn math_font(&self, size: u8, family: u8) -> FontId { self.mathfonts @@ -1642,7 +1698,7 @@ impl State { self.save(Key::Delcode(c), global); self.delcodes.insert(c, n); } - pub(super) fn assign_mathcode(&mut self, c: u8, n: u16, global: bool) { + pub(super) fn assign_mathcode(&mut self, c: u32, n: super::MathCode, global: bool) { self.save(Key::Mathcode(c), global); self.mathcodes.insert(c, n); } @@ -1917,6 +1973,7 @@ impl State { Key::Font => Saved::Font(self.text_font), Key::Box(n) => Saved::Box(self.boxes.get(n).cloned()), Key::Mathcode(c) => Saved::Mathcode(self.mathcodes.get(c).copied()), + Key::Mathcodenum(_) => unreachable!("packed math code reads do not create save records"), Key::Delcode(c) => Saved::Delcode(self.delcodes.get(c).copied()), Key::Sfcode(c) => Saved::Sfcode(self.sfcodes.get(c).copied()), Key::CaseCode(kind, c) => Saved::CaseCode(self.case_codes.get(&(*kind, *c)).copied()), diff --git a/crates/texrra-tex-core/src/opentype.rs b/crates/texrra-tex-core/src/opentype.rs index 865e383..01e8f78 100644 --- a/crates/texrra-tex-core/src/opentype.rs +++ b/crates/texrra-tex-core/src/opentype.rs @@ -368,6 +368,53 @@ pub struct OpenTypeRun { pub sources: Vec<(usize, PaintSource)>, } +/// Materialize a single native math glyph using the final selected glyph, +/// its outline bounds and the font's MATH italic correction. +pub(crate) fn math_glyph( + font: &Arc, + character: char, + source: &PaintSource, +) -> Result<(crate::math_engine_tex::MathGeometry, i64), String> { + use crate::{ + math::MathBox, + math_engine_tex::{MathGeometry, MathItem, PositionedItem}, + }; + let mut run = font.shape(character.to_string(), vec![(0, source.clone())])?; + let [glyph] = run.glyphs.as_mut_slice() else { + return Err("OpenType math character did not select one glyph".into()); + }; + let face = font.face()?; + let id = GlyphId(glyph.id); + let scale = |value: i64| scale_units(value, font.size, face.units_per_em()); + let advance = scale(i64::from(face.glyph_hor_advance(id).unwrap_or(0))); + let bounds = face.glyph_bounding_box(id); + let height = scale(i64::from(bounds.map_or(0, |b| b.y_max))); + let depth = scale(-i64::from(bounds.map_or(0, |b| b.y_min))); + let italic = face + .tables() + .math + .and_then(|table| table.glyph_info) + .and_then(|info| info.italic_corrections) + .and_then(|values| values.get(id)) + .map_or(0, |value| scale(i64::from(value.value))); + glyph.x = 0; + glyph.y = 0; + glyph.advance = advance; + run.width = advance; + Ok(( + MathGeometry { + metrics: MathBox { width: advance + italic, height, depth }, + items: vec![PositionedItem { + source: source.clone(), + x: 0, + y: 0, + item: MathItem::OpenType(Arc::new(run)), + }], + }, + italic, + )) +} + pub(crate) fn horizontal_box(run: &Arc) -> crate::HorizontalBox { use crate::{ math::MathBox, diff --git a/crates/texrra-tex-core/tests/execution_math.rs b/crates/texrra-tex-core/tests/execution_math.rs index 0215872..f48590f 100644 --- a/crates/texrra-tex-core/tests/execution_math.rs +++ b/crates/texrra-tex-core/tests/execution_math.rs @@ -115,7 +115,10 @@ fn incomplete_math_fonts_modes_and_fields_are_strict_errors() { r"\advance\mathcode0 by1", ] { assert!( - Executor::new(State::initex().with_etex(), Limits::default()) + Executor::new( + State::initex().with_etex().with_input_profile(InputProfile::TeX8Bit), + Limits::default(), + ) .run( SourceFile { name: "bad.tex".into(), diff --git a/crates/texrra-tex-core/tests/execution_paragraphs.rs b/crates/texrra-tex-core/tests/execution_paragraphs.rs index bbbfa38..d6a88c2 100644 --- a/crates/texrra-tex-core/tests/execution_paragraphs.rs +++ b/crates/texrra-tex-core/tests/execution_paragraphs.rs @@ -122,7 +122,7 @@ fn initex_font_and_unsupported_material_are_not_silently_substituted() { assert!( e.events .iter() - .any(|e| matches!(e,Event::MissingGlyph(m) if m.font==FontId::NULL&&m.slot==b'A')) + .any(|e| matches!(e,Event::MissingGlyph(m) if m.font==FontId::NULL&&m.slot==u32::from(b'A'))) ); let sized = Executor::default() .run( diff --git a/crates/texrra-tex-core/tests/execution_unicode_math_codes.rs b/crates/texrra-tex-core/tests/execution_unicode_math_codes.rs new file mode 100644 index 0000000..e504409 --- /dev/null +++ b/crates/texrra-tex-core/tests/execution_unicode_math_codes.rs @@ -0,0 +1,95 @@ +use texrra_tex_core::execution::{ + Dependency, Event, Executor, InputProfile, Limits, NoFiles, SourceFile, State, +}; + +const HEADER: &str = r"\catcode123=1 \catcode125=2 \catcode35=6 "; + +fn probe( + text: &str, + profile: InputProfile, +) -> Result { + Executor::new( + State::initex().with_etex().with_input_profile(profile), + Limits::default(), + ) + .run( + SourceFile { + name: "codes.tex".into(), + data: format!("{HEADER}{text}").into_bytes(), + }, + &mut NoFiles, + ) + .map_err(|error| error.message) +} + +#[test] +fn classic_and_unicode_commands_share_scoped_math_codes() { + let result = probe( + r#"\message{D=\the\Umathcodenum"03B1} + \Umathcode"03B1=7 5 "03B2 + \message{A=\the\Umathcodenum"03B1} + {\XeTeXmathcode"03B1=2 255 "10FFFF + \message{L=\the\XeTeXmathcodenum"03B1}} + \message{R=\the\Umathcodenum"03B1} + \mathcode"03B1="8000 + \message{T=\the\mathcode"03B1} + \message{N=\the\Umathcodenum"03B1} + {\global\Umathcode"03B1=0 3 42}\message{G=\the\mathcode"03B1}"#, + InputProfile::UnicodeScalar, + ) + .unwrap(); + let output: Vec<_> = result + .events + .iter() + .filter_map(|event| match event { + Event::Message { text, .. } => Some(text.trim()), + _ => None, + }) + .collect(); + assert_eq!( + output, + [ + "D=945", + "A=98567090", + "L=-11468801", + "R=98567090", + "T=32768", + "N=2097151", + "G=810" + ] + ); + assert!(result.reads.contains(&Dependency::UnicodeMathCode(945))); +} + +#[test] +fn unicode_math_code_invalid_queries_preserve_distinct_diagnostics() { + for (source, expected) in [ + (r"\message{\the\Umathcode65}", r"try \Umathcodenum"), + ( + r"\Umathcode65=0 17 65 \message{\the\mathcode65}", + "Extended mathchar used as mathchar", + ), + (r#"\Umathcodenum65="3FFFFF"#, "Bad active XeTeX math code"), + (r"\Umathcode65=8 0 65", "Bad math class"), + (r"\Umathcode65=0 256 65", "math family"), + ] { + let error = probe(source, InputProfile::UnicodeScalar).unwrap_err(); + assert!(error.contains(expected), "{source}: {error}"); + } + let byte_error = probe(r"\Umathcode65=0 0 65", InputProfile::TeX8Bit).unwrap_err(); + assert!(byte_error.contains("undefined native control sequence")); +} + +#[test] +fn packed_code_with_the_sign_bit_only_is_an_internal_integer() { + let result = probe( + r"\Umathcode65=0 128 0 + \Umathcodenum66=\Umathcodenum65 + \message{\number\Umathcodenum65/\the\Umathcodenum66}", + InputProfile::UnicodeScalar, + ) + .unwrap(); + assert!(result.events.iter().any(|event| matches!( + event, Event::Message { text, .. } if text == "-2147483648/-2147483648" + ))); +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index fd80bcd..c45b753 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -2175,6 +2175,35 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。 全量编译一致。incremental-receipt.json 的 SHA-256 为 bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。 +### Unicode 数学编码和实际数学字形 + +Unicode 入口的经典 \mathcode 与 \Umathcode、\Umathcodenum 共用 +一张码位表。三字段编码、带符号的 32 位查询、活性字符和分组恢复进入 +同一执行状态。\Umathchar、\Umathcharnum、\Umathchardef 及数值定义 +可向原生 noad 提供实际码位和最多 256 个字体族,对应 XeTeX 旧名称同步 +识别。兼容的 8 位入口保有 16 族及原有查询诊断,TeX 代码表保持实际依赖。 + +新测量使用 Fedora 官方 texlive-lm-math svn67718-8.fc44 的 +Latin Modern Math 及相同 CM TFM,含第 42 字体族、普通和活性码位、 +补充平面字符 U+1D6FC 及两种数学字符定义。对照 XeTeX 0.999998 的 +四个实际字形编号和位置一致,三个盒的尺寸一致,600 dpi 灰度图一致。 +第一版在取负方向边界后有 1 sp 深度差,改用先计算深度再做 XeTeX +固定点舍入。原始失败产物、配置、字体摘要和最终回执位于 +target/p3-xetex-mathcode。geometry-receipt.json SHA-256 为 +e9075a923ea91156b94480e3a0ff932a06a9334841ecab0ba780b6015f825449。 + +28 项定向回归通过。数值查询与参考逐项一致,schema58 保存实际宽位 +数学码。原有 schema56 的原样 XeLaTeX 格式重载,加号和等号的数学码 +与旧二进制一致。三页会话只编辑外部 codes.tex,复用 1047 步, +只替换第二页,增量 PDF、页面和来源映射与独立全量一致。 +完整 OpenType 数学常量、变体、伸缩分隔符与后端选择仍待接通。 +同源发布版运行原样 xelatex.ini 后,未改的 latex.ltx 确认选中 256 族 +分支。实际作业在第 397 行的 \chardef\e@mathgroup@top=256、3304 步 +处停下,当前宽字符定义仍需接通。完整日志和失败证据保留于 +target/p3-xetex-mathcode/xelatex-native。 +[XeTeX 数学码赋值](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L25737-L25818) +[XeTeX 原生数学字形与取度](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/XeTeX_ext.c#L2077-L2109) + ### 实际 special 出页和 XeTeX 设备几何 原生列表保存 \special 和 \special shipout。普通指令在扫描时展开,延迟 diff --git a/tests/native_pipeline.rs b/tests/native_pipeline.rs index 60ba5c4..df80ba8 100644 --- a/tests/native_pipeline.rs +++ b/tests/native_pipeline.rs @@ -484,6 +484,90 @@ fn resumed_suffix_reuses_search_for_unchanged_paragraphs() { fs::remove_dir_all(p).unwrap(); } +#[test] +fn unicode_math_code_edit_updates_the_page_that_reads_the_table() { + let p = directory("unicode-math-code"); + let mut request = request(&p); + request.world = WorldConfig::new(&p); + request.input_profile = texrra_tex_core::execution::InputProfile::UnicodeScalar; + let entry = p.join("main.tex"); + let codes = p.join("codes.tex"); + let padding = format!("{}\n", "\\relax ".repeat(26)).repeat(45); + let source = format!( + r#"\catcode123=1 \catcode125=2 \catcode36=3 + \font\sy=cmsy10 \font\ex=cmex10 + \textfont2=\sy \scriptfont2=\sy \scriptscriptfont2=\sy + \textfont3=\ex \scriptfont3=\ex \scriptscriptfont3=\ex + \font\unicode="[LiberationSerif-Regular.ttf]" at 10pt + \textfont42=\unicode + \shipout\hbox{{\vrule width7pt height8pt}} + {padding} + \input codes.tex + \shipout\hbox{{$α$}} + \shipout\hbox{{\vrule width9pt height8pt}} + \end + "# + ); + let project = ProjectSnapshot::new(ProjectDefinition { + configuration: request.world.clone(), + revision: 1, + roots: [p.clone()].into(), + files: [ + (entry, Arc::from(source.into_bytes())), + ( + p.join("cmsy10.tfm"), + Arc::from(include_bytes!("../crates/texrra-tex-core/assets/cmsy10.tfm").as_slice()), + ), + ( + p.join("cmex10.tfm"), + Arc::from(include_bytes!("../crates/texrra-tex-core/assets/cmex10.tfm").as_slice()), + ), + ( + p.join("LiberationSerif-Regular.ttf"), + Arc::from(include_bytes!("../assets/fonts-subset/LiberationSerif-Regular.ttf").as_slice()), + ), + (codes.clone(), Arc::from(br#"\Umathcode"03B1=0 42 65"#.as_slice())), + ] + .into(), + directories: Default::default(), + aliases: Default::default(), + generated_roots: [p.clone()].into(), + generated: Default::default(), + }) + .unwrap(); + let compiler = NativeCompiler::default().with_automatic_entry_checkpoints(); + let before = compiler + .compile(request.clone().with_project(project.clone())) + .unwrap(); + let after_project = project + .with_file_edits( + 2, + [(codes, Arc::from(br#"\Umathcode"03B1=0 42 66"#.as_slice()))].into(), + ) + .unwrap(); + let request = request.with_project(after_project); + let after = compiler.compile(request.clone()).unwrap(); + let full = NativeCompiler::default().compile(request).unwrap(); + assert!(after.entry_checkpoint_work.reused_steps > 0); + assert_eq!(after.pdf, full.pdf); + assert_ne!(after.pdf, before.pdf); + assert_eq!(after.pages, full.pages); + assert_eq!(after.source_map.pages, full.source_map.pages); + let changes: Vec<_> = after + .preview_since(Some(before.revision())) + .unwrap() + .pages + .iter() + .map(|page| page.index) + .collect(); + assert_eq!(changes, [1]); + eprintln!( + "Unicode math-code edit reused {} steps and replaced pages {:?}", + after.entry_checkpoint_work.reused_steps, changes + ); + fs::remove_dir_all(p).unwrap(); +} + #[test] fn checkpoint_keeps_late_special_tokens_until_the_updated_page_is_shipped() { let p = directory("late-special");