Files
texrra-engine/crates/texrra-tex-core/src/execution/engine/alignment.rs
T

1028 lines
38 KiB
Rust

//! Native alignment templates and unset rows (TeX WEB, parts 25 and 37).
//! Delimiters switch templates at the raw-token boundary, including during
//! macro argument scans; cells are never collected as strings or recompiled.
use super::super::boxes::{self, PackSpec, VerticalBuilder};
use super::*;
#[derive(Clone, Copy)]
pub(super) enum Boundary {
Prefix,
Entry,
Peek,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Stage {
Preamble,
Peek,
Entry,
Suffix,
Noalign(usize),
}
#[derive(Clone)]
struct Template {
prefix: Vec<Token>,
suffix: Vec<Token>,
}
#[derive(Clone)]
struct Cell {
last: usize,
node: NativeBox,
}
#[derive(Clone)]
pub(super) struct AlignmentFrame {
horizontal: bool,
span: Span,
spec: PackSpec,
depth: usize,
stage: Stage,
templates: Vec<Template>,
skips: Vec<Glue>,
repeat: Option<usize>,
repeat_cursor: usize,
template_tokens: usize,
column: usize,
first: usize,
omitted: bool,
terminator: Option<Primitive>,
cells: Vec<Cell>,
adjustments: super::super::marks::MigratingMaterial,
// Maximum natural extent, indexed by (last,first) so each constraint is
// visited once when its final column is resolved.
extents: std::collections::BTreeMap<(usize, usize), i64>,
parent_paragraph: Option<super::super::paragraph::Builder>,
parent_vertical: VerticalBuilder,
parent_math: Vec<super::super::math::MathBuilder>,
parent_display: Option<super::display::DisplayFrame>,
parent_balance: i64,
row_paragraph: Option<super::super::paragraph::Builder>,
row_vertical: VerticalBuilder,
}
impl AlignmentFrame {
pub(super) fn collect_statistics(&self, c: &mut super::super::statistics::Collector) {
use super::super::statistics::Ownership::Active;
for p in [&self.parent_paragraph, &self.row_paragraph]
.into_iter()
.flatten()
{
c.paragraph_builder(p);
}
c.vertical(&self.parent_vertical.nodes, Active);
if let Some(d) = &self.parent_display {
d.collect_statistics(c);
}
c.vertical(&self.row_vertical.nodes, Active);
c.vertical(&self.adjustments.pre, Active);
c.vertical(&self.adjustments.post, Active);
for cell in &self.cells {
c.native_box(&cell.node, Active);
}
for t in &self.templates {
c.usage.token_list_cells += t.prefix.len() + t.suffix.len();
}
for m in &self.parent_math {
c.math_builder(m);
}
}
}
impl Executor {
pub(super) fn alignment_brace_token(token: &Token) -> i64 {
// get_next/back_input count literal tokens, not the meanings of
// control sequences such as bgroup, egroup or their aliases.
match token.kind {
TokenKind::Character(_, CatCode::BeginGroup) => 1,
TokenKind::Character(_, CatCode::EndGroup) => -1,
_ => 0,
}
}
pub(super) fn alignment_brace(&mut self, token: &Token) -> i64 {
match self.meaning(token) {
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup)) => 1,
Meaning::Character(TokenKind::Character(_, CatCode::EndGroup)) => -1,
_ => 0,
}
}
fn alignment_marker(&mut self, boundary: Boundary) -> Result<(), Error> {
let mut t: InputToken =
Token::new(TokenKind::Command(CommandName::FrozenRelax), self.current).into();
t.alignment = Some(boundary);
self.push(vec![t])
}
// Called by raw before a token can be consumed by any expandable scanner.
pub(super) fn alignment_raw(&mut self, token: &InputToken) -> Result<bool, Error> {
if self.alignments.is_empty() {
return Ok(false);
}
if let Some(boundary) = token.alignment {
match boundary {
Boundary::Prefix => {
if self.alignment_balance < 500_000 {
return self.fail("interwoven native alignment templates");
}
self.alignment_balance = 0;
return Ok(true);
}
Boundary::Entry if self.scanner_status != ScannerStatus::Normal => {
return self.fail("runaway scanner at end of native alignment template");
}
_ => return Ok(false),
}
}
self.alignment_balance += Self::alignment_brace_token(&token.token);
if self.alignment_balance != 0 {
return Ok(false);
}
let end = match self.meaning(&token.token) {
Meaning::Character(TokenKind::Character(_, CatCode::Alignment)) => {
Some(Primitive::Relax)
}
Meaning::Primitive(p @ (Primitive::Cr | Primitive::Crcr | Primitive::Span)) => Some(p),
_ => None,
};
let Some(end) = end else { return Ok(false) };
let frame = self.alignments.last_mut().unwrap();
if frame.stage != Stage::Entry {
return self.fail("interwoven native alignment preambles");
}
frame.terminator = Some(end);
frame.stage = Stage::Suffix;
let suffix = if frame.omitted {
Vec::new()
} else {
frame.templates[frame.column].suffix.clone()
};
self.alignment_balance = 1_000_000;
self.alignment_marker(Boundary::Entry)?;
self.push(suffix.into_iter().map(InputToken::from).collect())?;
Ok(true)
}
pub(super) fn alignment_boundary(
&mut self,
boundary: Boundary,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
match boundary {
Boundary::Prefix => unreachable!("prefix boundary is handled by raw"),
Boundary::Entry => self.finish_alignment_column(files),
Boundary::Peek => self.peek_alignment(files),
}
}
pub(super) fn start_alignment(
&mut self,
p: Primitive,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let horizontal = p == Primitive::Halign;
if !self.math.is_empty()
&& (!horizontal
|| self.display.is_none()
|| self.math.len() != 1
|| self.math[0].depth != self.state.group_depth()
|| !self.math[0].nodes.is_empty()
|| self.math[0].numerator.is_some())
{
return self.fail("halign requires an empty outer display math list");
}
if horizontal && self.paragraph.is_some() {
if self.restricted() {
return self.fail("halign requires vertical or display mode");
}
self.end_paragraph(files)?;
}
if !horizontal && self.paragraph.is_none() {
return self.fail("valign requires horizontal mode");
}
if self.alignments.len() >= self.limits.input_depth.min(32) {
return self.fail("native alignment nesting capacity exceeded");
}
let parent_balance = self.alignment_balance;
let prev_depth = self.vertical.prev_depth;
self.alignments.push(AlignmentFrame {
horizontal,
span,
spec: PackSpec::Natural,
depth: 0,
stage: Stage::Preamble,
templates: Vec::new(),
skips: Vec::new(),
repeat: None,
repeat_cursor: 0,
template_tokens: 0,
column: 0,
first: 0,
omitted: false,
terminator: None,
cells: Vec::new(),
adjustments: Default::default(),
extents: Default::default(),
parent_paragraph: self.paragraph.take(),
parent_vertical: self.vertical.enter_nested(!horizontal),
parent_math: std::mem::take(&mut self.math),
parent_display: self.display.take(),
parent_balance,
row_paragraph: None,
row_vertical: VerticalBuilder::default(),
});
self.alignment_balance = -1_000_000;
if horizontal {
self.vertical.prev_depth = prev_depth;
} else {
self.start_alignment_hlist(span);
}
let spec = if self.keyword("to", files)? {
PackSpec::To(self.dimension(false, false, files)?.amount)
} else if self.keyword("spread", files)? {
PackSpec::Spread(self.dimension(false, false, files)?.amount)
} else {
PackSpec::Natural
};
self.begin_group(GroupKind::Align, files)?;
let open = loop {
let t = self.expanded_non_space(files)?.token;
if self.primitive(&t) != Some(Primitive::Relax) {
break t;
}
};
if self.alignment_brace(&open) != 1 {
return self.fail("expected opening brace for native alignment");
}
self.alignment_balance = -1_000_000;
self.alignments.last_mut().unwrap().spec = spec;
self.scan_alignment_preamble(files)?;
self.begin_group(GroupKind::Align, files)?;
let frame = self.alignments.last_mut().unwrap();
frame.depth = self.state.group_depth();
frame.stage = Stage::Peek;
self.alignment_balance = 1_000_000;
self.push_mode_hook(TokenParameter::Everycr)?;
self.alignment_marker(Boundary::Peek)
}
fn start_alignment_hlist(&mut self, span: Span) {
let mut b = super::super::paragraph::Builder::default();
b.start(&self.state, span, false);
b.restricted = true;
b.font_step_limit = self.limits.steps.saturating_sub(self.steps);
b.ligature_carry = self.ligature_carry;
self.paragraph = Some(b);
}
fn preamble_token(&mut self, files: &mut impl SourceProvider) -> Result<InputToken, Error> {
loop {
let mut t = self.required_raw(files)?;
while self.primitive(&t.token) == Some(Primitive::Span) {
t = self.required_raw(files)?;
t = match self.expand_one(t, files, false)? {
Some(t) => t,
None => self.required_raw(files)?,
};
}
if self.meaning(&t.token) == Meaning::Parameter(Parameter::Tabskip) {
self.assignment_inner(None, Some(Key::Parameter(Parameter::Tabskip)), files)?;
} else {
return Ok(t);
}
}
}
fn scan_alignment_preamble(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
let mut count = 0usize;
let skip = self.read_parameter(Parameter::Tabskip).glue();
self.alignments.last_mut().unwrap().skips.push(skip);
loop {
let mut prefix = Vec::new();
loop {
let t = self.preamble_token(files)?.token;
let meaning = self.meaning(&t);
if matches!(
meaning,
Meaning::Character(TokenKind::Character(_, CatCode::Parameter))
) {
break;
}
let tab = matches!(
meaning,
Meaning::Character(TokenKind::Character(_, CatCode::Alignment))
);
let end = matches!(meaning, Meaning::Primitive(Primitive::Cr | Primitive::Crcr));
if (tab || end) && self.alignment_balance == -1_000_000 {
let frame = self.alignments.last_mut().unwrap();
if tab && prefix.is_empty() && frame.repeat.is_none() {
frame.repeat = Some(frame.templates.len());
continue;
}
return self.fail("missing parameter marker in native alignment preamble");
}
if !prefix.is_empty() || !self.is_spacer(&t) {
prefix.push(t);
count += 1;
}
if count > self.limits.tokens {
return self.fail("native alignment template capacity exceeded");
}
}
let mut suffix = Vec::new();
let end = loop {
let t = self.preamble_token(files)?.token;
let m = self.meaning(&t);
if self.alignment_balance == -1_000_000
&& matches!(
m,
Meaning::Character(TokenKind::Character(_, CatCode::Alignment))
| Meaning::Primitive(Primitive::Cr | Primitive::Crcr)
)
{
break m;
}
if matches!(
m,
Meaning::Character(TokenKind::Character(_, CatCode::Parameter))
) {
return self.fail("multiple parameter markers in native alignment template");
}
suffix.push(t);
count += 1;
if count > self.limits.tokens {
return self.fail("native alignment template capacity exceeded");
}
};
let skip = self.read_parameter(Parameter::Tabskip).glue();
let frame = self.alignments.last_mut().unwrap();
frame.template_tokens = count;
frame.templates.push(Template { prefix, suffix });
frame.skips.push(skip);
if frame.templates.len() > self.limits.tokens.min(65535) {
return self.fail("native alignment column capacity exceeded");
}
if matches!(end, Meaning::Primitive(_)) {
break;
}
}
Ok(())
}
fn peek_alignment(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
self.alignment_balance = 1_000_000;
let t = loop {
let t = self.expanded_non_space(files)?;
if self.primitive(&t.token) != Some(Primitive::Crcr) {
break t;
}
};
if self.alignment_brace(&t.token) == -1 {
return self.finish_alignment(files);
}
if self.primitive(&t.token) == Some(Primitive::Noalign) {
let open = self.expanded_non_space(files)?.token;
if self.alignment_brace(&open) != 1 {
return self.fail("expected noalign opening brace");
}
self.begin_group(GroupKind::NoAlign, files)?;
self.alignments.last_mut().unwrap().stage = Stage::Noalign(self.state.group_depth());
if self.paragraph.is_none() {
self.normal_paragraph(files)?;
}
return Ok(());
}
let frame = self.alignments.last_mut().unwrap();
frame.column = 0;
frame.first = 0;
self.begin_alignment_cell(false, files)?;
self.begin_alignment_template(t)
}
fn begin_alignment_cell(
&mut self,
spanning: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if spanning {
return Ok(());
}
let frame = self.alignments.last_mut().unwrap();
frame.row_paragraph = self.paragraph.take();
let horizontal = frame.horizontal;
frame.row_vertical = self.vertical.enter_nested(horizontal);
let span = frame.span;
if horizontal {
self.start_alignment_hlist(span);
} else {
self.normal_paragraph(files)?;
}
Ok(())
}
fn begin_alignment_template(&mut self, t: InputToken) -> Result<(), Error> {
let omitted = self.primitive(&t.token) == Some(Primitive::Omit);
let frame = self.alignments.last_mut().unwrap();
frame.stage = Stage::Entry;
frame.omitted = omitted;
let prefix = frame.templates[frame.column].prefix.clone();
if omitted {
self.alignment_balance = 0;
} else {
self.unread(t)?;
self.alignment_marker(Boundary::Prefix)?;
self.push(prefix.into_iter().map(InputToken::from).collect())?;
}
Ok(())
}
fn finish_alignment_column(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
if self.alignment_balance < 500_000
|| self
.alignments
.last()
.is_none_or(|f| f.depth != self.state.group_depth())
{
return self.fail("unbalanced native alignment entry");
}
self.finish_text(true)?;
let (end, horizontal, span, first, last) = {
let f = self.alignments.last().unwrap();
(
f.terminator.unwrap(),
f.horizontal,
f.span,
f.first,
f.column,
)
};
if end != Primitive::Span {
if !horizontal {
self.end_paragraph(files)?;
}
self.finish_group(GroupKind::Align, self.current, files)?;
self.begin_group(GroupKind::Align, files)?;
let mut node = if horizontal {
let (nodes, adjustments) =
super::super::marks::extract(self.paragraph.take().unwrap().nodes);
let stored = &mut self.alignments.last_mut().unwrap().adjustments;
stored.pre.extend(adjustments.pre);
stored.post.extend(adjustments.post);
boxes::hpack(nodes, PackSpec::Natural, span, &self.state)
} else {
boxes::vpack(
self.vertical.take_nodes(),
PackSpec::Natural,
0,
BoxKind::Vertical,
span,
)
}
.map_err(|e| self.error(e, span))?;
self.account_box(&node)?;
let extent = if horizontal { node.width } else { node.height };
mark_unset(&mut node, (last - first) as u8).map_err(|e| self.error(e, span))?;
let f = self.alignments.last_mut().unwrap();
f.extents
.entry((last, first))
.and_modify(|w| *w = (*w).max(extent))
.or_insert(extent);
f.cells.push(Cell { last, node });
self.paragraph = f.row_paragraph.take();
self.vertical
.leave_nested(std::mem::take(&mut f.row_vertical), horizontal);
} else if last - first >= 255 {
return self.fail("native alignment span exceeds 256 columns");
}
if matches!(end, Primitive::Cr | Primitive::Crcr) {
self.finish_alignment_row()?;
self.alignments.last_mut().unwrap().stage = Stage::Peek;
self.alignment_balance = 1_000_000;
self.push_mode_hook(TokenParameter::Everycr)?;
return self.alignment_marker(Boundary::Peek);
}
self.extend_alignment_preamble()?;
let f = self.alignments.last_mut().unwrap();
f.column += 1;
if end != Primitive::Span {
f.first = f.column;
}
self.alignment_balance = 1_000_000;
let t = self.expanded_non_space(files)?;
self.begin_alignment_cell(end == Primitive::Span, files)?;
self.begin_alignment_template(t)
}
fn extend_alignment_preamble(&mut self) -> Result<(), Error> {
let f = self.alignments.last_mut().unwrap();
if f.column + 1 < f.templates.len() {
return Ok(());
}
let Some(start) = f.repeat else {
return self.fail("extra native alignment tab");
};
let original_len = f.templates.len() - f.repeat_cursor;
let source = start + f.repeat_cursor % (original_len - start);
let template = f.templates[source].clone();
let skip = f.skips[source + 1];
let tokens = f
.template_tokens
.saturating_add(template.prefix.len())
.saturating_add(template.suffix.len());
if tokens > self.limits.tokens {
return self.fail("native alignment template capacity exceeded");
}
f.template_tokens = tokens;
if f.templates.len() >= self.limits.tokens.min(65535) {
return self.fail("native alignment column capacity exceeded");
}
f.templates.push(template);
f.skips.push(skip);
f.repeat_cursor += 1;
Ok(())
}
fn finish_alignment_row(&mut self) -> Result<(), Error> {
let f = self.alignments.last_mut().unwrap();
let cells = std::mem::take(&mut f.cells);
let mut node = if f.horizontal {
let mut nodes = vec![TextNode::NamedGlue(f.skips[0], Parameter::Tabskip)];
for cell in cells {
nodes.push(TextNode::Box(cell.node.horizontal_item()));
nodes.push(TextNode::NamedGlue(
f.skips[cell.last + 1],
Parameter::Tabskip,
));
}
boxes::hpack(nodes, PackSpec::Natural, f.span, &self.state)
} else {
let mut nodes = vec![NativeVerticalNode::NamedGlue(
f.skips[0],
Parameter::Tabskip,
)];
for cell in cells {
nodes.push(NativeVerticalNode::Box(Box::new(cell.node)));
nodes.push(NativeVerticalNode::NamedGlue(
f.skips[cell.last + 1],
Parameter::Tabskip,
));
}
boxes::vpack(
nodes,
PackSpec::Natural,
i32::MAX,
BoxKind::Vertical,
f.span,
)
}
.map_err(|e| self.error(e, self.current))?;
mark_unset(&mut node, 0).map_err(|e| self.error(e, self.current))?;
self.account_box(&node)?;
if self.alignments.last().unwrap().horizontal {
self.reads
.insert(Dependency::Parameter(Parameter::Baselineskip));
self.reads
.insert(Dependency::Parameter(Parameter::Lineskip));
self.reads
.insert(Dependency::Parameter(Parameter::Lineskiplimit));
let f = self.alignments.last_mut().unwrap();
self.vertical.append(&mut f.adjustments.pre);
self.vertical
.append_box(NativeVerticalNode::Box(Box::new(node)), &self.state)
.map_err(|e| self.error(e, self.current))?;
let f = self.alignments.last_mut().unwrap();
self.vertical.append(&mut f.adjustments.post);
} else {
let p = self.paragraph.as_mut().unwrap();
p.nodes.push(TextNode::Box(node.horizontal_item()));
p.space_factor = 1000;
}
Ok(())
}
pub(super) fn close_noalign_group(
&mut self,
files: &mut impl SourceProvider,
) -> Result<bool, Error> {
if !self
.alignments
.last()
.is_some_and(|f| f.stage == Stage::Noalign(self.state.group_depth()))
{
return Ok(false);
}
if self.alignments.last().unwrap().horizontal {
self.end_paragraph(files)?;
}
self.finish_group(GroupKind::NoAlign, self.current, files)?;
self.alignments.last_mut().unwrap().stage = Stage::Peek;
self.alignment_marker(Boundary::Peek)?;
Ok(true)
}
fn finish_alignment(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
self.finish_group(GroupKind::Align, self.current, files)?;
self.finish_group(GroupKind::Align, self.current, files)?;
// Retain the frame until packing succeeds; failures still have the
// actual active lists available to the diagnostic/resource observer.
let columns = self.alignments.last().unwrap().templates.len();
let mut skips = self.alignments.last().unwrap().skips.clone();
let mut widths = Vec::with_capacity(columns);
for j in 0..columns {
self.tick()?;
let mut width = None;
for (&(last, first), &extent) in self
.alignments
.last()
.unwrap()
.extents
.range((j, 0)..=(j, j))
{
debug_assert_eq!(last, j);
let used: i64 = (first..j)
.map(|k| widths[k] + i64::from(skips[k + 1].width))
.sum();
width = Some(width.map_or(extent - used, |w: i64| w.max(extent - used)));
}
if width.is_none() {
skips[j + 1] = Glue::default();
}
widths.push(width.unwrap_or(0));
}
self.alignments.last_mut().unwrap().skips = skips;
let f = self.alignments.last().unwrap();
let prototype =
alignment_prototype(f, &widths, &self.state).map_err(|e| self.error(e, f.span))?;
self.diagnose_box(&prototype, files)?;
self.account_box(&prototype)?;
let displayed = !self.alignments.last().unwrap().parent_math.is_empty();
let offset = if displayed {
i64::from(self.read_parameter(Parameter::Displayindent).width())
} else {
0
};
let horizontal = self.alignments.last().unwrap().horizontal;
let span = self.alignments.last().unwrap().span;
let roots = if horizontal {
self.vertical.nodes.len()
} else {
self.paragraph.as_ref().unwrap().nodes.len()
};
for index in 0..roots {
self.tick()?;
let f = self.alignments.last().unwrap();
if f.horizontal {
let NativeVerticalNode::Box(b) = &mut self.vertical.nodes[index] else {
continue;
};
if !b.kind.is_unset() {
continue;
}
let result = set_alignment_row(b, &widths, &f.skips, &prototype);
b.shift = offset;
// e-TeX's dlist subtype is a property of the actual row box.
b.display = displayed;
result.map_err(|e| self.error(e, span))?;
} else {
let TextNode::Box(b) = &mut self.paragraph.as_mut().unwrap().nodes[index] else {
continue;
};
let node = b.native_box.as_mut().unwrap();
if !node.kind.is_unset() {
continue;
}
let result = set_alignment_row(node, &widths, &f.skips, &prototype);
b.width = node.width;
b.height = node.height;
b.depth = node.depth;
result.map_err(|e| self.error(e, span))?;
}
}
if horizontal {
for index in 0..self.vertical.nodes.len() {
if let NativeVerticalNode::Rule(r) = &mut self.vertical.nodes[index] {
if r.width.is_none() {
r.width = Some(prototype.width as i32);
}
r.height.get_or_insert(prototype.height as i32);
r.depth.get_or_insert(prototype.depth as i32);
if offset != 0 {
let rule = r.clone();
let mut b = boxes::hpack(
vec![TextNode::Rule(rule)],
PackSpec::Natural,
span,
&self.state,
)
.map_err(|e| self.error(e, span))?;
b.shift = offset;
self.diagnose_box(&b, files)?;
self.account_box(&b)?;
self.vertical.nodes[index] = NativeVerticalNode::Box(Box::new(b));
self.vertical.nest_tail_in(index);
}
}
}
}
if horizontal
&& self.vertical.tail_depth()
+ self.alignments.last().unwrap().parent_vertical.tail_depth()
> self.limits.input_depth.min(128)
{
return self.fail("native owned list tail depth capacity exceeded");
}
let f = self.alignments.pop().unwrap();
self.alignment_balance = f.parent_balance;
self.math = f.parent_math;
self.display = f.parent_display;
if f.horizontal {
let inner = std::mem::replace(&mut self.vertical, f.parent_vertical);
self.paragraph = f.parent_paragraph;
if displayed {
return self.finish_display_alignment(inner, f.span, files);
}
self.vertical.prev_depth = inner.prev_depth;
let start = self.vertical.nodes.len();
self.vertical.append_builder(inner);
self.emit_vertical(start);
self.request_page();
} else {
let inner = self.paragraph.take().unwrap();
self.paragraph = f.parent_paragraph;
self.vertical.leave_nested(f.parent_vertical, true);
let p = self.paragraph.as_mut().unwrap();
p.nodes.extend(inner.nodes);
p.space_factor = inner.space_factor;
}
Ok(())
}
}
fn empty_alignment_box(width: i64, horizontal: bool, span: Span) -> NativeBox {
NativeBox {
kind: if horizontal {
BoxKind::Horizontal
} else {
BoxKind::Vertical
},
display: false,
width: if horizontal { width } else { 0 },
height: if horizontal { 0 } else { width },
depth: 0,
shift: 0,
content: if horizontal {
BoxContent::Horizontal(Vec::new())
} else {
BoxContent::Vertical(Vec::new())
},
diagnostic: Vec::new(),
setting: GlueSetting::default(),
badness: 0,
diagnostic_eligible: false,
excess: 0,
span,
}
}
fn alignment_prototype(
f: &AlignmentFrame,
widths: &[i64],
state: &State,
) -> Result<NativeBox, String> {
if f.horizontal {
let mut nodes = vec![TextNode::NamedGlue(f.skips[0], Parameter::Tabskip)];
for (j, &w) in widths.iter().enumerate() {
nodes.push(TextNode::Box(
empty_alignment_box(w, true, f.span).horizontal_item(),
));
nodes.push(TextNode::NamedGlue(f.skips[j + 1], Parameter::Tabskip));
}
boxes::hpack(nodes, f.spec, f.span, state)
} else {
let mut nodes = vec![NativeVerticalNode::NamedGlue(
f.skips[0],
Parameter::Tabskip,
)];
for (j, &w) in widths.iter().enumerate() {
nodes.push(NativeVerticalNode::Box(Box::new(empty_alignment_box(
w, false, f.span,
))));
nodes.push(NativeVerticalNode::NamedGlue(
f.skips[j + 1],
Parameter::Tabskip,
));
}
boxes::vpack(nodes, f.spec, i32::MAX, BoxKind::Vertical, f.span)
}
}
fn set_alignment_cell(
cell: &mut NativeBox,
extent: i64,
first: i64,
row_width: i64,
row_height: i64,
row_depth: i64,
) {
let mut stretch = [0; 4];
let mut shrink = [0; 4];
let mut add = |g: Glue| {
stretch[g.stretch.order as usize] += i64::from(g.stretch.amount);
shrink[g.shrink.order as usize] += i64::from(g.shrink.amount);
};
let horizontal = matches!(&cell.content, BoxContent::Horizontal(_));
cell.kind = if horizontal {
BoxKind::Horizontal
} else {
BoxKind::Vertical
};
match &cell.content {
BoxContent::Horizontal(v) => {
for n in v {
if let TextNode::Glue(g)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
add(*g)
}
}
}
BoxContent::Vertical(v) => {
for n in v {
if let NativeVerticalNode::Glue(g)
| NativeVerticalNode::NamedGlue(g, _)
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
add(*g)
}
}
}
}
let natural = if horizontal { cell.width } else { cell.height };
cell.setting = boxes::setting(extent - natural, stretch, shrink, true).0;
if horizontal {
cell.width = first;
cell.height = row_height;
cell.depth = row_depth;
} else {
cell.height = first;
cell.width = row_width;
}
cell.badness = 0;
cell.diagnostic_eligible = false;
cell.excess = 0;
}
fn set_alignment_row(
row: &mut NativeBox,
widths: &[i64],
skips: &[Glue],
prototype: &NativeBox,
) -> Result<(), String> {
// The actual unset nodes own their span records. Finalization only visits
// the root linked list, including after rows have been removed or moved.
let original: Vec<&NativeBox> = match &row.content {
BoxContent::Horizontal(v) => v
.iter()
.filter_map(|n| match n {
TextNode::Box(b) => b.native_box.as_deref(),
_ => None,
})
.collect(),
BoxContent::Vertical(v) => v
.iter()
.filter_map(|n| match n {
NativeVerticalNode::Box(b) => Some(b.as_ref()),
_ => None,
})
.collect(),
};
if original.is_empty() {
return Err("invalid native unset alignment row".into());
}
let mut spans = Vec::with_capacity(original.len());
let mut first = 0usize;
for cell in original {
let BoxKind::Unset { span, .. } = cell.kind else {
return Err("invalid native unset alignment cell".into());
};
let last = first + usize::from(span);
if last >= widths.len() {
return Err("native unset alignment span exceeds preamble".into());
}
spans.push((first, last));
first = last + 1;
}
let horizontal = matches!(&row.content, BoxContent::Horizontal(_));
row.kind = if horizontal {
BoxKind::Horizontal
} else {
BoxKind::Vertical
};
let old = std::mem::replace(&mut row.content, BoxContent::Horizontal(Vec::new()));
let mut cells: VecDeque<NativeBox> = match old {
BoxContent::Horizontal(v) => v
.into_iter()
.filter_map(|n| match n {
TextNode::Box(b) => b.native_box.map(|b| *b),
_ => None,
})
.collect(),
BoxContent::Vertical(v) => v
.into_iter()
.filter_map(|n| match n {
NativeVerticalNode::Box(b) => Some(*b),
_ => None,
})
.collect(),
};
let mut h = Vec::new();
let mut v = Vec::new();
if horizontal {
h.push(TextNode::NamedGlue(skips[0], Parameter::Tabskip));
} else {
v.push(NativeVerticalNode::NamedGlue(skips[0], Parameter::Tabskip));
}
for (first, last) in spans {
let mut extent = widths[first];
for j in first..last {
let (mut sum, mut previous) = (0, 0);
extent += i64::from(skips[j + 1].width)
+ prototype
.setting
.adjustment(skips[j + 1], &mut sum, &mut previous)
+ widths[j + 1];
}
let mut cell = cells.pop_front().unwrap();
set_alignment_cell(
&mut cell,
extent,
widths[first],
row.width,
row.height,
row.depth,
);
if horizontal {
h.push(TextNode::Box(cell.horizontal_item()));
} else {
v.push(NativeVerticalNode::Box(Box::new(cell)));
}
for j in first..last {
let blank = empty_alignment_box(widths[j + 1], horizontal, row.span);
if horizontal {
h.push(TextNode::NamedGlue(skips[j + 1], Parameter::Tabskip));
h.push(TextNode::Box(blank.horizontal_item()));
} else {
v.push(NativeVerticalNode::NamedGlue(
skips[j + 1],
Parameter::Tabskip,
));
v.push(NativeVerticalNode::Box(Box::new(blank)));
}
}
if horizontal {
h.push(TextNode::NamedGlue(skips[last + 1], Parameter::Tabskip));
} else {
v.push(NativeVerticalNode::NamedGlue(
skips[last + 1],
Parameter::Tabskip,
));
}
}
row.setting = prototype.setting;
row.badness = 0;
row.diagnostic_eligible = false;
row.excess = 0;
if horizontal {
row.width = prototype.width;
row.diagnostic = super::super::diagnostics::text_nodes(&h);
row.content = BoxContent::Horizontal(h);
} else {
row.height = prototype.height;
row.content = BoxContent::Vertical(v);
}
Ok(())
}
fn mark_unset(b: &mut NativeBox, span: u8) -> Result<(), String> {
let mut stretch = [0i64; 4];
let mut shrink = [0i64; 4];
let mut add = |g: Glue| {
stretch[g.stretch.order as usize] += i64::from(g.stretch.amount);
shrink[g.shrink.order as usize] += i64::from(g.shrink.amount);
};
match &b.content {
BoxContent::Horizontal(v) => {
for n in v {
if let TextNode::Glue(g)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
add(*g);
}
}
}
BoxContent::Vertical(v) => {
for n in v {
if let NativeVerticalNode::Glue(g)
| NativeVerticalNode::NamedGlue(g, _)
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) = n
{
add(*g);
}
}
}
}
let flex = |totals: [i64; 4]| -> Result<Flex, String> {
let order = (0..4).rev().find(|&i| totals[i] != 0).unwrap_or(0);
Ok(Flex {
amount: i32::try_from(totals[order])
.map_err(|_| "native unset glue capacity exceeded")?,
order: order as u8,
})
};
b.kind = BoxKind::Unset {
span,
stretch: flex(stretch)?,
shrink: flex(shrink)?,
};
Ok(())
}