Share packed native lists across copied boxes and shipouts

This commit is contained in:
gloamxun committed 2026-11-28 08:01:14 +08:00
1 parent ca3730338e
commit da48cf9cad
16 files changed
+157 -67

No files matched your search

@@ -43,8 +43,8 @@ pub struct GlueSetting {
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum BoxContent {
Horizontal(Vec<TextNode>),
Vertical(Vec<NativeVerticalNode>),
Horizontal(Arc<Vec<TextNode>>),
Vertical(Arc<Vec<NativeVerticalNode>>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct NativeBox {
@@ -264,7 +264,7 @@ impl NativeBox {
}
}
BoxContent::Vertical(nodes) => {
for n in nodes {
for n in nodes.iter() {
match n {
NativeVerticalNode::Output(o) => out.push(o),
NativeVerticalNode::Leaders(_) => *leaders = true,
@@ -662,7 +662,7 @@ pub(super) fn vpack(
height,
depth,
shift: 0,
content: BoxContent::Vertical(nodes),
content: BoxContent::Vertical(nodes.into()),
diagnostic: Arc::default(),
setting: set,
interword_runs: Vec::new(),
@@ -775,7 +775,7 @@ pub(super) fn hpack_with_direction_report(
height,
depth,
shift: 0,
content: BoxContent::Horizontal(nodes),
content: BoxContent::Horizontal(nodes.into()),
diagnostic,
setting: set,
interword_runs: Vec::new(),
@@ -1001,7 +1001,7 @@ impl NativeBox {
};
let mut cursor = y - self.height;
let (mut cumulative, mut previous) = (0, 0);
for node in nodes {
for node in nodes.iter() {
budget.inside_leader(1)?;
match node {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => {
@@ -9,8 +9,8 @@ impl NativeBox {
visit: &mut impl FnMut(&mut Arc<NativeFont>),
) {
match &mut self.content {
BoxContent::Horizontal(nodes) => rebind_horizontal(nodes, visit),
BoxContent::Vertical(nodes) => rebind_vertical(nodes, visit),
BoxContent::Horizontal(nodes) => rebind_horizontal(Arc::make_mut(nodes).as_mut_slice(), visit),
BoxContent::Vertical(nodes) => rebind_vertical(Arc::make_mut(nodes).as_mut_slice(), visit),
}
}
}
@@ -39,7 +39,7 @@ fn prepare(
match &mut packed.content {
BoxContent::Horizontal(nodes) => {
packed.interword_runs = shape_row(nodes, packed.setting, remaining, cancellation)?;
for node in nodes {
for node in Arc::make_mut(nodes) {
let child = match node {
TextNode::Box(item)
| TextNode::MathChar(item)
@@ -56,7 +56,7 @@ fn prepare(
}
}
BoxContent::Vertical(nodes) => {
for node in nodes {
for node in Arc::make_mut(nodes) {
let child = match node {
NativeVerticalNode::Box(item)
| NativeVerticalNode::Line(item)
@@ -50,8 +50,8 @@ fn descend_mut<'a>(b: &'a mut NativeBox, path: &[usize]) -> &'a mut NativeBox {
None => b,
Some((&i, rest)) => descend_mut(
match &mut b.content {
BoxContent::Vertical(v) => vertical_box_mut(&mut v[i]),
BoxContent::Horizontal(v) => text_box_mut(&mut v[i]),
BoxContent::Vertical(v) => vertical_box_mut(&mut Arc::make_mut(v)[i]),
BoxContent::Horizontal(v) => text_box_mut(&mut Arc::make_mut(v)[i]),
},
rest,
),
@@ -60,8 +60,8 @@ fn descend_mut<'a>(b: &'a mut NativeBox, path: &[usize]) -> &'a mut NativeBox {
fn refresh(b: &mut NativeBox, path: &[usize]) {
if let Some((&i, rest)) = path.split_first() {
let child = match &mut b.content {
BoxContent::Vertical(v) => vertical_box_mut(&mut v[i]),
BoxContent::Horizontal(v) => text_box_mut(&mut v[i]),
BoxContent::Vertical(v) => vertical_box_mut(&mut Arc::make_mut(v)[i]),
BoxContent::Horizontal(v) => text_box_mut(&mut Arc::make_mut(v)[i]),
};
refresh(child, rest);
}
@@ -130,8 +130,8 @@ impl VerticalBuilder {
pub(in crate::execution) fn push(&mut self, node: NativeVerticalNode) {
match self.tail_box_mut().map(|b| &mut b.content) {
None => self.nodes.push(node),
Some(BoxContent::Vertical(v)) => v.push(node),
Some(BoxContent::Horizontal(v)) => v.push(horizontal(node)),
Some(BoxContent::Vertical(v)) => Arc::make_mut(v).push(node),
Some(BoxContent::Horizontal(v)) => Arc::make_mut(v).push(horizontal(node)),
}
self.refresh_tail();
}
@@ -169,8 +169,8 @@ impl VerticalBuilder {
fn pop(&mut self) -> Option<Removed> {
let node = match self.tail_box_mut().map(|b| &mut b.content) {
None => self.nodes.pop().map(Removed::Vertical),
Some(BoxContent::Vertical(v)) => v.pop().map(Removed::Vertical),
Some(BoxContent::Horizontal(v)) => v.pop().map(Removed::Text),
Some(BoxContent::Vertical(v)) => Arc::make_mut(v).pop().map(Removed::Vertical),
Some(BoxContent::Horizontal(v)) => Arc::make_mut(v).pop().map(Removed::Text),
};
self.refresh_tail();
node
@@ -791,9 +791,9 @@ fn empty_alignment_box(width: i64, horizontal: bool, span: Span) -> NativeBox {
depth: 0,
shift: 0,
content: if horizontal {
BoxContent::Horizontal(Vec::new())
BoxContent::Horizontal(Default::default())
} else {
BoxContent::Vertical(Vec::new())
BoxContent::Vertical(Default::default())
},
diagnostic: Default::default(),
setting: GlueSetting::default(),
@@ -857,7 +857,7 @@ fn set_alignment_cell(
};
match &cell.content {
BoxContent::Horizontal(v) => {
for n in v {
for n in v.iter() {
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
@@ -867,7 +867,7 @@ fn set_alignment_cell(
}
}
BoxContent::Vertical(v) => {
for n in v {
for n in v.iter() {
if let NativeVerticalNode::Glue(g)
| NativeVerticalNode::NamedGlue(g, _)
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) = n
@@ -937,16 +937,16 @@ fn set_alignment_row(
} else {
BoxKind::Vertical
};
let old = std::mem::replace(&mut row.content, BoxContent::Horizontal(Vec::new()));
let old = std::mem::replace(&mut row.content, BoxContent::Horizontal(Default::default()));
let mut cells: VecDeque<NativeBox> = match old {
BoxContent::Horizontal(v) => v
BoxContent::Horizontal(v) => std::sync::Arc::unwrap_or_clone(v)
.into_iter()
.filter_map(|n| match n {
TextNode::Box(b) => b.native_box.map(|b| *b),
_ => None,
})
.collect(),
BoxContent::Vertical(v) => v
BoxContent::Vertical(v) => std::sync::Arc::unwrap_or_clone(v)
.into_iter()
.filter_map(|n| match n {
NativeVerticalNode::Box(b) => Some(*b),
@@ -1014,10 +1014,10 @@ fn set_alignment_row(
if horizontal {
row.width = prototype.width;
row.diagnostic = super::super::diagnostics::text_nodes(&h).into();
row.content = BoxContent::Horizontal(h);
row.content = BoxContent::Horizontal(h.into());
} else {
row.height = prototype.height;
row.content = BoxContent::Vertical(v);
row.content = BoxContent::Vertical(v.into());
}
Ok(())
}
@@ -1031,7 +1031,7 @@ fn mark_unset(b: &mut NativeBox, span: u8) -> Result<(), String> {
};
match &b.content {
BoxContent::Horizontal(v) => {
for n in v {
for n in v.iter() {
if let TextNode::Glue(g) | TextNode::FontSpace(g, _, _)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
@@ -1041,7 +1041,7 @@ fn mark_unset(b: &mut NativeBox, span: u8) -> Result<(), String> {
}
}
BoxContent::Vertical(v) => {
for n in v {
for n in v.iter() {
if let NativeVerticalNode::Glue(g)
| NativeVerticalNode::NamedGlue(g, _)
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) = n
@@ -166,9 +166,11 @@ impl Executor {
.expect("unhbox starts an actual paragraph")
.nodes
.extend(
nodes.into_iter().filter(|node| !matches!(node, TextNode::MarginKern { .. })),
Arc::unwrap_or_clone(nodes)
.into_iter()
.filter(|node| !matches!(node, TextNode::MarginKern { .. })),
),
BoxContent::Vertical(nodes) => self.append_unboxed_vertical(nodes),
BoxContent::Vertical(nodes) => self.append_unboxed_vertical(Arc::unwrap_or_clone(nodes)),
}
Ok(())
}
@@ -442,7 +444,7 @@ impl Executor {
let max_depth = self.read_parameter(Parameter::Splitmaxdepth).width();
let skip = self.read_parameter(Parameter::Splittopskip).glue();
let original = self.state.take_box(index).unwrap();
let BoxContent::Vertical(mut nodes) = original.content else {
let BoxContent::Vertical(nodes) = original.content else {
unreachable!()
};
let cut = super::super::vertical_break::find_break(
@@ -453,6 +455,7 @@ impl Executor {
self.limits.steps,
)
.map_err(|e| self.error(e, span))?;
let mut nodes = Arc::unwrap_or_clone(nodes);
let tail = nodes.split_off(cut.index);
self.collect_split_marks(&nodes)?;
let save = self.read_parameter(Parameter::Savingvdiscards).width() > 0;
@@ -520,7 +523,7 @@ impl Executor {
height: 0,
depth: 0,
shift: 0,
content: BoxContent::Horizontal(Vec::new()),
content: BoxContent::Horizontal(Default::default()),
diagnostic: Default::default(),
setting: GlueSetting::default(),
interword_runs: Vec::new(),
@@ -827,7 +830,7 @@ impl Executor {
let BoxContent::Vertical(nodes) = b.content else {
unreachable!("vadjust owns a vertical list");
};
let adjustment = NativeAdjustment { pre, nodes };
let adjustment = NativeAdjustment { pre, nodes: Arc::unwrap_or_clone(nodes) };
if let Some(math) = self.math.last_mut() {
math.nodes.push(MathNode::Adjustment(adjustment));
} else {
@@ -849,7 +852,7 @@ impl Executor {
split_top,
split_depth,
float_cost,
nodes,
nodes: Arc::unwrap_or_clone(nodes),
span: frame.span,
};
if let Some(math) = self.math.last_mut() {
@@ -24,7 +24,7 @@ impl Executor {
return Ok(());
}
// Packing can move existing lists or replace an old register. Recount
// actual storage here, including a shared diagnostic allocation once.
// actual storage here, counting each shared list allocation once.
let usage = self.collect_usage(shipping, None, Collector::for_capacity());
self.material_charge = usage
.active_material
@@ -14,8 +14,8 @@ pub(in crate::execution) fn rebind(
images: &[Arc<PdfImageUse>],
) -> Result<(), String> {
match &mut b.content {
BoxContent::Horizontal(nodes) => horizontal(nodes, images)?,
BoxContent::Vertical(nodes) => vertical(nodes, images)?,
BoxContent::Horizontal(nodes) => horizontal(Arc::make_mut(nodes).as_mut_slice(), images)?,
BoxContent::Vertical(nodes) => vertical(Arc::make_mut(nodes).as_mut_slice(), images)?,
}
diagnostics(Arc::make_mut(&mut b.diagnostic), images)
}
@@ -216,7 +216,7 @@ impl PageInsertions {
let BoxContent::Vertical(nodes) = b.content else {
unreachable!("checked vbox");
};
nodes
std::sync::Arc::unwrap_or_clone(nodes)
} else {
Vec::new()
};
@@ -238,7 +238,7 @@ impl PageInsertions {
let BoxContent::Vertical(nodes) = b.content else {
unreachable!()
};
insertion.nodes = nodes;
insertion.nodes = std::sync::Arc::unwrap_or_clone(nodes);
self.held.push(NativeVerticalNode::Insertion(insertion));
}
} else {
@@ -45,7 +45,7 @@ impl Converter<'_> {
let metrics = g.metrics;
g.metrics.width -= id.metrics().italic(char::from(slot));
Ok(delimiter_native_box(
BoxContent::Horizontal(vec![TextNode::MathChar(super::math::math_box(g))]),
BoxContent::Horizontal(vec![TextNode::MathChar(super::math::math_box(g))].into()),
metrics.width,
metrics.height,
metrics.depth,
@@ -159,7 +159,7 @@ impl Converter<'_> {
self.reserve_delimiter_glyphs(geometry.items.len())?;
let metrics = geometry.metrics;
delimiter_native_box(
BoxContent::Horizontal(vec![TextNode::Box(super::math::math_box(geometry))]),
BoxContent::Horizontal(vec![TextNode::Box(super::math::math_box(geometry))].into()),
metrics.width, metrics.height, metrics.depth,
)
} else if let Some((id, slot)) = best {
@@ -209,7 +209,7 @@ impl Converter<'_> {
})
.collect::<Result<Vec<_>, _>>()?;
delimiter_native_box(
BoxContent::Vertical(nodes),
BoxContent::Vertical(nodes.into()),
repeat.metrics.width,
height,
extent - height,
@@ -220,7 +220,7 @@ impl Converter<'_> {
}
} else {
delimiter_native_box(
BoxContent::Horizontal(Vec::new()),
BoxContent::Horizontal(Default::default()),
self.state.parameter(Parameter::Nulldelimiterspace).width() as i64,
0,
0,
@@ -122,7 +122,7 @@ impl Converter<'_> {
height,
depth,
shift: 0,
content: BoxContent::Vertical(nodes),
content: BoxContent::Vertical(nodes.into()),
diagnostic: Default::default(),
setting: GlueSetting::default(),
interword_runs: Vec::new(),
@@ -25,9 +25,10 @@ impl Converter<'_> {
self.last_pack_badness.set(Some(b.badness));
}
}
let BoxContent::Horizontal(mut nodes) = b.content else {
let BoxContent::Horizontal(nodes) = b.content else {
unreachable!()
};
let mut nodes = std::sync::Arc::unwrap_or_clone(nodes);
if let [TextNode::MathChar(c)] = nodes.as_slice() {
let difference = b.width - c.width;
if difference != 0 {
@@ -31,7 +31,7 @@ impl Converter<'_> {
&& matches!(nodes[0], TextNode::MathChar(_))
&& matches!(nodes[1], TextNode::Kern { .. })
{
nodes.pop();
std::sync::Arc::make_mut(nodes).pop();
b.diagnostic = super::diagnostics::text_nodes(nodes).into();
}
}
@@ -152,12 +152,12 @@ pub(super) struct Collector {
pub usage: ResourceUsage,
macros: BTreeSet<usize>,
token_lists: BTreeSet<(usize, usize)>,
shared_diagnostic_lists: Option<BTreeSet<usize>>,
shared_lists: Option<BTreeSet<usize>>,
}
impl Collector {
pub fn for_capacity() -> Self {
Self {
shared_diagnostic_lists: Some(BTreeSet::new()),
shared_lists: Some(BTreeSet::new()),
..Self::default()
}
}
@@ -192,8 +192,9 @@ impl Collector {
pub fn native_box(&mut self, b: &NativeBox, o: Ownership) {
self.material(o).boxes += 1;
match &b.content {
BoxContent::Horizontal(v) => self.text(v, o),
BoxContent::Vertical(v) => self.vertical(v, o),
BoxContent::Horizontal(v) if self.visit_shared(v) => self.text(v, o),
BoxContent::Vertical(v) if self.visit_shared(v) => self.vertical(v.iter(), o),
_ => {}
}
self.shared_diagnostics(&b.diagnostic, o);
}
@@ -306,14 +307,18 @@ impl Collector {
self.text(&b.nodes, Ownership::Active);
self.usage.active_material.ligature_work_items += b.ligature_work_items();
}
fn visit_shared<T: ?Sized>(&mut self, list: &Arc<T>) -> bool {
self.shared_lists.as_mut().is_none_or(|seen| {
seen.insert(Arc::as_ptr(list).cast::<()>() as usize)
})
}
pub fn shared_diagnostics(
&mut self,
nodes: &Arc<[super::diagnostics::DiagnosticNode]>,
o: Ownership,
) {
if !nodes.is_empty() && self.shared_diagnostic_lists.as_mut()
.is_none_or(|seen| seen.insert(nodes.as_ptr() as usize))
{
if !nodes.is_empty() && self.visit_shared(nodes) {
self.diagnostics(nodes, o);
}
}
@@ -70,7 +70,11 @@ impl SourceProvider for Files {
}
}
fn native(source: &str, files: &mut Files) -> Result<Execution, Error> {
Executor::new(State::initex().with_etex(), Limits::default())
native_with_limits(source, files, Limits::default())
}
fn native_with_limits(source: &str, files: &mut Files, limits: Limits) -> Result<Execution, Error> {
Executor::new(State::initex().with_etex(), limits)
.with_native_pages()
.run(
SourceFile {
@@ -311,23 +315,15 @@ fn nested_box_views_share_diagnostic_storage_at_the_node_limit() {
let p = directory();
let material = r"\kern1sp ".repeat(96);
let wrapping = r"\setbox0=\hbox{\box0}".repeat(16);
let source = format!(r"{HEADER}\setbox0=\hbox{{{material}}}{wrapping}\shipout\box0\end");
let mut files = Files::new(&p);
let execution = Executor::new(
State::initex().with_etex(),
let source = format!(r"\setbox0=\hbox{{{material}}}{wrapping}\shipout\box0\end");
let execution = native_with_limits(
&source,
&mut Files::new(&p),
Limits {
tokens: 1024,
..Limits::default()
},
)
.with_native_pages()
.run(
SourceFile {
name: "probe.tex".into(),
data: source.into_bytes(),
},
&mut files,
)
.unwrap();
let boxes = execution
@@ -344,6 +340,49 @@ fn nested_box_views_share_diagnostic_storage_at_the_node_limit() {
fs::remove_dir_all(p).unwrap();
}
#[test]
fn packed_lists_share_storage_across_shipout_copies_and_keep_split_results_isolated() {
let p = directory();
let material = r"\kern1sp ".repeat(96);
let copies = r"\shipout\copy1 ".repeat(8);
let source = format!(
r"\splittopskip=0pt \splitmaxdepth=10pt
\setbox0=\hbox{{\vrule width4pt height5pt {material}}}
\setbox1=\vbox{{\copy0\penalty-10000 \copy0}}
{copies}\setbox2=\vsplit1 to5pt \shipout\box2\shipout\box1\end"
);
let execution = native_with_limits(
&source,
&mut Files::new(&p),
Limits {
tokens: 1024,
..Limits::default()
},
)
.unwrap();
let pages = execution
.events
.iter()
.filter_map(|event| {
let Event::Shipout(page) = event else { return None };
let BoxContent::Vertical(nodes) = &page.box_node.content else {
panic!("expected a vertical box on every page");
};
Some(nodes)
})
.collect::<Vec<_>>();
assert_eq!(pages.len(), 10);
assert!(pages[..8].iter().all(|nodes| std::sync::Arc::ptr_eq(pages[0], nodes)));
let box_count = |nodes: &[NativeVerticalNode]| {
nodes.iter().filter(|node| matches!(node, NativeVerticalNode::Box(_))).count()
};
assert_eq!(box_count(pages[0]), 2);
assert_eq!(box_count(pages[8]), 1);
assert_eq!(box_count(pages[9]), 1);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn statistics_observe_real_paragraph_math_output_and_language_data_without_rewriting_lists() {
let p = directory();
+42
View File
@@ -819,6 +819,48 @@ letterspace-fresh.log 和 device-pdftex-spaced-moved.log。
[原版字距虚拟字体构造](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L16400-L16492)
[原版格式所写字体字段](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L30627-L30696)
### 封装盒共享实际水平和垂直列表
封装后的水平和垂直列表通过共享所有权随盒副本进入状态和执行事件。
拆盒及解盒在取得唯一所有权时直接转移节点,共享时复制当前列表,
保留已出页的副本。尾节点修改、字体和图像重绑定、出页造型沿用
对应列表的按需复制。容量复核按实际共享分配计数,逐次出页仍
遍历每个实例的定位和迟写。原逻辑列表进入现有格式和诊断报告。
同一只竖盒含两个 12,000 kern 的子盒。旧版在默认容量保留 39
页后停止,新版生成 46 页,144 DPI 灰度图逐页与 XeTeX 相同。
同一机上的两次探针中,旧失败进程峰值 RSS 为 267,676 KiB,
新成功进程峰值为 48,312 KiB。单页的另一组对照将同一个盒的
两次 PDF special 放在不同坐标,迟写两次,光栅和 aux 均与
原版逐字节一致。上个提交预存的盒格式镜像由本版加载后,两页 PDF 与
旧作业逐字节一致。对齐、拆盒、格式镜像和统计共 31 项定向回归通过。
四页项目在入口检查点前封装并输出共享竖盒,子文件拆盒后改动
文本与颜色。三次成功修订只更新第 2 页,后两次各复用 2,150 步,
PDF、测量页面、SVG、来源映射和 aux 与独立全量一致。出页失败
时保留上一修订的预览和 aux。
使用同一真实格式、字体、文件指纹和默认容量,原样
xeCJK-example-CJKfntef.tex 首次完整生成六页 PDF。用时门禁
仍以统一性能阶段的固定语料为准,本次记录实际执行 71,061,058 步。
aux 与参考逐字节一致,第 2 至 4 页的 611 个提取词、词框与
144 DPI 光栅逐项一致。第 1、5、6 页分别有 15,300、128,248 和
28,718 个灰度像素差异,词序或分段也存在差异。两份 PDF 使用的
字体族一致,LASY6 编码和嵌入形式以及 SimSun 资源数量有差异。
下一入口由第 1 页首个像素差异及第 5 页第一段标记正文的断行
定位,沿实际原始列表、参考 XDV 和两端 PDF 对照。保留第 6 页
分行与提取顺序的差异。
独立的 next-ignored-split 用相同原样输入在参考 XeTeX 和
pdfTeX 的 e-TeX 模式执行。屏蔽位 1 使两处无限 shrink 各记录
一次 ignored 诊断,作业成功出两页,组结束前后读到 1 和 0。
INITEX 普通模式的诊断也保留。该能力缺口与本次六页编译结果
分别记录。
原样 PDF、逐页对照、格式镜像及修订证据在
target/p3-packed-list-sharing,receipt.json 为
9e7c3eeb72c06d732a90a39d5972972fd953a96d75310a2f180d299ba220b735。
### 盒子副本共享诊断列表
原样 xeCJK 下划线样稿的默认容量失败已从执行事件归因。