diff --git a/crates/texrra-tex-core/src/execution/diagnostics.rs b/crates/texrra-tex-core/src/execution/diagnostics.rs index acbe18c..4dab6f3 100644 --- a/crates/texrra-tex-core/src/execution/diagnostics.rs +++ b/crates/texrra-tex-core/src/execution/diagnostics.rs @@ -405,6 +405,14 @@ impl Printer<'_> { self.command("relax"); self.literal(" "); } + TokenKind::Command(CommandName::FrozenPrimitivePrefix) => { + self.command(self.state.primitive_prefix_name()); + self.literal(" "); + } + TokenKind::Command(CommandName::FrozenPrimitive(name)) => { + self.command(name); + self.literal(" "); + } TokenKind::Command(CommandName::Font(font)) => { let name = self.state.fonts.font(*font)?.identifier_text(); self.command(&name); diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index d076417..abaaa59 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -655,6 +655,9 @@ impl Executor { TokenKind::Command(CommandName::FrozenRelax) => { self.fail("frozen relax cannot be redefined") } + TokenKind::Command( + CommandName::FrozenPrimitivePrefix | CommandName::FrozenPrimitive(_), + ) => self.fail("frozen primitive cannot be redefined"), TokenKind::Command(CommandName::Font(_)) => { self.fail("frozen font identifier cannot be redefined") } @@ -662,6 +665,34 @@ impl Executor { _ => self.fail("expected a control sequence or active character"), } } + fn frozen_primitive(&self, token: &Token) -> Option<(InputToken, bool)> { + let TokenKind::Command(name) = &token.kind else { + return None; + }; + let (name, meaning) = self.state.original_primitive(name)?; + let expandable = matches!(meaning, Meaning::Primitive(p) if p.expandable()); + let token = Token { + kind: TokenKind::Command(CommandName::FrozenPrimitive(name.into())), + ..token.clone() + }; + Some((token.into(), expandable)) + } + + fn deferred_internal_primitive( + &mut self, + prefix: InputToken, + files: &mut impl SourceProvider, + ) -> Result { + let operand = self.required_raw(files)?; + Ok(self.frozen_primitive(&operand.token).map_or_else( + || Token { + kind: TokenKind::Command(CommandName::FrozenRelax), + ..prefix.token + }.into(), + |(operand, _)| operand, + )) + } + fn expanded(&mut self, files: &mut impl SourceProvider) -> Result, Error> { self.expanded_context(files, false) } @@ -830,12 +861,26 @@ impl Executor { break Some(input); } let meaning = self.meaning(&input.token); - if !matches!(meaning, Meaning::Primitive(Primitive::Expandafter)) { + let Meaning::Primitive(command @ (Primitive::Expandafter | Primitive::UsePrimitive)) = meaning else { break self.expand_one_inner(input, meaning, files, definition_context)?; - } + }; if self.read_parameter(Parameter::Tracingcommands).width() > 1 { self.trace_command(&input.token, files)?; } + if command == Primitive::UsePrimitive { + let operand = self.normal_raw(files)?; + let Some((original, expandable)) = self.frozen_primitive(&operand.token) else { + break None; + }; + if expandable { + input = original; + definition_context = false; + continue; + } + self.unread(operand)?; + input.token.kind = TokenKind::Command(CommandName::FrozenPrimitivePrefix); + break Some(input); + } // Expanding the second token is the same dispatch with deferred // input. Only a re-entry from a scanner needs a new expansion frame. if let Some(outer) = first.replace(self.required_raw(files)?) { @@ -1222,7 +1267,10 @@ impl Executor { } fn the_value(&mut self, files: &mut impl SourceProvider) -> Result { use Primitive::*; - let next = self.expanded_non_space(files)?; + let mut next = self.expanded_non_space(files)?; + if self.primitive(&next.token) == Some(DeferredPrimitive) { + next = self.deferred_internal_primitive(next, files)?; + } let text = match self.meaning(&next.token) { Meaning::Font(font) => { let mut token = next.token; @@ -1527,7 +1575,8 @@ impl Executor { &operand.token.kind, TokenKind::Command(name) if !Self::suppresses_meaning(&operand, &live) - && self.state.original_primitive(name) == Some(&live) + && self.state.original_primitive(name) + .is_some_and(|(_, meaning)| *meaning == live) ) } Ifcsname => { @@ -2620,6 +2669,11 @@ impl Executor { _ => break token, } }; + let first = if first.token.kind == TokenKind::Command(CommandName::FrozenPrimitivePrefix) { + self.deferred_internal_primitive(first, files)? + } else { + first + }; if let TokenKind::Character('\u{0060}', CatCode::Other) = first.token.kind { let next = self.required_raw(files)?; let character = match &next.token.kind { @@ -3272,6 +3326,10 @@ impl Executor { } TokenKind::Command(CommandName::Control(name)) => format!("\\{name}"), TokenKind::Command(CommandName::FrozenRelax) => "\\relax".into(), + TokenKind::Command(CommandName::FrozenPrimitive(name)) => format!("\\{name}"), + TokenKind::Command(CommandName::FrozenPrimitivePrefix) => { + format!("\\{}", self.state.primitive_prefix_name()) + } TokenKind::Command(CommandName::Font(font)) => { format!("\\{}", self.font_token_name(*font)) } @@ -3474,6 +3532,10 @@ impl Executor { } TokenKind::Command(CommandName::Control(name)) => format!("{escape}{name}"), TokenKind::Command(CommandName::FrozenRelax) => format!("{escape}relax"), + TokenKind::Command(CommandName::FrozenPrimitive(name)) => format!("{escape}{name}"), + TokenKind::Command(CommandName::FrozenPrimitivePrefix) => { + format!("{escape}{}", self.state.primitive_prefix_name()) + } TokenKind::Command(CommandName::Font(font)) => { self.reads.insert(Dependency::FontResources); format!("{escape}{}", self.font_token_name(*font)) @@ -3494,7 +3556,9 @@ impl Executor { text } fn message_token(&mut self, token: &Token) -> std::string::String { - if matches!(token.kind, TokenKind::Command(CommandName::Font(_))) { + if matches!(token.kind, TokenKind::Command( + CommandName::Font(_) | CommandName::FrozenPrimitivePrefix | CommandName::FrozenPrimitive(_) + )) { return format!("{} ", self.string_token(&token.kind)); } @@ -4030,6 +4094,18 @@ impl Executor { self.paragraph.as_mut().unwrap().nodes.push(space); } } + DeferredPrimitive => { + let operand = self.normal_raw(files)?; + if let Some((original, expandable)) = self.frozen_primitive(&operand.token) { + if expandable { + return self.fail(format!( + "misplaced {}", + self.token_string(&original.token.kind) + )); + } + self.unread(original)?; + } + } Ignorespaces => { while let Some(next) = self.expanded(files)? { if !self.is_spacer(&next.token) { diff --git a/crates/texrra-tex-core/src/execution/engine/case.rs b/crates/texrra-tex-core/src/execution/engine/case.rs index 2d636b1..12b8033 100644 --- a/crates/texrra-tex-core/src/execution/engine/case.rs +++ b/crates/texrra-tex-core/src/execution/engine/case.rs @@ -18,7 +18,8 @@ impl Executor { let c = match &mut token.kind { TokenKind::Character(c, _) | TokenKind::Command(CommandName::Active(c)) => c, TokenKind::Command( - CommandName::Control(_) | CommandName::Font(_) | CommandName::FrozenRelax, + CommandName::Control(_) | CommandName::Font(_) | CommandName::FrozenRelax + | CommandName::FrozenPrimitivePrefix | CommandName::FrozenPrimitive(_), ) => continue, }; self.reads.insert(Dependency::CaseCode(kind, *c)); diff --git a/crates/texrra-tex-core/src/execution/engine/input.rs b/crates/texrra-tex-core/src/execution/engine/input.rs index 5d5c283..68978e7 100644 --- a/crates/texrra-tex-core/src/execution/engine/input.rs +++ b/crates/texrra-tex-core/src/execution/engine/input.rs @@ -387,11 +387,19 @@ impl Executor { reads: &mut BTreeSet, ) { match name { - CommandName::FrozenRelax => { + CommandName::FrozenRelax | CommandName::FrozenPrimitivePrefix + | CommandName::FrozenPrimitive(_) => { if let Ok(escape) = u8::try_from(self.state.escapechar) { out.character(char::from(escape)); } - out.text("relax "); + let name = match name { + CommandName::FrozenRelax => "relax", + CommandName::FrozenPrimitivePrefix => self.state.primitive_prefix_name(), + CommandName::FrozenPrimitive(name) => name, + _ => unreachable!(), + }; + out.text(name); + out.push(' '); } CommandName::Font(font) => { reads.insert(Dependency::FontResources); @@ -569,7 +577,8 @@ impl Executor { .unwrap_or_default(); format!("{escape}{} ", self.font_token_name(*font)) } - CommandName::FrozenRelax => unreachable!("frozen relax is not a macro"), + CommandName::FrozenRelax | CommandName::FrozenPrimitivePrefix + | CommandName::FrozenPrimitive(_) => unreachable!("frozen primitive is not a macro"), CommandName::Active(c) => c.to_string(), CommandName::Control(name) => { if name.chars().count() == 1 { diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index 2bbcf85..e08f398 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -882,7 +882,7 @@ impl Executor { | Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand | Knbccode | Knaccode | Letterspacefont | Textfont | Scriptfont | Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time - | Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage + | Day | Month | Year | BeginGroup | EndGroup | Relax | DeferredPrimitive | Message | Errmessage | Endinput | Showbox | Show | Showthe | Showtokens | Showlists | Showifs | Showgroups | Discretionary | DiscretionaryHyphen | Parshape | LinePenalties(_) | Partokenname => { diff --git a/crates/texrra-tex-core/src/execution/font_catalog.rs b/crates/texrra-tex-core/src/execution/font_catalog.rs index 8954f5d..7c6ec96 100644 --- a/crates/texrra-tex-core/src/execution/font_catalog.rs +++ b/crates/texrra-tex-core/src/execution/font_catalog.rs @@ -100,7 +100,8 @@ impl FontInstance { CommandName::Control(name) if name.is_empty() => "FONT".into(), CommandName::Control(name) => name.clone(), CommandName::Active(c) => format!("FONT{c}"), - CommandName::Font(_) | CommandName::FrozenRelax => { + CommandName::Font(_) | CommandName::FrozenRelax + | CommandName::FrozenPrimitivePrefix | CommandName::FrozenPrimitive(_) => { unreachable!("a frozen id is not a definition selector") } } @@ -334,7 +335,7 @@ impl FontCatalog { defaults: FontIntegers, optional: bool, ) -> Result { - if matches!(selector, CommandName::Font(_) | CommandName::FrozenRelax) { + if !matches!(selector, CommandName::Control(_) | CommandName::Active(_)) { return Err(FontLoadError::Fatal("frozen font identifiers cannot name font definitions".into())); } size.validate()?; diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 3405eb6..5e8eef2 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -16,9 +16,9 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 101; -const COMPATIBLE_SCHEMAS: [u32; 67] = [ - 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, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, SCHEMA, +const SCHEMA: u32 = 102; +const COMPATIBLE_SCHEMAS: [u32; 68] = [ + 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, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, SCHEMA, ]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); @@ -217,8 +217,8 @@ impl FormatImage { if image.schema < 100 { image.state.install_line_penalty_primitives(); } - if image.schema < 101 { - image.state.install_primitive_inspection(); + if image.schema < 102 { + image.state.install_primitive_commands(); } let pdf_objects = image.state.pdf_objects.as_deref(); let mut numbered_images = 0; diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index bb61af3..97b7434 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -16,12 +16,18 @@ pub enum CommandName { /// It retains the loaded font even when the spelling selector is redefined. Font(FontId), FrozenRelax, + /// Preserved in token lists before the ordinary token naming the operand. + FrozenPrimitivePrefix, + /// The selected primitive meaning, which survives putting a token back. + FrozenPrimitive(String), } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum Primitive { Relax, Ignorespaces, + UsePrimitive, + DeferredPrimitive, Explicitspace, Par, BeginGroup, @@ -495,6 +501,7 @@ impl Primitive { | Firstmarks | Botmarks | Noexpand + | UsePrimitive | Expandafter | Number | Uchar @@ -1357,7 +1364,7 @@ impl Default for State { state.parameters.insert(p, v); } state.install_pdftex_primitives(); - state.install_primitive_inspection(); + state.install_primitive_commands(); state.install_unicode_commands(); state } @@ -1596,7 +1603,7 @@ impl State { use Primitive::*; self.profile = Profile::EtexBootstrap; self.install_line_penalty_primitives(); - self.install_primitive_inspection(); + self.install_primitive_commands(); let hook = TokenParameter::Everyeof; self.commands.insert( CommandName::Control(hook.name()), @@ -1942,14 +1949,16 @@ impl State { self.install_unicode_commands(); self.install_xetex_etex_commands(); self.install_direction_commands(); - self.install_primitive_inspection(); + self.install_primitive_commands(); self } - pub(super) fn install_primitive_inspection(&mut self) { + pub(super) fn install_primitive_commands(&mut self) { let xe = self.input_profile == super::InputProfile::XeTeX; self.update_profile_command("ifprimitive", Meaning::Primitive(Primitive::Ifprimitive), xe); self.update_profile_command("ifpdfprimitive", Meaning::Primitive(Primitive::Ifpdfprimitive), !xe); + self.update_profile_command("primitive", Meaning::Primitive(Primitive::UsePrimitive), xe); + self.update_profile_command("pdfprimitive", Meaning::Primitive(Primitive::UsePrimitive), !xe); self.update_profile_command( "showtokens", Meaning::Primitive(Primitive::Showtokens), @@ -2049,7 +2058,14 @@ impl State { ); } + pub(super) fn primitive_prefix_name(&self) -> &'static str { + if self.input_profile == super::InputProfile::XeTeX { "primitive" } else { "pdfprimitive" } + } + pub(super) fn profile_primitive_name(&self, primitive: Primitive) -> Option<&'static str> { + if matches!(primitive, Primitive::UsePrimitive | Primitive::DeferredPrimitive) { + return Some(self.primitive_prefix_name()); + } if self.input_profile == super::InputProfile::XeTeX { return XETEX_PRIMITIVE_ALIASES .iter() @@ -2122,10 +2138,13 @@ impl State { }) } /// Built-in meanings before any macro, alias or format assignments. - pub(super) fn original_primitive(&self, name: &CommandName) -> Option<&'static Meaning> { + pub(super) fn original_primitive<'a>( + &self, + name: &'a CommandName, + ) -> Option<(&'a str, &'static Meaning)> { use super::InputProfile; use std::sync::OnceLock; - type CommandCatalogue = OnceLock>; + type CommandCatalogue = OnceLock>; static CATALOGUES: [[CommandCatalogue; 2]; 3] = [const { [const { OnceLock::new() }; 2] }; 3]; @@ -2134,27 +2153,36 @@ impl State { InputProfile::UnicodeScalar => 1, InputProfile::XeTeX => 2, }; + let name = match name { + CommandName::Control(name) | CommandName::FrozenPrimitive(name) => name.as_str(), + CommandName::FrozenPrimitivePrefix => self.primitive_prefix_name(), + CommandName::FrozenRelax => "relax", + CommandName::Font(FontId::NULL) => "nullfont", + _ => return None, + }; let extended = self.profile == Profile::EtexBootstrap; CATALOGUES[input][usize::from(extended)] .get_or_init(|| { let state = Self::initex().with_input_profile(self.input_profile); let state = if extended { state.with_etex() } else { state }; - state.commands + state.commands.into_iter().filter_map(|(name, meaning)| match name { + CommandName::Control(name) => Some((name, meaning)), + _ => None, + }).collect() }) .get(name) + .map(|meaning| (name, meaning)) } pub fn meaning(&self, name: &CommandName) -> Meaning { - if *name == CommandName::FrozenRelax { - return Meaning::Primitive(Primitive::Relax); + match name { + CommandName::FrozenRelax => Meaning::Primitive(Primitive::Relax), + CommandName::FrozenPrimitivePrefix => Meaning::Primitive(Primitive::DeferredPrimitive), + CommandName::FrozenPrimitive(_) => self.original_primitive(name) + .map(|(_, meaning)| meaning.clone()).unwrap_or(Meaning::Undefined), + CommandName::Font(font) => Meaning::Font(*font), + _ => self.commands.get(name).cloned().unwrap_or(Meaning::Undefined), } - if let CommandName::Font(font) = name { - return Meaning::Font(*font); - } - self.commands - .get(name) - .cloned() - .unwrap_or(Meaning::Undefined) } /// Classic projection for byte-table consumers. A code outside the /// representable classic range has TeX's recovery value of zero. diff --git a/crates/texrra-tex-core/tests/execution_conditional_trace.rs b/crates/texrra-tex-core/tests/execution_conditional_trace.rs index 42af4a7..9d8493b 100644 --- a/crates/texrra-tex-core/tests/execution_conditional_trace.rs +++ b/crates/texrra-tex-core/tests/execution_conditional_trace.rs @@ -131,3 +131,39 @@ fn primitive_inspection_requires_the_original_name_and_live_meaning() { assert!(result.reads.contains(&Dependency::Meaning(CommandName::Control("hbox".into())))); } } + +#[test] +fn primitive_execution_preserves_the_deferred_prefix_across_expanded_definitions() { + for (profile, spelling) in [ + (InputProfile::TeX8Bit, r"\pdfprimitive"), + (InputProfile::XeTeX, r"\primitive"), + ] { + let source = r"\catcode123=1 \catcode125=2 + \let\p=PREFIX \let\outerbox=\hbox + \count0=37 + \def\count{\errmessage{live count}} + \def\iftrue{\errmessage{live iftrue}} + \edef\saved{\p\hbox{\p\iftrue\vrule width9pt height1pt\else\errmessage{branch}\fi}} + \def\hbox{\errmessage{live hbox}} + \setbox0=\outerbox{\saved} + \message{VALUES:\number\p\count0/\the\wd0} + \p\unregistered + \end" + .replace("PREFIX", spelling); + let result = Executor::new( + State::initex().with_etex().with_input_profile(profile), + Limits::default(), + ) + .run( + SourceFile { + name: "primitive.tex".into(), + data: source.into_bytes(), + }, + &mut NoFiles, + ) + .unwrap(); + assert!(result.events.iter().any(|event| matches!( + event, Event::Message { text, .. } if text == "VALUES:37/9.0pt" + ))); + } +} diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index 5474a78..757139b 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -18,6 +18,33 @@ | W6 会话 | 实施中 | 共享库/CLI 与当前原生文字/数学/规则来源进入公共结果;真实 A4 副本九类/27 revision 与独立干净作业页面/PDF/aux/映射一致,新增数学场景独立参考通过;详细失败/捕获重放及宿主/离线/CLI观察已通过;原子项目版本/已知生成初态及TeX流记录已接通;完整副作用/恢复契约、旧来源和性能仍缺 | | W7 总验收 | 未满足 | 原有和新增测试、原样项目、格式与会话门禁全部通过才能结项 | +## 2026-11-28 执行原始原语 + +pdfTeX 的 `\pdfprimitive` 与 XeTeX 的 `\primitive` 按当前兼容模式的 +初始命令表取回原语。可展开的原语立即进入展开器。其余命令保留内部执行 +前缀及普通操作数记号,由主命令、整数扫描或 `\the` 内部量扫描在实际 +需要时取回原始含义。内部前缀能进入展开定义、格式镜像和记号输出。 +[pdfTeX 的原语执行](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L9019-L9082) +· [XeTeX 的原语执行](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/xetexdir/xetex.web#L9035-L9099) + +上一阶段报 `extra else` 的冻结输入现已在两种模式读出 37 并绘制 Yes。 +扩展对照覆盖原语调用别名、嵌套前缀、展开定义中的 `\the` 和数值扫描。 +两种模式各有 9 条查询及 3 页文字词框和 144 DPI 灰度图精确一致。 +实际写出的 `replay.tex` 与参考逐字节一致,重新输入后完成绘制。 +三项 pdfTeX 诊断对照确认了不适用的延期操作数、盒扫描和尺寸单位边界。 + +schema102 持久化生成真实盒及读取寄存器的内部前缀,两种最小镜像重载 +分别与对应参考的查询和光栅一致。schema101 重载保留同名用户宏。 +从原样 `pdflatex.ini` 和 `xelatex.ini` 生成的既有 schema100 镜像 +均加载真实 `article.cls` 并完成一页,原语读取值 37,盒宽 8.0 pt。 + +三页项目两次修改并恢复子文件中的原始寄存器赋值,每次复用 1,112 步, +只刷新第二页。PDF、页面、SVG、日志、辅助文件和来源映射均与独立 +全量编译一致。发布构建和三项定向回归通过。 + +回执在 `target/p2-native-primitive-execution`,`receipt.json` 的 SHA-256 为 +`dfe65d449520e0a6c0f2855308f59db4b76274fcaa2cfaf23523ece09b656c8b`。 + ## 2026-11-28 原语身份判断与未展开记号诊断 pdfTeX 的 `\ifpdfprimitive` 和 XeTeX 的 `\ifprimitive` 对照当前