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

890 lines
31 KiB
Rust

//! 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),
Character {
font: FontId,
slot: u8,
#[serde(default, skip_serializing_if = "crate::native_font::unexpanded")]
expansion: i32,
ligature: Option<String>,
},
OpenType { font: FontId, text: String, glyphs: Vec<u16> },
Box(DiagnosticBox),
EmptyBox(i32),
Glue {
value: Glue,
name: Option<Parameter>,
},
Leaders {
value: Glue,
mode: LeaderMode,
pattern: Box<DiagnosticNode>,
},
Kern {
width: i32,
explicit: bool,
},
Math {
width: i32,
after: bool,
},
Penalty(i32),
Discretionary {
pre: Vec<DiagnosticNode>,
post: Vec<DiagnosticNode>,
replacement: u8,
},
Rule(NativeRule),
Mark(NativeMark),
Adjustment {
pre: bool,
nodes: Vec<DiagnosticNode>,
},
Insertion {
class: u8,
natural_size: i64,
split_top: Glue,
split_depth: i32,
float_cost: i32,
nodes: Vec<DiagnosticNode>,
},
Output(OutputNode),
Unsupported(String),
AccentKern(i32),
AutoKern(i32),
MarginKern { width: i32, right: bool },
Direction(DirectionBoundary),
}
/// A semantic view, without recursively copying the box's painted contents.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct DiagnosticBox {
pub kind: BoxKind,
pub display: bool,
pub width: i64,
pub height: i64,
pub depth: i64,
pub shift: i64,
pub setting: GlueSetting,
pub nodes: Vec<DiagnosticNode>,
}
pub(super) fn box_view(b: &NativeBox) -> DiagnosticBox {
let nodes = match &b.content {
BoxContent::Horizontal(_) => b.diagnostic.clone(),
BoxContent::Vertical(v) => vertical_nodes(v),
};
DiagnosticBox {
kind: b.kind,
display: b.display,
width: b.width,
height: b.height,
depth: b.depth,
shift: b.shift,
setting: b.setting,
nodes,
}
}
fn leader_node(leader: &LeaderGlue) -> DiagnosticNode {
let pattern = match &leader.pattern {
LeaderPattern::Box(b) => DiagnosticNode::Box(box_view(b)),
LeaderPattern::Rule(r) => DiagnosticNode::Rule(*r),
};
DiagnosticNode::Leaders {
value: leader.glue,
mode: leader.mode,
pattern: Box::new(pattern),
}
}
pub(super) fn vertical_nodes(nodes: &[NativeVerticalNode]) -> Vec<DiagnosticNode> {
nodes
.iter()
.map(|n| match n {
NativeVerticalNode::Box(b) => DiagnosticNode::Box(box_view(b)),
NativeVerticalNode::Line(b) => DiagnosticNode::Box(box_view(b)),
NativeVerticalNode::Glue(g) => DiagnosticNode::Glue {
value: *g,
name: None,
},
NativeVerticalNode::NamedGlue(g, p) => DiagnosticNode::Glue {
value: *g,
name: Some(*p),
},
NativeVerticalNode::Leaders(leader) => leader_node(leader),
NativeVerticalNode::Kern(k) => DiagnosticNode::Kern {
width: *k,
explicit: true,
},
NativeVerticalNode::ImplicitKern(k) => DiagnosticNode::Kern {
width: *k,
explicit: false,
},
NativeVerticalNode::Penalty(p) => DiagnosticNode::Penalty(*p),
NativeVerticalNode::Rule(r) => DiagnosticNode::Rule(*r),
NativeVerticalNode::Mark(m) => DiagnosticNode::Mark(m.clone()),
NativeVerticalNode::Insertion(n) => insertion_view(n),
NativeVerticalNode::Output(o) => DiagnosticNode::Output(o.clone()),
})
.collect()
}
fn insertion_view(n: &NativeInsertion) -> DiagnosticNode {
DiagnosticNode::Insertion {
class: n.class,
natural_size: n.natural_size,
split_top: n.split_top,
split_depth: n.split_depth,
float_cost: n.float_cost,
nodes: vertical_nodes(&n.nodes),
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ShowBoxReport {
pub context: InputContext,
pub index: u16,
pub breadth: i32,
pub depth: i32,
pub destination: WriteDestination,
pub text: String,
pub span: Span,
}
pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
nodes
.iter()
.map(|n| match n {
TextNode::Language(l) => DiagnosticNode::Language(*l),
TextNode::Glyph {
font,
glyph,
slot,
original,
ligature,
left_boundary,
right_boundary,
..
} => DiagnosticNode::Character {
font: *font,
slot: *slot,
expansion: glyph.math_geometry.as_ref()
.and_then(|geometry| geometry.items.first())
.and_then(|paint| match &paint.item {
crate::math_engine_tex::MathItem::NativeGlyph { font, .. } => Some(font.expansion),
_ => None,
})
.unwrap_or(0),
ligature: ligature.then(|| {
format!(
"{}{original}{}",
if *left_boundary { "|" } else { "" },
if *right_boundary { "|" } else { "" }
)
}),
},
TextNode::OpenType(run) => DiagnosticNode::OpenType {
font: run.font.id, text: run.text.clone(),
glyphs: run.glyphs.iter().map(|glyph| glyph.id).collect(),
},
TextNode::Box(b) if b.native_box.is_some() => {
DiagnosticNode::Box(box_view(b.native_box.as_ref().unwrap()))
}
TextNode::MathChar(b) => {
if let Some(g) = &b.math_geometry
&& g.items.len() == 1
&& let crate::math_engine_tex::MathItem::NativeGlyph { font, slot, .. } =
&g.items[0].item
&& g.items[0].x == 0
&& g.items[0].y == 0
{
DiagnosticNode::Character {
font: font.id,
slot: *slot,
expansion: font.expansion,
ligature: None,
}
} else {
DiagnosticNode::Unsupported(
"native math character diagnostic structure is unavailable".into(),
)
}
}
TextNode::Box(_) => DiagnosticNode::Unsupported(
"compound math diagnostics require retained native math box/list structure".into(),
),
TextNode::Rule(r) => DiagnosticNode::Rule(*r),
TextNode::Mark(m) => DiagnosticNode::Mark(m.clone()),
TextNode::Adjustment(value) => DiagnosticNode::Adjustment {
pre: value.pre,
nodes: vertical_nodes(&value.nodes),
},
TextNode::Insertion(n) => insertion_view(n),
TextNode::Output(o) => DiagnosticNode::Output(o.clone()),
TextNode::Indent(w) => DiagnosticNode::EmptyBox(*w),
TextNode::NamedGlue(g, p) => DiagnosticNode::Glue {
value: *g,
name: Some(*p),
},
TextNode::Glue(g) => DiagnosticNode::Glue {
value: *g,
name: None,
},
TextNode::Leaders(leader) => leader_node(leader),
TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width),
TextNode::AutoKern(width) => DiagnosticNode::AutoKern(*width),
TextNode::MarginKern { width, right, .. } => DiagnosticNode::MarginKern {
width: *width,
right: *right,
},
TextNode::Kern { width, explicit } => DiagnosticNode::Kern {
width: *width,
explicit: *explicit,
},
TextNode::Direction(boundary) => DiagnosticNode::Direction(*boundary),
TextNode::MathBoundary { width, after } => DiagnosticNode::Math {
width: *width,
after: *after,
},
TextNode::Penalty(p) => DiagnosticNode::Penalty(*p),
TextNode::Discretionary {
pre_break,
post_break,
replacement_count,
..
} => DiagnosticNode::Discretionary {
pre: text_nodes(pre_break),
post: text_nodes(post_break),
replacement: *replacement_count,
},
})
.collect()
}
struct Printer<'a> {
state: &'a State,
out: String,
column: usize,
tally: usize,
breadth: usize,
depth: i32,
limit: usize,
overflow: bool,
wrap: bool,
reads: BTreeSet<Dependency>,
}
impl Printer<'_> {
fn raw(&mut self, c: char) {
if self.out.len() + c.len_utf8() > self.limit {
self.overflow = true;
return;
}
self.out.push(c);
if c == '\n' {
self.column = 0;
} else {
self.tally += 1;
self.column += 1;
if self.wrap && self.column == 79 {
self.out.push('\n');
self.column = 0;
}
}
}
fn literal(&mut self, s: &str) {
for c in s.chars() {
if c as u32 == self.state.newlinechar as u32 {
self.raw('\n');
} else {
self.raw(c);
}
}
}
fn ascii(&mut self, c: u8) {
if c as i32 == self.state.newlinechar {
self.raw('\n');
return;
}
let s = match c {
0..=31 => format!("^^{}", char::from(c + 64)),
127 => "^^?".into(),
128..=255 => format!("^^{c:02x}"),
_ => char::from(c).to_string(),
};
for c in s.chars() {
self.raw(c);
}
}
fn command(&mut self, s: &str) {
if let Ok(c) = u8::try_from(self.state.escapechar) {
self.ascii(c);
}
// TeX's tally and line wrapping count the printed ^^ representation,
// not the internal byte character in a control sequence identifier.
for c in s.chars() {
if let Ok(c) = u8::try_from(c as u32) {
self.ascii(c);
} else {
self.raw(c);
}
}
}
fn number(&mut self, n: i64) {
self.literal(&print_scaled(n as i32));
}
fn flex(&mut self, n: i32, order: u8) {
self.number(n as i64);
if order > 0 {
self.literal("fil");
for _ in 1..order {
self.literal("l");
}
}
}
fn glue(&mut self, g: Glue, name: Option<Parameter>) {
self.command("glue");
if let Some(p) = name {
self.literal("(");
self.command(&p.name());
self.literal(")");
}
self.literal(" ");
self.glue_spec(g);
}
fn glue_spec(&mut self, g: Glue) {
self.number(g.width as i64);
if g.stretch.amount != 0 {
self.literal(" plus ");
self.flex(g.stretch.amount, g.stretch.order);
}
if g.shrink.amount != 0 {
self.literal(" minus ");
self.flex(g.shrink.amount, g.shrink.order);
}
}
fn character(&mut self, font: FontId, slot: u8, expansion: i32) -> Result<(), String> {
let (name, expansion) = self.state.fonts.diagnostic_font(font, expansion)?;
self.command(&name);
if expansion != 0 {
self.literal(&format!(" ({expansion:+})"));
}
self.literal(" ");
self.ascii(slot);
Ok(())
}
fn token(&mut self, token: &Token) -> Result<(), String> {
match &token.kind {
TokenKind::Character(c, code) => {
if let Ok(c) = u8::try_from(*c as u32) {
self.ascii(c);
if *code == CatCode::Parameter {
self.ascii(c);
}
} else {
self.raw(*c);
if *code == CatCode::Parameter {
self.raw(*c);
}
}
}
TokenKind::Command(CommandName::Active(c)) => {
if let Ok(c) = u8::try_from(*c as u32) {
self.ascii(c);
} else {
self.raw(*c);
}
}
TokenKind::Command(CommandName::FrozenRelax) => {
self.command("relax");
self.literal(" ");
}
TokenKind::Command(CommandName::Font(font)) => {
let name = self.state.fonts.font(*font)?.identifier_text();
self.command(&name);
self.literal(" ");
}
TokenKind::Command(CommandName::Control(name)) => {
if name.is_empty() {
self.command("csname");
self.command("endcsname");
self.literal(" ");
} else {
self.command(name);
if name.chars().count() == 1 {
self.reads
.insert(Dependency::CatCode(name.chars().next().unwrap()));
}
if name.chars().count() > 1
|| name
.chars()
.next()
.is_some_and(|c| self.state.catcode(c) == CatCode::Letter)
{
self.literal(" ");
}
}
}
}
Ok(())
}
fn line(&mut self, prefix: &str) {
self.raw('\n');
self.literal(prefix);
}
fn mark_(&mut self, m: &NativeMark) -> Result<(), String> {
if m.class == 0 {
self.command("mark");
} else {
self.command("marks");
self.literal(&m.class.to_string());
}
self.tokens(&m.tokens)
}
fn tokens(&mut self, tokens: &[Token]) -> Result<(), String> {
self.literal("{");
self.tally = 0;
for t in tokens {
if self.tally >= 69 {
self.command("ETC.");
break;
}
self.token(t)?;
}
self.literal("}");
Ok(())
}
fn nodes(&mut self, nodes: &[DiagnosticNode], prefix: &str) -> Result<(), String> {
if prefix.len() as i32 > self.depth {
if !nodes.is_empty() {
self.literal(" []");
}
return Ok(());
}
for (i, n) in nodes.iter().enumerate() {
self.line(prefix);
if i >= self.breadth {
self.literal("etc.");
break;
}
match n {
DiagnosticNode::Character {
font,
slot,
expansion,
ligature,
} => {
self.character(*font, *slot, *expansion)?;
if let Some(s) = ligature {
self.literal(" (ligature ");
for c in s.chars() {
self.ascii(c as u8);
}
self.literal(")");
}
}
DiagnosticNode::OpenType { font, text, .. } => {
let name = self.state.fonts.font(*font)?.identifier_text();
self.command(&name);
self.literal(" ");
self.literal(text);
}
DiagnosticNode::Box(b) => self.box_(b, prefix)?,
DiagnosticNode::EmptyBox(w) => {
self.command("hbox");
self.literal("(0.0+0.0)x");
self.number(*w as i64);
}
DiagnosticNode::Glue { value, name } => self.glue(*value, *name),
DiagnosticNode::Leaders {
value,
mode,
pattern,
} => {
self.command(match mode {
LeaderMode::Aligned => "leaders",
LeaderMode::Centered => "cleaders",
LeaderMode::Expanded => "xleaders",
});
self.literal(" ");
self.glue_spec(*value);
self.nodes(
std::slice::from_ref(pattern.as_ref()),
&format!("{prefix}."),
)?;
}
DiagnosticNode::MarginKern { width, right } => {
self.command("kern");
self.number(i64::from(*width));
self.literal(if *right { " (right margin)" } else { " (left margin)" });
}
DiagnosticNode::AccentKern(width) => {
self.command("kern");
self.literal(" ");
self.number(i64::from(*width));
self.literal(" (for accent)");
}
DiagnosticNode::AutoKern(width) => {
self.command("kern");
self.literal(" ");
self.number(i64::from(*width));
self.literal(r" (for \pdfprependkern/\pdfappendkern)");
}
DiagnosticNode::Kern { width, explicit } => {
self.command("kern");
if *explicit {
self.literal(" ");
}
self.number(*width as i64);
}
DiagnosticNode::Direction(boundary) => self.command(boundary.name()),
DiagnosticNode::Math { width, after } => {
self.command(if *after { "mathoff" } else { "mathon" });
if *width != 0 {
self.literal(", surrounded ");
self.number(*width as i64);
}
}
DiagnosticNode::Penalty(p) => {
self.command("penalty");
self.literal(&format!(" {p}"));
}
DiagnosticNode::Mark(m) => {
self.mark_(m)?;
}
DiagnosticNode::Adjustment { pre, nodes } => {
self.command("vadjust");
if *pre {
self.literal(" pre ");
}
self.nodes(nodes, &format!("{prefix}."))?;
}
DiagnosticNode::Insertion {
class,
natural_size,
split_top,
split_depth,
float_cost,
nodes,
} => {
self.command("insert");
self.literal(&format!("{class}, natural size "));
self.number(*natural_size);
self.literal("; split(");
self.glue_spec(*split_top);
self.literal(",");
self.number(i64::from(*split_depth));
self.literal(&format!("); float cost {float_cost}"));
self.nodes(nodes, &format!("{prefix}."))?;
}
DiagnosticNode::Output(o) => match &o.operation {
OutputOperation::Open { stream, name, .. } => {
self.command("openout");
self.literal(&format!("{stream}="));
let quoted = name.contains(' ');
if quoted {
self.literal("\"");
}
for c in name.chars() {
if let Ok(c) = u8::try_from(c as u32) {
self.ascii(c)
} else {
self.raw(c)
}
}
if quoted {
self.literal("\"");
}
}
OutputOperation::Close { stream } => {
self.command("closeout");
self.literal(&stream.to_string());
}
OutputOperation::Write { stream, tokens } => {
self.command("write");
self.literal(&match *stream {
16 => "*".into(),
17 => "-".into(),
n => n.to_string(),
});
self.tokens(tokens)?;
}
OutputOperation::PdfColor { stack, action } => {
use crate::pdf_device::PdfColorStackAction::*;
self.command("pdfcolorstack");
let (name, program) = match action {
Set(program) => ("set", Some(program)),
Push(program) => ("push", Some(program)),
Current => ("current", None),
Pop => ("pop", None),
};
self.literal(&format!(" {stack} {name}"));
if let Some(program) = program {
self.literal(&format!(" {{{}}}", program.literal()));
}
}
OutputOperation::PdfObject(number) => {
self.command("pdfrefobj");
self.literal(&format!(" {number}"));
}
OutputOperation::PdfImage { image, .. } => {
if image.xdv.is_some() {
self.command(if image.image.raster_frame().is_some() {
"XeTeXpicfile"
} else {
"XeTeXpdffile"
});
self.literal(&format!(
" \"{}\"",
image.image.version.path.display()
));
} else {
self.command("pdfrefximage");
self.literal(&format!(" {}", image.id));
}
}
OutputOperation::PdfSave => self.command("pdfsave"),
OutputOperation::PdfRestore => self.command("pdfrestore"),
OutputOperation::PdfTextSpace(operation) => {
self.command(operation.name());
}
OutputOperation::PdfLink(node) => {
use crate::pdf_device::links::LinkNode;
self.command(match node {
LinkNode::Start(_) => "pdfstartlink",
LinkNode::End => "pdfendlink",
LinkNode::Running(false) => "pdfrunninglinkoff",
LinkNode::Running(true) => "pdfrunninglinkon",
LinkNode::Destination { .. } => "pdfdest",
});
if let LinkNode::Destination { structure: Some(object), .. } = node {
self.literal(&format!(" struct{object}"));
}
}
OutputOperation::PdfLiteral { mode, shipout, tokens } => {
use crate::pdf_device::PdfLiteralMode;
self.command("pdfliteral");
if *shipout {
self.literal(" shipout");
}
match mode {
PdfLiteralMode::Origin => {}
PdfLiteralMode::Page => self.literal(" page"),
PdfLiteralMode::Direct => self.literal(" direct"),
PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => {}
}
self.tokens(tokens)?;
}
OutputOperation::PdfSavePosition => self.command("pdfsavepos"),
OutputOperation::Special { shipout, tokens, .. } => {
self.command("special");
if *shipout {
self.literal(" shipout");
}
self.tokens(tokens)?;
}
OutputOperation::PdfSetMatrix(tokens) => {
self.command("pdfsetmatrix");
self.tokens(tokens)?;
}
},
DiagnosticNode::Language(l) => {
self.command("setlanguage");
self.literal(&format!(
"{} (hyphenmin {},{})",
l.language, l.left_min, l.right_min
));
}
DiagnosticNode::Discretionary {
pre,
post,
replacement,
} => {
self.command("discretionary");
if *replacement > 0 {
self.literal(&format!(" replacing {replacement}"));
}
self.nodes(pre, &format!("{prefix}."))?;
self.nodes(post, &format!("{prefix}|"))?;
}
DiagnosticNode::Rule(r) => {
self.command("rule");
self.literal("(");
if let Some(n) = r.height {
self.number(i64::from(n));
} else {
self.literal("*");
}
self.literal("+");
if let Some(n) = r.depth {
self.number(i64::from(n));
} else {
self.literal("*");
}
self.literal(")x");
if let Some(n) = r.width {
self.number(i64::from(n));
} else {
self.literal("*");
}
}
DiagnosticNode::Unsupported(reason) => return Err(reason.clone()),
}
}
Ok(())
}
fn box_(&mut self, b: &DiagnosticBox, prefix: &str) -> Result<(), String> {
self.command(if b.kind.is_unset() {
"unsetbox"
} else if b.kind == BoxKind::Horizontal {
"hbox"
} else {
"vbox"
});
self.literal("(");
self.number(b.height);
self.literal("+");
self.number(b.depth);
self.literal(")x");
self.number(b.width);
if let BoxKind::Unset {
span,
stretch,
shrink,
} = b.kind
{
if span != 0 {
self.literal(&format!(" ({} columns)", u16::from(span) + 1));
}
for (name, flex) in [("stretch", stretch), ("shrink", shrink)] {
if flex.amount != 0 {
self.literal(&format!(", {name} "));
self.flex(flex.amount, flex.order);
}
}
let child = format!("{prefix}.");
return self.nodes(&b.nodes, &child);
}
let set = b.setting;
if set.sign != 0 && set.numerator != 0 && set.denominator != 0 {
self.literal(", glue set ");
if set.sign < 0 {
self.literal("- ");
}
let g = set.numerator as f64 / set.denominator as f64;
if g.abs() > 20000.0 {
self.literal(if g > 0.0 { ">" } else { "< -" });
self.flex(20000 * 65536, set.order);
} else {
self.flex((g * 65536.0).round() as i32, set.order);
}
}
if b.shift != 0 {
self.literal(", shifted ");
self.number(b.shift);
}
if b.display {
self.literal(", display");
}
let child = format!("{prefix}.");
self.nodes(&b.nodes, &child)?;
Ok(())
}
}
pub(super) fn show_box(
state: &State,
index: u16,
breadth: i32,
depth: i32,
limit: usize,
wrap: bool,
) -> Result<(String, BTreeSet<Dependency>), String> {
let mut p = 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(),
};
p.literal(&format!("> \\box{index}="));
if let Some(b) = state.box_register(index) {
if depth < 0 {
p.literal(" []");
} else {
p.line("");
p.box_(&box_view(b), "")?;
}
} else {
p.literal("void");
}
p.raw('\n');
p.raw('\n');
if p.overflow {
return Err("native box diagnostic output capacity exceeded".into());
}
Ok((p.out, p.reads))
}
pub(super) fn shipout_box(
state: &State,
b: &NativeBox,
breadth: i32,
depth: i32,
limit: usize,
) -> Result<(String, BTreeSet<Dependency>), String> {
let mut p = Printer {
state,
out: String::new(),
column: 0,
tally: 0,
breadth: if breadth <= 0 { 5 } else { breadth as usize },
depth,
limit,
overflow: false,
wrap: true,
reads: BTreeSet::new(),
};
if depth < 0 {
p.literal(" []");
} else {
p.box_(&box_view(b), "")?;
}
p.raw('\n');
p.raw('\n');
if p.overflow {
return Err("native box diagnostic output capacity exceeded".into());
}
Ok((p.out, p.reads))
}
pub(super) fn show_nodes(
state: &State,
nodes: &[DiagnosticNode],
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(),
};
printer.nodes(nodes, "")?;
if printer.overflow {
return Err("native list diagnostic output capacity exceeded".into());
}
Ok((printer.out, printer.reads))
}