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();