From 13ab32247d7e956d4ab88375e82f99fd1a16225b Mon Sep 17 00:00:00 2001 From: GloamXun Date: Sat, 21 Nov 2026 01:49:10 +0800 Subject: [PATCH] Implement native paragraph token naming and execution contexts --- .../texrra-tex-core/src/execution/engine.rs | 51 +++++++++++++------ .../src/execution/engine/alignment.rs | 11 +++- .../src/execution/engine/math.rs | 2 +- .../src/execution/format_image.rs | 4 +- crates/texrra-tex-core/src/execution/mod.rs | 1 + crates/texrra-tex-core/src/execution/mouth.rs | 5 +- .../src/execution/parameters.rs | 2 + crates/texrra-tex-core/src/execution/state.rs | 30 ++++++++++- .../tests/execution_fractions.rs | 2 +- .../tests/execution_pdf_unicode.rs | 2 +- .../tests/execution_vcenter.rs | 2 +- docs/P2_M1_PROGRESS.md | 30 +++++++++++ 12 files changed, 118 insertions(+), 24 deletions(-) diff --git a/crates/texrra-tex-core/src/execution/engine.rs b/crates/texrra-tex-core/src/execution/engine.rs index 1cd2a32..8d5ca38 100644 --- a/crates/texrra-tex-core/src/execution/engine.rs +++ b/crates/texrra-tex-core/src/execution/engine.rs @@ -1666,7 +1666,7 @@ impl Executor { Ok(replacement) } fn paragraph_argument(&self, token: &Token, long: bool) -> Result<(), Error> { - if !long && token.kind == TokenKind::Command(CommandName::Control("par".into())) { + if !long && self.state.is_paragraph_token(&token.kind) { return Err(self.error( "paragraph ended before non-long macro argument was complete", token.span, @@ -1737,6 +1737,9 @@ impl Executor { } self.consume_macro_delimiter(expected); } + if !definition.long && !definition.parameters.is_empty() { + self.reads.insert(Dependency::ParagraphToken); + } let mut arguments = Vec::new(); for (index, delimiter) in definition.parameters.iter().enumerate() { let mut argument = Vec::new(); @@ -3397,6 +3400,24 @@ impl Executor { } Ok(initial_depth) } + fn insert_paragraph_token(&mut self, span: Span) -> Result<(), Error> { + self.reads.insert(Dependency::ParagraphToken); + self.push(vec![Token::new(self.state.paragraph_token(), span).into()]) + } + + fn in_unrestricted_horizontal_mode(&self) -> bool { + self.paragraph.is_some() && self.math.is_empty() && !self.restricted() + } + + fn group_end_needs_paragraph_token(&mut self) -> bool { + let minimum = match self.state.group_kind() { + Some(GroupKind::Vbox | GroupKind::Vtop | GroupKind::Vcenter) => 1, + Some(GroupKind::Insertion | GroupKind::Output | GroupKind::NoAlign) => 2, + _ => return false, + }; + self.read_parameter(Parameter::Partokencontext).width() >= minimum + } + fn run_active_input( &mut self, initial_depth: usize, @@ -3425,11 +3446,8 @@ impl Executor { self.trace_command(&token, files)?; } } - if self.native_page.is_some() - && self.paragraph.is_some() - && self.math.is_empty() - && !self.restricted() - && matches!( + if self.in_unrestricted_horizontal_mode() + && (matches!( &meaning, Meaning::Primitive( Primitive::End @@ -3446,21 +3464,19 @@ impl Executor { | Primitive::Splitdiscards | Primitive::Halign ) - ) + ) || (matches!( + &meaning, + Meaning::Character(TokenKind::Character(_, CatCode::EndGroup)) + ) && self.group_end_needs_paragraph_token())) { + let span = token.span; self.unread(InputToken { - token: token.clone(), + token, frozen: input.frozen, end_write: input.end_write, alignment: None, })?; - self.push(vec![ - Token::new( - TokenKind::Command(CommandName::Control("par".into())), - token.span, - ) - .into(), - ])?; + self.insert_paragraph_token(span)?; continue; } if frozen_expandable { @@ -3586,6 +3602,11 @@ impl Executor { token.invocation.unwrap_or(token.span), files, )?, + Partokenname => { + if let TokenKind::Command(name) = self.required_raw(files)?.token.kind { + self.state.set_paragraph_token(name); + } + } Par => { if self.paragraph.is_none() { self.normal_paragraph(files)?; diff --git a/crates/texrra-tex-core/src/execution/engine/alignment.rs b/crates/texrra-tex-core/src/execution/engine/alignment.rs index 6a28f46..3b87b93 100644 --- a/crates/texrra-tex-core/src/execution/engine/alignment.rs +++ b/crates/texrra-tex-core/src/execution/engine/alignment.rs @@ -169,7 +169,16 @@ impl Executor { ) -> Result<(), Error> { match boundary { Boundary::Prefix => unreachable!("prefix boundary is handled by raw"), - Boundary::Entry => self.finish_alignment_column(files), + Boundary::Entry => { + if self.alignments.last().is_some_and(|frame| !frame.horizontal) + && self.in_unrestricted_horizontal_mode() + && self.read_parameter(Parameter::Partokencontext).width() > 1 + { + self.alignment_marker(Boundary::Entry)?; + return self.insert_paragraph_token(self.current); + } + self.finish_alignment_column(files) + } Boundary::Peek => self.peek_alignment(files), } } diff --git a/crates/texrra-tex-core/src/execution/engine/math.rs b/crates/texrra-tex-core/src/execution/engine/math.rs index b3017d0..ac0b59e 100644 --- a/crates/texrra-tex-core/src/execution/engine/math.rs +++ b/crates/texrra-tex-core/src/execution/engine/math.rs @@ -788,7 +788,7 @@ impl Executor { | Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time | Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage | Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen - | Parshape => { + | Parshape | Partokenname => { return Ok(false); } _ => return self.fail(format!("unsupported native math primitive: {p:?}")), diff --git a/crates/texrra-tex-core/src/execution/format_image.rs b/crates/texrra-tex-core/src/execution/format_image.rs index 29e6630..044c053 100644 --- a/crates/texrra-tex-core/src/execution/format_image.rs +++ b/crates/texrra-tex-core/src/execution/format_image.rs @@ -8,8 +8,8 @@ use std::{ sync::{Arc, Mutex, OnceLock, Weak}, }; -const SCHEMA: u32 = 36; -const COMPATIBLE_SCHEMAS: [u32; 8] = [27, 28, 31, 32, 33, 34, 35, SCHEMA]; +const SCHEMA: u32 = 37; +const COMPATIBLE_SCHEMAS: [u32; 9] = [27, 28, 31, 32, 33, 34, 35, 36, SCHEMA]; const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); #[derive(serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/mod.rs b/crates/texrra-tex-core/src/execution/mod.rs index 945ad47..8dfcd1d 100644 --- a/crates/texrra-tex-core/src/execution/mod.rs +++ b/crates/texrra-tex-core/src/execution/mod.rs @@ -423,6 +423,7 @@ pub enum Dependency { InputStream(u8), InputPosition(usize), OutputStream(u8), + ParagraphToken, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] diff --git a/crates/texrra-tex-core/src/execution/mouth.rs b/crates/texrra-tex-core/src/execution/mouth.rs index 31384ae..3a84bd1 100644 --- a/crates/texrra-tex-core/src/execution/mouth.rs +++ b/crates/texrra-tex-core/src/execution/mouth.rs @@ -499,7 +499,10 @@ impl Mouth { CatCode::EndLine => { self.cursor = self.line.len(); let kind = match self.state { - LineState::New => TokenKind::Command(CommandName::Control("par".into())), + LineState::New => { + reads.insert(Dependency::ParagraphToken); + state.paragraph_token() + } LineState::Middle => TokenKind::Character(' ', CatCode::Space), LineState::Skip => continue, }; diff --git a/crates/texrra-tex-core/src/execution/parameters.rs b/crates/texrra-tex-core/src/execution/parameters.rs index 09cbdb2..8c75959 100644 --- a/crates/texrra-tex-core/src/execution/parameters.rs +++ b/crates/texrra-tex-core/src/execution/parameters.rs @@ -113,6 +113,7 @@ pub enum Parameter { Tabskip, Pdfprotrudechars, Pdfadjustspacing, + Partokencontext, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum ParameterValue { @@ -229,6 +230,7 @@ impl Parameter { Self::Tabskip, Self::Pdfprotrudechars, Self::Pdfadjustspacing, + Self::Partokencontext, ]; pub fn name(self) -> String { format!("{self:?}").to_ascii_lowercase() diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index e12ebe3..eaa8165 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -327,6 +327,7 @@ pub enum Primitive { Pdfuniformdeviate, Pdfnormaldeviate, Pdfpageref, + Partokenname, } impl Primitive { @@ -594,6 +595,8 @@ pub struct State { pub newlinechar: i32, pub escapechar: i32, pub globaldefs: i32, + #[serde(default, skip_serializing_if = "Option::is_none")] + paragraph_token: Option, groups: Vec, job_parameters: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -709,6 +712,7 @@ impl Default for State { escapechar: 92, globaldefs: 0, groups: Vec::new(), + paragraph_token: None, job_parameters: BTreeMap::new(), pdf_creation_date: None, registers: BTreeMap::new(), @@ -965,6 +969,7 @@ impl Default for State { ("pdfuniformdeviate", Pdfuniformdeviate), ("pdfnormaldeviate", Pdfnormaldeviate), ("pdfpageref", Pdfpageref), + ("partokenname", Partokenname), ("pdfcolorstack", Pdfcolorstack), ("pdfsave", Pdfsave), ("pdfstartlink", Pdfstartlink), @@ -1334,8 +1339,11 @@ impl State { pub fn tokens(&self, index: u16) -> Vec { self.toks.get(&index).cloned().unwrap_or_default() } + pub(super) fn group_kind(&self) -> Option { + self.groups.last().map(|group| group.kind) + } pub(super) fn group_type(&self) -> i32 { - match self.groups.last().map(|g| g.kind) { + match self.group_kind() { None => 0, Some(GroupKind::Simple) => 1, Some(GroupKind::SemiSimple) => 14, @@ -1571,6 +1579,26 @@ impl State { pub fn count(&self, index: u16) -> i32 { self.counts.get(&index).copied().unwrap_or(0) } + pub(super) fn set_paragraph_token(&mut self, name: CommandName) { + self.paragraph_token = match &name { + CommandName::Control(value) if value == "par" => None, + _ => Some(name), + }; + } + pub(super) fn paragraph_token(&self) -> TokenKind { + let name = self + .paragraph_token + .clone() + .unwrap_or_else(|| CommandName::Control("par".into())); + TokenKind::Command(name) + } + pub(super) fn is_paragraph_token(&self, token: &TokenKind) -> bool { + match (token, &self.paragraph_token) { + (TokenKind::Command(name), Some(paragraph)) => name == paragraph, + (TokenKind::Command(CommandName::Control(name)), None) => name == "par", + _ => false, + } + } pub fn group_depth(&self) -> usize { self.groups.len() } diff --git a/crates/texrra-tex-core/tests/execution_fractions.rs b/crates/texrra-tex-core/tests/execution_fractions.rs index fbfb686..e576429 100644 --- a/crates/texrra-tex-core/tests/execution_fractions.rs +++ b/crates/texrra-tex-core/tests/execution_fractions.rs @@ -246,7 +246,7 @@ fn genuine_fraction_primitives_and_retained_boxes_survive_format_roundtrip() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 36); + assert_eq!(payload["schema"], 37); let state = State::initex().with_etex(); let loaded = FormatImage::decode(&bytes) .unwrap() diff --git a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs index 393c4d7..b4fbb3e 100644 --- a/crates/texrra-tex-core/tests/execution_pdf_unicode.rs +++ b/crates/texrra-tex-core/tests/execution_pdf_unicode.rs @@ -334,7 +334,7 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums() let envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap(); let original: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(original["schema"], 36); + assert_eq!(original["schema"], 37); for (schema, expected) in [ (1, "incompatible native format"), (2, "incompatible native format"), diff --git a/crates/texrra-tex-core/tests/execution_vcenter.rs b/crates/texrra-tex-core/tests/execution_vcenter.rs index d2bd354..c7b0360 100644 --- a/crates/texrra-tex-core/tests/execution_vcenter.rs +++ b/crates/texrra-tex-core/tests/execution_vcenter.rs @@ -164,7 +164,7 @@ fn new_format_owns_vcenter_and_boxed_math_without_reinjecting_old_meanings() { let envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let payload: serde_json::Value = serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); - assert_eq!(payload["schema"], 36); + assert_eq!(payload["schema"], 37); let executor = FormatImage::decode(&bytes) .unwrap() .new_job( diff --git a/docs/P2_M1_PROGRESS.md b/docs/P2_M1_PROGRESS.md index c61a6cd..7e1012d 100644 --- a/docs/P2_M1_PROGRESS.md +++ b/docs/P2_M1_PROGRESS.md @@ -1126,6 +1126,36 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode [原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿) [pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143) +### 原生段落结束 token 和分组上下文 + +`\partokenname` 全局选择引擎插入的段落 token,并用实际 token 身份检查 +非 long 宏的参数。空行和经典隐式段落边界使用该命令。`\partokencontext` +是普通局部整数参数;模式1扩展至垂直盒、垂直顶盒和 `\vcenter`,模式2也 +覆盖插入、调整、输出例程、`\noalign` 及垂直对齐的单元格。实现先把遇到 +的闭合 token 放回输入,再执行当前段落命令,因此分组还在,命令效果遵循 +正常执行及恢复。schema37 格式保存改名和参数。 +[TeX Live 的段落 token 更改文件](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/partoken.ch) + +同一输入下实际段落输出的10条上下文记录逐字节一致,两页144 DPI灰度图 +逐像素一致。TeX Live 原样成功用例的90个字形和 DVI 坐标逐个匹配, +最大位置偏差0 sp,原样失败用例在重命名后的段落 token 处拒绝非 long +参数。两个相关测试文件合计18项通过。首次对照缺少字体查找根,恢复 +真实 TeX Live 的两处搜索根后通过,早期日志保留。 +[TeX Live 原样成功用例](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tests/partoken-ok.tex) +[TeX Live 原样预期失败用例](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tests/partoken-xfail.tex) + +实际 INITEX 还转储了名为 `\renamedpar` 的段落 token 和模式1。加载后 +两个盒子中的隐式命令各修改一次作业计数。编辑第二页时复用1015步只 +替换第二页,PDF、SVG 和来源映射与独立零复用一致。来源映射只归一化 +测试目录和会话修订号。首次验证计数赋值未设为全局,修正用例后通过。 + +`target/p3-paragraph-token-native` 的回执: + +- `receipt.json` 为 `03eface7fac03417da5437c240176281bfb410e070f7568f6e40a63e19a0d8de`。 +- `minimal-format/seed.tfx` 为 `e6ee320d0b87cf3f25e8a52b858f1eb491e77356b2f4b60781233b1d4bb11347`。 +- `checkpoint/receipt.json` 为 `07e1e1d38425b91587029fc838b7dde351bd394ae473ebf3552f7e567b6637af`。 +- `targeted-regression.log` 为 `295b489dfef681c254f4a2afcba01511f08e0c69b99aaf9be33153ac0ad8397d`。 + ### 宏的左花括号分隔符与表格行边界 带 `#{` 的 TeX 宏把字面左花括号匹配为分隔符,再将同一括号放回替换