Report active native math alignment and output lists

This commit is contained in:
gloamxun committed 2026-11-21 06:26:49 +08:00
1 parent 3ed2c2cd54
commit d02777a1fc
12 files changed
+779 -199

No files matched your search

@@ -1,6 +1,8 @@
//! Lossless native list diagnostics; never infer TeX nodes from painted positions.
use super::registers::print_scaled;
use super::*;
mod math;
pub(super) use math::show_math;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum DiagnosticNode {
Language(HyphenationLanguage),
@@ -0,0 +1,298 @@
use super::*;
use crate::math_engine_tex::MathStyle;
impl Printer<'_> {
fn delimiter(&mut self, delimiter: Delimiter) {
let small = u32::from(delimiter.small.family) * 256 + u32::from(delimiter.small.slot);
let large = u32::from(delimiter.large.family) * 256 + u32::from(delimiter.large.slot);
self.literal(&format!("\"{:X}", (small << 12) | large));
}
fn math_character(&mut self, character: MathChar) {
self.command("fam");
self.literal(&format!("{} ", character.family));
self.ascii(character.slot);
}
fn math_field(&mut self, field: &MathField, parent: &str, part: char) -> Result<(), String> {
if matches!(field, MathField::Empty) {
return Ok(());
}
if parent.len() as i32 >= self.depth {
self.literal(" []");
return Ok(());
}
let prefix = format!("{parent}{part}");
match field {
MathField::Empty => {}
MathField::Char(character) => {
self.line(&prefix);
self.math_character(*character);
}
// math_text_char is only introduced by conversion, after the
// original noad can appear in the active list.
MathField::TextChar(_) => {}
MathField::List(nodes) => self.math_sublist(nodes, None, &prefix)?,
MathField::Box(boxed) => {
self.line(&prefix);
self.box_(&box_view(boxed), &prefix)?;
}
MathField::Radical(_, argument) => self.math_field(argument, parent, part)?,
}
Ok(())
}
fn math_sublist(
&mut self,
nodes: &[MathNode],
leading: Option<Delimiter>,
prefix: &str,
) -> Result<(), String> {
if nodes.is_empty() && leading.is_none() {
self.line(prefix);
self.literal("{}");
} else {
self.math_list(nodes, leading, prefix)?;
}
Ok(())
}
fn noad(&mut self, noad: &Noad, prefix: &str) -> Result<(), String> {
if let Some(accent) = noad.accent {
self.command("accent");
self.math_character(accent);
} else if let MathField::Radical(delimiter, _) = &noad.nucleus {
self.command("radical");
self.delimiter(*delimiter);
} else if let Some(rule) = noad.rule {
self.command(match rule {
MathRulePosition::Over => "overline",
MathRulePosition::Under => "underline",
});
} else if noad.vcenter {
self.command("vcenter");
} else {
self.command(match noad.class {
NoadClass::Ord => "mathord",
NoadClass::Op => "mathop",
NoadClass::Bin => "mathbin",
NoadClass::Rel => "mathrel",
NoadClass::Open => "mathopen",
NoadClass::Close => "mathclose",
NoadClass::Punct => "mathpunct",
NoadClass::Inner => "mathinner",
});
}
match noad.limits {
OperatorLimits::Display => {}
OperatorLimits::AboveBelow => self.command("limits"),
OperatorLimits::Side => self.command("nolimits"),
}
self.math_field(&noad.nucleus, prefix, '.')?;
if let Some(sup) = &noad.sup {
self.math_field(sup, prefix, '^')?;
}
if let Some(sub) = &noad.sub {
self.math_field(sub, prefix, '_')?;
}
Ok(())
}
fn fraction(
&mut self,
specification: &FractionSpec,
numerator: &[MathNode],
leading: Option<Delimiter>,
denominator: Option<&[MathNode]>,
prefix: &str,
) -> Result<(), String> {
self.command("fraction");
self.literal(", thickness ");
if let Some(thickness) = specification.thickness {
self.number(i64::from(thickness));
} else {
self.literal("= default");
}
for (name, delimiter) in [("left", specification.left), ("right", specification.right)] {
if delimiter != Delimiter::from_code(0) {
self.literal(&format!(", {name}-delimiter "));
self.delimiter(delimiter);
}
}
if prefix.len() as i32 >= self.depth {
self.literal(" []");
if denominator.is_some() {
self.literal(" []");
}
} else {
self.math_sublist(numerator, leading, &format!("{prefix}\\"))?;
if let Some(denominator) = denominator {
self.math_sublist(denominator, None, &format!("{prefix}/"))?;
}
}
Ok(())
}
fn math_glue(&mut self, glue: Glue) {
self.command("glue");
self.literal("(");
self.command("mskip");
self.literal(") ");
self.number(i64::from(glue.width));
self.literal("mu");
for (label, flex) in [(" plus ", glue.stretch), (" minus ", glue.shrink)] {
if flex.amount != 0 {
self.literal(label);
self.flex(flex.amount, flex.order);
if flex.order == 0 {
self.literal("mu");
}
}
}
}
fn math_list(
&mut self,
nodes: &[MathNode],
leading: Option<Delimiter>,
prefix: &str,
) -> Result<(), String> {
if prefix.len() as i32 > self.depth {
if !nodes.is_empty() || leading.is_some() {
self.literal(" []");
}
return Ok(());
}
if let Some(delimiter) = leading {
self.line(prefix);
self.command("left");
self.delimiter(delimiter);
}
for (i, node) in nodes.iter().enumerate() {
if self.overflow {
break;
}
if i + usize::from(leading.is_some()) >= self.breadth {
self.line(prefix);
self.literal("etc.");
break;
}
let ordinary = match node {
MathNode::ExplicitSpace(glue, name) => Some(DiagnosticNode::Glue {
value: *glue,
name: *name,
}),
MathNode::Leaders(leader) => Some(leader_node(leader)),
MathNode::Kern {
amount,
mu: false,
explicit,
} => Some(DiagnosticNode::Kern {
width: *amount,
explicit: *explicit,
}),
MathNode::Penalty(n) => Some(DiagnosticNode::Penalty(*n)),
MathNode::Rule(rule) => Some(DiagnosticNode::Rule(*rule)),
MathNode::Mark(mark) => Some(DiagnosticNode::Mark(mark.clone())),
MathNode::Adjustment(adjustment) => Some(DiagnosticNode::Adjustment {
pre: adjustment.pre,
nodes: vertical_nodes(&adjustment.nodes),
}),
MathNode::Insertion(insertion) => Some(insertion_view(insertion)),
MathNode::Output(output) => Some(DiagnosticNode::Output(output.clone())),
MathNode::Discretionary(node) => {
text_nodes(std::slice::from_ref(node.as_ref())).pop()
}
_ => None,
};
if let Some(node) = ordinary {
self.nodes(&[node], prefix)?;
continue;
}
self.line(prefix);
match node {
MathNode::Noad(noad) => self.noad(noad, prefix)?,
MathNode::Delimiter { value, opening, .. } => {
self.command(if *opening { "left" } else { "right" });
self.delimiter(*value);
}
MathNode::Style(style) => self.command(match style {
MathStyle::Display | MathStyle::DisplayCramped => "displaystyle",
MathStyle::Text | MathStyle::TextCramped => "textstyle",
MathStyle::Script | MathStyle::ScriptCramped => "scriptstyle",
MathStyle::ScriptScript | MathStyle::ScriptScriptCramped => "scriptscriptstyle",
}),
MathNode::Choice(branches) => {
self.command("mathchoice");
for (label, branch) in ['D', 'T', 'S', 's'].into_iter().zip(branches.iter()) {
self.math_list(branch, None, &format!("{prefix}{label}"))?;
}
}
MathNode::Glue(glue) => self.math_glue(*glue),
MathNode::Kern {
amount, mu: true, ..
} => {
self.command("mkern");
self.number(i64::from(*amount));
self.literal("mu");
}
MathNode::Fraction {
numerator,
denominator,
specification,
..
} => {
self.fraction(specification, numerator, None, Some(denominator), prefix)?;
}
_ => unreachable!("ordinary math list item"),
}
}
Ok(())
}
}
pub(in crate::execution) fn show_math(
state: &State,
math: &super::super::math::MathBuilder,
breadth: i32,
depth: i32,
limit: usize,
wrap: bool,
) -> Result<(String, BTreeSet<Dependency>), String> {
let mut printer = Printer {
state,
out: String::new(),
column: 0,
tally: 0,
breadth: if breadth <= 0 { 5 } else { breadth as usize },
depth,
limit,
overflow: false,
wrap,
reads: BTreeSet::new(),
};
let leading = math.left.as_ref().map(|(left, _)| *left);
if let Some(pending) = &math.numerator {
printer.math_list(&math.nodes, None, "")?;
printer.line("this will begin denominator of:");
if depth < 0 {
printer.literal(" []");
} else {
printer.line("");
printer.fraction(
&pending.specification,
&pending.numerator,
leading,
None,
"",
)?;
}
} else {
printer.math_list(&math.nodes, leading, "")?;
}
if printer.overflow {
return Err("native math list diagnostic output capacity exceeded".into());
}
printer.raw('\n');
Ok((printer.out, printer.reads))
}
@@ -30,10 +30,10 @@ struct Cell {
}
#[derive(Clone)]
pub(super) struct AlignmentFrame {
horizontal: bool,
span: Span,
pub(super) horizontal: bool,
pub(super) span: Span,
spec: PackSpec,
depth: usize,
pub(super) depth: usize,
stage: Stage,
templates: Vec<Template>,
skips: Vec<Glue>,
@@ -43,21 +43,37 @@ pub(super) struct AlignmentFrame {
column: usize,
first: usize,
omitted: bool,
terminator: Option<Primitive>,
terminator: Option<(Primitive, Span)>,
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>,
pub(super) parent_paragraph: Option<super::super::paragraph::Builder>,
pub(super) parent_vertical: VerticalBuilder,
pub(super) parent_math: Vec<super::super::math::MathBuilder>,
pub(super) parent_display: Option<super::display::DisplayFrame>,
parent_balance: i64,
row_paragraph: Option<super::super::paragraph::Builder>,
row_vertical: VerticalBuilder,
pub(super) row_paragraph: Option<super::super::paragraph::Builder>,
pub(super) row_vertical: VerticalBuilder,
row_span: Option<Span>,
pub(super) cell_span: Option<Span>,
}
impl AlignmentFrame {
pub(super) fn activity_row(&self) -> Option<(Span, Vec<super::super::diagnostics::DiagnosticNode>)> {
use super::super::diagnostics::{DiagnosticNode, box_view};
let span = self.row_span?;
let tabskip = |value| DiagnosticNode::Glue { value, name: Some(Parameter::Tabskip) };
let mut nodes = Vec::with_capacity(1 + 2 * self.cells.len());
nodes.push(tabskip(self.skips[0]));
for cell in &self.cells {
nodes.push(DiagnosticNode::Box(box_view(&cell.node)));
nodes.push(tabskip(self.skips[cell.last + 1]));
}
Some((span, nodes))
}
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]
@@ -150,7 +166,7 @@ impl Executor {
if frame.stage != Stage::Entry {
return self.fail("interwoven native alignment preambles");
}
frame.terminator = Some(end);
frame.terminator = Some((end, token.token.invocation.unwrap_or(token.token.span)));
frame.stage = Stage::Suffix;
let suffix = if frame.omitted {
Vec::new()
@@ -238,6 +254,8 @@ impl Executor {
parent_balance,
row_paragraph: None,
row_vertical: VerticalBuilder::default(),
row_span: None,
cell_span: None,
});
self.alignment_balance = -1_000_000;
if horizontal {
@@ -399,18 +417,22 @@ impl Executor {
let frame = self.alignments.last_mut().unwrap();
frame.column = 0;
frame.first = 0;
self.begin_alignment_cell(false, files)?;
let span = t.token.invocation.unwrap_or(t.token.span);
frame.row_span = Some(span);
self.begin_alignment_cell(false, span, files)?;
self.begin_alignment_template(t)
}
fn begin_alignment_cell(
&mut self,
spanning: bool,
cell_span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if spanning {
return Ok(());
}
let frame = self.alignments.last_mut().unwrap();
frame.cell_span = Some(cell_span);
frame.row_paragraph = self.paragraph.take();
let horizontal = frame.horizontal;
frame.row_vertical = self.vertical.enter_nested(horizontal);
@@ -447,7 +469,7 @@ impl Executor {
return self.fail("unbalanced native alignment entry");
}
self.finish_text(true)?;
let (end, horizontal, span, first, last) = {
let ((end, end_span), horizontal, span, first, last) = {
let f = self.alignments.last().unwrap();
(
f.terminator.unwrap(),
@@ -510,7 +532,7 @@ impl Executor {
}
self.alignment_balance = 1_000_000;
let t = self.expanded_non_space(files)?;
self.begin_alignment_cell(end == Primitive::Span, files)?;
self.begin_alignment_cell(end == Primitive::Span, end_span, files)?;
self.begin_alignment_template(t)
}
fn extend_alignment_preamble(&mut self) -> Result<(), Error> {
@@ -544,6 +566,8 @@ impl Executor {
fn finish_alignment_row(&mut self) -> Result<(), Error> {
let f = self.alignments.last_mut().unwrap();
let cells = std::mem::take(&mut f.cells);
f.row_span = None;
f.cell_span = None;
let mut node = if f.horizontal {
let mut nodes = vec![TextNode::NamedGlue(f.skips[0], Parameter::Tabskip)];
for cell in cells {
@@ -20,17 +20,17 @@ pub(super) struct BoxFrame {
pub(super) paragraph: Option<super::super::paragraph::Builder>,
pub(super) vertical: VerticalBuilder,
pub(super) span: Span,
discretionary: Option<DiscretionaryFrame>,
pub(super) discretionary: Option<DiscretionaryFrame>,
pub(super) math: Vec<super::super::math::MathBuilder>,
// An inner $...$ belongs to this box, even inside an outer display.
display: Option<super::display::DisplayFrame>,
pub(super) display: Option<super::display::DisplayFrame>,
}
#[derive(Clone)]
struct DiscretionaryFrame {
pub(super) struct DiscretionaryFrame {
parts: Vec<Vec<TextNode>>,
font: FontId,
span: Span,
math: Vec<super::super::math::MathBuilder>,
pub(super) math: Vec<super::super::math::MathBuilder>,
}
impl BoxFrame {
pub(super) fn collect_statistics(&self, c: &mut super::super::statistics::Collector) {
@@ -1,4 +1,4 @@
use super::super::diagnostics::{DiagnosticNode, show_nodes, text_nodes, vertical_nodes};
mod activity;
use super::*;
impl Executor {
pub(super) fn trace_conditional(
@@ -626,179 +626,6 @@ impl Executor {
lines.push("### bottom level".into());
lines
}
fn activity_lists(
&self,
breadth: i32,
depth: i32,
wrap: bool,
) -> Result<(String, BTreeSet<Dependency>), String> {
if !self.math.is_empty()
|| self.box_frames.iter().any(|frame| !frame.math.is_empty())
|| !self.alignments.is_empty()
|| self.output_frame.is_some()
{
return Err(
"native showlists requires math, alignment or output nest diagnostics".into(),
);
}
let mut frames = Vec::new();
let mut enclosing_span = None;
for frame in &self.box_frames {
frames.push((frame.paragraph.as_ref(), &frame.vertical, enclosing_span));
enclosing_span = Some(frame.span);
}
frames.push((self.paragraph.as_ref(), &self.vertical, enclosing_span));
let mut text = String::new();
let mut reads = BTreeSet::from([
Dependency::ParagraphMode,
Dependency::VerticalState,
Dependency::PageState,
Dependency::FontResources,
Dependency::EscapeChar,
Dependency::NewLineChar,
]);
let mut line = |span: Span| {
reads.insert(Dependency::InputPosition(span.source));
let prefix = self
.sources
.get(span.source)
.and_then(|source| source.data.get(..span.start))
.unwrap_or_default();
let eols = prefix
.iter()
.enumerate()
.filter(|&(index, byte)| {
*byte == b'\r' || (*byte == b'\n' && (index == 0 || prefix[index - 1] != b'\r'))
})
.count();
eols + 1
};
let mut levels = Vec::new();
for (paragraph, vertical, span) in frames.into_iter().rev() {
levels.push((
paragraph.map(|p| (p, line(p.span))),
vertical,
span.map(&mut line),
));
}
let mut render = |text: &mut String, nodes: &[DiagnosticNode]| -> Result<(), String> {
let (part, used) =
show_nodes(&self.state, nodes, breadth, depth, self.limits.tokens, wrap)?;
if text.len().saturating_add(part.len()) > self.limits.tokens {
return Err("native list diagnostic output limit exceeded".into());
}
text.push_str(&part);
reads.extend(used);
Ok(())
};
for (paragraph, vertical, enter) in levels {
if !text.is_empty() {
text.push('\n');
}
if let Some((paragraph, line)) = paragraph {
let mode = if paragraph.restricted {
"restricted horizontal"
} else {
"horizontal"
};
text.push_str(&format!("### {mode} mode entered at line {line}"));
let language = paragraph.initial_language;
if !paragraph.restricted
&& (language.language != 0 || language.left_min != 2 || language.right_min != 3)
{
text.push_str(&format!(
" (language{}:hyphenmin{},{})",
language.language, language.left_min, language.right_min
));
}
render(&mut text, &text_nodes(&paragraph.nodes))?;
text.push_str(&format!("\n\nspacefactor {}", paragraph.space_factor));
if !paragraph.restricted && paragraph.current_language.language != 0 {
text.push_str(&format!(
", current language {}",
paragraph.current_language.language
));
}
if paragraph.restricted {
continue;
}
text.push('\n');
}
let mode = if enter.is_some() {
"internal vertical"
} else {
"vertical"
};
text.push_str(&format!(
"### {mode} mode entered at line {}",
enter.unwrap_or(0)
));
if enter.is_none()
&& let Some(page) = &self.native_page
{
if !page.nodes.is_empty() {
text.push_str("\n### current page:");
render(&mut text, &vertical_nodes(&page.nodes))?;
if page.started {
let [goal, total, plus, fil, fill, filll, shrink, _] = page.dimensions;
text.push_str(&format!(
"\n\n total height {}",
registers::print_scaled_wide(total)
));
for (value, unit) in
[(plus, ""), (fil, "fil"), (fill, "fill"), (filll, "filll")]
{
if value != 0 {
text.push_str(&format!(
" plus {}{unit}",
registers::print_scaled_wide(value)
));
}
}
if shrink != 0 {
text.push_str(&format!(
" minus {}",
registers::print_scaled_wide(shrink)
));
}
text.push_str(&format!(
"\n goal height {}",
registers::print_scaled_wide(goal)
));
}
text.push('\n');
}
if !page.contributions.is_empty() {
text.push_str("\n### recent contributions:");
let pending: Vec<_> = page.contributions.iter().cloned().collect();
render(&mut text, &vertical_nodes(&pending))?;
}
}
if enter.is_none() && !vertical.nodes.is_empty() && self.native_page.is_some() {
text.push_str("\n### recent contributions:");
}
render(&mut text, &vertical_nodes(&vertical.nodes))?;
text.push_str("\n\nprevdepth ");
if vertical.prev_depth <= -1000 * 65536 {
text.push_str("ignored");
} else {
text.push_str(&registers::print_scaled(vertical.prev_depth));
}
if vertical.previous_lines != 0 {
let suffix = if vertical.previous_lines == 1 {
""
} else {
"s"
};
text.push_str(&format!(
", prevgraf {} line{suffix}",
vertical.previous_lines
));
}
}
Ok((text, reads))
}
}
impl Executor {
@@ -0,0 +1,348 @@
use super::*;
use crate::execution::{
boxes::VerticalBuilder,
diagnostics::{DiagnosticNode, show_math, show_nodes, text_nodes, vertical_nodes},
math::MathBuilder,
paragraph::Builder,
};
#[derive(Clone, Copy, Default)]
struct Entry {
span: Option<Span>,
output: bool,
cell: bool,
}
impl Entry {
fn at(span: Span) -> Self {
Self {
span: Some(span),
..Self::default()
}
}
}
struct SavedList<'a> {
paragraph: Option<&'a Builder>,
vertical: &'a VerticalBuilder,
math: &'a [MathBuilder],
display: bool,
entry: Entry,
}
enum Level<'a> {
List(SavedList<'a>),
AlignmentRow(&'a super::super::alignment::AlignmentFrame),
}
enum Owner<'a> {
Box(&'a super::super::boxes::BoxFrame),
Alignment(&'a super::super::alignment::AlignmentFrame),
Output(&'a super::super::page::OutputFrame),
}
impl Executor {
fn activity_line(&self, span: Span, reads: &mut BTreeSet<Dependency>) -> usize {
reads.insert(Dependency::InputPosition(span.source));
let prefix = self
.sources
.get(span.source)
.and_then(|source| source.data.get(..span.start))
.unwrap_or_default();
prefix
.iter()
.enumerate()
.filter(|&(index, byte)| {
*byte == b'\r' || (*byte == b'\n' && (index == 0 || prefix[index - 1] != b'\r'))
})
.count()
+ 1
}
fn activity_levels(&self) -> Vec<Level<'_>> {
// Box, alignment and output frames each retain their suspended lists.
// The opening group depths give their order across those stacks.
let mut owners = Vec::new();
owners.extend(self.box_frames.iter().map(|f| (f.depth, Owner::Box(f))));
owners.extend(
self.alignments
.iter()
.map(|f| (f.depth, Owner::Alignment(f))),
);
owners.extend(
self.output_frame
.iter()
.map(|f| (f.depth, Owner::Output(f))),
);
owners.sort_by_key(|(depth, _)| *depth);
let mut levels = Vec::new();
let mut entry = Entry::default();
for (_, owner) in owners {
match owner {
Owner::Box(frame) => {
let math = frame
.discretionary
.as_ref()
.map_or(&frame.math[..], |disc| &disc.math[..]);
levels.push(Level::List(SavedList {
paragraph: frame.paragraph.as_ref(),
vertical: &frame.vertical,
math,
display: frame.display.is_some(),
entry,
}));
entry = Entry::at(frame.span);
}
Owner::Alignment(frame) => {
levels.push(Level::List(SavedList {
paragraph: frame.parent_paragraph.as_ref(),
vertical: &frame.parent_vertical,
math: &frame.parent_math,
display: frame.parent_display.is_some(),
entry,
}));
entry = Entry::at(frame.span);
if let Some(cell) = frame.cell_span {
levels.push(Level::List(SavedList {
paragraph: frame.row_paragraph.as_ref(),
vertical: &frame.row_vertical,
math: &[],
display: false,
entry,
}));
levels.push(Level::AlignmentRow(frame));
entry = Entry {
cell: frame.horizontal,
..Entry::at(cell)
};
}
}
Owner::Output(frame) => {
levels.push(Level::List(SavedList {
paragraph: frame.paragraph.as_ref(),
vertical: &frame.vertical,
math: &frame.math,
display: frame.display.is_some(),
entry,
}));
entry = Entry {
output: true,
..Entry::at(frame.span)
};
}
}
}
levels.push(Level::List(SavedList {
paragraph: self.paragraph.as_ref(),
vertical: &self.vertical,
math: &self.math,
display: self.display.is_some(),
entry,
}));
levels
}
pub(super) fn activity_lists(
&self,
breadth: i32,
depth: i32,
wrap: bool,
) -> Result<(String, BTreeSet<Dependency>), String> {
let mut text = String::new();
let auxiliary_break = if wrap { "\n" } else { "\n\n" };
let mut reads = BTreeSet::from([
Dependency::ParagraphMode,
Dependency::VerticalState,
Dependency::PageState,
Dependency::FontResources,
Dependency::EscapeChar,
Dependency::NewLineChar,
]);
let render = |text: &mut String,
reads: &mut BTreeSet<Dependency>,
nodes: &[DiagnosticNode]|
-> Result<(), String> {
let remaining = self.limits.tokens.saturating_sub(text.len());
let (part, used) = show_nodes(&self.state, nodes, breadth, depth, remaining, wrap)?;
text.push_str(&part);
reads.extend(used);
Ok(())
};
for level in self.activity_levels().into_iter().rev() {
if !text.is_empty() {
text.push('\n');
}
let list = match level {
Level::List(list) => list,
Level::AlignmentRow(frame) => {
let (span, nodes) = frame.activity_row().expect("active alignment row");
let line = self.activity_line(span, &mut reads);
let (mode, aux) = if frame.horizontal {
("restricted horizontal", "spacefactor 0")
} else {
("internal vertical", "prevdepth 0.0")
};
text.push_str(&format!("### {mode} mode entered at line {line}"));
render(&mut text, &mut reads, &nodes)?;
text.push_str(&format!("{auxiliary_break}{aux}"));
continue;
}
};
for (index, math) in list.math.iter().enumerate().rev() {
let mode = if list.display && index == 0 {
"display math"
} else {
"math"
};
let line = self.activity_line(math.span, &mut reads);
text.push_str(&format!("### {mode} mode entered at line {line}"));
let remaining = self.limits.tokens.saturating_sub(text.len());
let (part, used) = show_math(&self.state, math, breadth, depth, remaining, wrap)?;
text.push_str(&part);
if !wrap {
text.push('\n');
}
reads.extend(used);
}
if let Some(paragraph) = list.paragraph {
let mode = if paragraph.restricted {
"restricted horizontal"
} else {
"horizontal"
};
let span = if list.entry.cell {
list.entry.span.expect("alignment cell start")
} else {
paragraph.span
};
let line = self.activity_line(span, &mut reads);
text.push_str(&format!("### {mode} mode entered at line {line}"));
let language = paragraph.initial_language;
if !paragraph.restricted
&& (language.language != 0 || language.left_min != 2 || language.right_min != 3)
{
text.push_str(&format!(
" (language{}:hyphenmin{},{})",
language.language, language.left_min, language.right_min
));
}
render(&mut text, &mut reads, &text_nodes(&paragraph.nodes))?;
text.push_str(&format!(
"{auxiliary_break}spacefactor {}",
paragraph.space_factor
));
if !paragraph.restricted && paragraph.current_language.language != 0 {
text.push_str(&format!(
", current language {}",
paragraph.current_language.language
));
}
if paragraph.restricted {
continue;
}
text.push('\n');
}
let (mode, line) = match list.entry.span {
Some(span) => ("internal vertical", self.activity_line(span, &mut reads)),
None => ("vertical", 0),
};
text.push_str(&format!("### {mode} mode entered at line {line}"));
if list.entry.output {
text.push_str(r" (\output routine)");
}
if list.entry.span.is_none()
&& let Some(page) = &self.native_page
{
let current_page = if page.output_active && !page.insertions.held.is_empty() {
&page.insertions.held
} else {
&page.nodes
};
if !current_page.is_empty() {
text.push_str("\n### current page:");
if page.output_active {
text.push_str(" (held over for next output)");
}
render(&mut text, &mut reads, &vertical_nodes(current_page))?;
if page.activity_page_specs() {
let [goal, total, plus, fil, fill, filll, shrink, _] = page.dimensions;
text.push_str(&format!(
"{auxiliary_break}total height {}",
registers::print_scaled_wide(total)
));
for (value, unit) in
[(plus, ""), (fil, "fil"), (fill, "fill"), (filll, "filll")]
{
if value != 0 {
text.push_str(&format!(
" plus {}{unit}",
registers::print_scaled_wide(value)
));
}
}
if shrink != 0 {
text.push_str(&format!(
" minus {}",
registers::print_scaled_wide(shrink)
));
}
text.push_str(&format!(
"\n goal height {}",
registers::print_scaled_wide(goal)
));
let escape = u8::try_from(self.state.escapechar)
.ok()
.map_or_else(String::new, |c| char::from(c).to_string());
for (class, size, split) in
page.insertions.activity(&self.state, &page.nodes)
{
reads.insert(Dependency::Count(class.into()));
text.push_str(&format!(
"\n{escape}insert{class} adds {}",
registers::print_scaled_wide(size)
));
if let Some(n) = split {
text.push_str(&format!(", #{n} might split"));
}
}
} else if !wrap {
text.push('\n');
}
}
if !page.contributions.is_empty() {
text.push_str("\n### recent contributions:");
let pending: Vec<_> = page.contributions.iter().cloned().collect();
render(&mut text, &mut reads, &vertical_nodes(&pending))?;
}
}
let vertical = list.vertical;
if list.entry.span.is_none() && !vertical.nodes.is_empty() && self.native_page.is_some()
{
text.push_str("\n### recent contributions:");
}
render(&mut text, &mut reads, &vertical_nodes(&vertical.nodes))?;
text.push_str(auxiliary_break);
text.push_str("prevdepth ");
if vertical.prev_depth <= -1000 * 65536 {
text.push_str("ignored");
} else {
text.push_str(&registers::print_scaled(vertical.prev_depth));
}
if vertical.previous_lines != 0 {
let suffix = if vertical.previous_lines == 1 {
""
} else {
"s"
};
text.push_str(&format!(
", prevgraf {} line{suffix}",
vertical.previous_lines
));
}
}
if text.len() > self.limits.tokens {
return Err("native list diagnostic output limit exceeded".into());
}
Ok((text, reads))
}
}
@@ -786,7 +786,8 @@ impl Executor {
| Knbccode | Knaccode | Letterspacefont | Textfont | Scriptfont
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
| Endinput | Showbox | Show | Showthe | Showlists | Showifs | Showgroups
| Discretionary | DiscretionaryHyphen
| Parshape | Partokenname => {
return Ok(false);
}
@@ -3,11 +3,12 @@ use super::*;
#[derive(Clone)]
pub(super) struct OutputFrame {
depth: usize,
paragraph: Option<super::super::paragraph::Builder>,
vertical: VerticalBuilder,
math: Vec<super::super::math::MathBuilder>,
display: Option<super::display::DisplayFrame>,
pub(super) depth: usize,
pub(super) span: Span,
pub(super) paragraph: Option<super::super::paragraph::Builder>,
pub(super) vertical: VerticalBuilder,
pub(super) math: Vec<super::super::math::MathBuilder>,
pub(super) display: Option<super::display::DisplayFrame>,
}
impl OutputFrame {
pub(super) fn collect_statistics(&self, c: &mut super::super::statistics::Collector) {
@@ -151,6 +152,7 @@ impl Executor {
}
self.output_frame = Some(OutputFrame {
depth: self.state.group_depth() + 1,
span: self.current,
paragraph: self.paragraph.take(),
vertical: std::mem::take(&mut self.vertical),
math: std::mem::take(&mut self.math),
@@ -51,6 +51,24 @@ fn scale(size: i64, factor: i64) -> i64 {
}
impl PageInsertions {
pub(super) fn activity<'a>(
&'a self,
state: &'a State,
nodes: &'a [NativeVerticalNode],
) -> impl Iterator<Item = (u8, i64, Option<usize>)> + 'a {
self.classes.iter().map(move |(&class, entry)| {
let size = scale(entry.size, i64::from(state.count(class.into())));
let split = entry.split.then(|| {
nodes
.iter()
.take(entry.placement.last + 1)
.filter(|node| matches!(node, NativeVerticalNode::Insertion(n) if n.class == class))
.count()
});
(class, size, split)
})
}
pub fn record_front(
&mut self,
node: &NativeInsertion,
@@ -158,6 +158,10 @@ impl NativePageState {
}
}
pub(super) fn activity_page_specs(&self) -> bool {
self.specs_frozen
}
pub(super) fn resume_contributions(&mut self, output_material: Vec<NativeVerticalNode>) {
self.discards.clear();
let held = self.insertions.held.drain(..);
+23 -1
View File
@@ -1457,7 +1457,7 @@ XYZ、Fit 与 FitH/FitV 系列在本阶段覆盖,矩形视图见后续实现
`\showgroups` 和 `\showifs`。诊断读取当时的参数与流状态,通过原生文件
写出路径写入实际打开的流。关闭后恢复常规日志及交互诊断。新增格式
schema48,继续接受 schema47。活动列表使用真正的盒、段落、页面和
贡献列表。活动数学、对齐、输出例程中的列表与页面插入类摘要仍待覆盖。
贡献列表。活动数学、对齐、输出例程中的列表与页面插入类摘要见后续阶段。
三份 pdfTeX INITEX 文件逐字节一致,覆盖开闭流、长行、8 位字符、真实
分组和条件、空盒和负深度。另有实际横盒、纵盒与已构建页面的流输出
@@ -1535,6 +1535,28 @@ target/p2-pdf-warning-lines-native,回执 SHA-256
c9f4f3f6cbe8f8bdfedaae35ed85bda92850773b2ef0e0f4e1d14c271d264598。
[TeX Live pdfTeX 实现](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web)
### 活动数学、对齐和输出例程的列表
`\showlists` 从原生当前列表和挂起的嵌套读取数据。数学输出包括实际 noad、
上下标、样式、四个数学选择分支、字族槽位及尚未完结的分式。显示
`\halign` 和 `\valign` 的活动单元、未定宽盒、行间材料和真实 `\tabskip`。
输出例程显示发页触发点、待处理的贡献列表与留到下一页的插入项。
页面插入摘要按实际类累计量、当前 `\count` 缩放和已记录的拆分位置产生。
十份重定向诊断逐字节与 pdfTeX 一致,发页数均一致。两份普通日志的
活动列表及 ! OK 区间与参考逐字节一致,均返回交互诊断状态1。22项
定向回归通过。保留首轮失败、跨行单元诊断位置和插入页空行差异。
编辑输出例程内第二页的真实字形后复用877步,仅替换第二页。PDF、
SVG、诊断文件和归一化来源映射均与独立零复用全量一致。
证据在 target/p2-show-lists-active-native。三份回执的 SHA-256 分别为
02f694ded149cb7598a1abec7afb79e5c4ad6ce1396ac709f7b7bc8140912182(重定向),
2ace062c409b6b617247f9025d7fea2b241bb5a3222a8ef56644f914ae6eb0ec(普通日志),
7ab9a6c8967ad11c12b10379ccaaae5e1a045cacefc90adbd494327384ad8739(续编)。
兼容 profile 仍为1.40.22。下一阶段检查修订24对应原语及发布差异,再用
未修改的 LaTeX 格式和原样 ACM 的本地结构目的地做验收。
[TeX Live 的活动列表实现](https://raw.githubusercontent.com/TeX-Live/texlive-source/trunk/texk/web2c/pdftexdir/pdftex.web)
### PDF 字面中的矩阵与来源映射
来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和
+34
View File
@@ -295,3 +295,37 @@ fn automatic_kerns_preserve_raw_ligature_and_hyphen_margin_order() {
fs::remove_dir_all(root).unwrap();
fs::remove_dir_all(oracle).unwrap();
}
#[test]
fn redirected_showlists_preserves_live_nested_math_alignment_and_output() {
let root = directory();
let oracle = directory();
let entry = "activity.tex";
let input = r"\catcode37=14 \catcode38=4
\input math-fonts
\pdfoutput=1
\immediate\openout3=lists.dat \showstream=3
\showboxbreadth=30 \showboxdepth=10
\setbox0=\vbox{\halign{#&\hfil#\cr
A&
\hbox{$x_i^2+{a\over b}\showlists$}\cr}}
\vsize=14pt \output={\showlists\shipout\box255}
\hrule height10pt width4pt
\vskip2pt \penalty-10000
\immediate\closeout3 \end";
let fonts = include_bytes!("../examples/native-bootstrap/math-fonts.tex");
for path in [&root, &oracle] {
fs::write(path.join(entry), input).unwrap();
fs::write(path.join("math-fonts.tex"), fonts).unwrap();
}
let expected = reference(&oracle, entry);
let actual = native(&root, entry);
assert!(expected.status.success(), "{expected:?}");
assert!(actual.status.success(), "{actual:?}");
assert_eq!(
fs::read_to_string(root.join("lists.dat")).unwrap(),
fs::read_to_string(oracle.join("lists.dat")).unwrap()
);
fs::remove_dir_all(root).unwrap();
fs::remove_dir_all(oracle).unwrap();
}