Redirect native TeX diagnostics to real output streams

This commit is contained in:
gloamxun committed 2026-11-21 05:38:05 +08:00
1 parent 6ebcb75794
commit 6675ab639a
11 files changed
+540 -21

No files matched your search

@@ -12,16 +12,16 @@ pub(super) enum Destination {
}
#[derive(Clone)]
pub(super) struct BoxFrame {
kind: BoxKind,
spec: PackSpec,
pub(super) kind: BoxKind,
pub(super) spec: PackSpec,
group: GroupKind,
depth: usize,
destination: Destination,
paragraph: Option<super::super::paragraph::Builder>,
vertical: VerticalBuilder,
span: Span,
pub(super) depth: usize,
pub(super) destination: Destination,
pub(super) paragraph: Option<super::super::paragraph::Builder>,
pub(super) vertical: VerticalBuilder,
pub(super) span: Span,
discretionary: Option<DiscretionaryFrame>,
math: Vec<super::super::math::MathBuilder>,
pub(super) math: Vec<super::super::math::MathBuilder>,
// An inner $...$ belongs to this box, even inside an outer display.
display: Option<super::display::DisplayFrame>,
}
@@ -1,3 +1,4 @@
use super::super::diagnostics::{DiagnosticNode, show_nodes, text_nodes, vertical_nodes};
use super::*;
impl Executor {
pub(super) fn trace_conditional(
@@ -211,6 +212,9 @@ impl Executor {
context
}
pub(super) fn print_show_parts(&self, parts: &[&str]) -> Result<String, Error> {
self.format_show_parts(parts, true)
}
fn format_show_parts(&self, parts: &[&str], wrap: bool) -> Result<String, Error> {
let mut out = String::new();
let mut column = 0;
let mut raw = |c: char| -> Result<(), Error> {
@@ -222,7 +226,7 @@ impl Executor {
column = 0;
} else {
column += 1;
if column == 79 {
if wrap && column == 79 {
out.push('\n');
column = 0;
}
@@ -245,13 +249,44 @@ impl Executor {
}
Ok(out)
}
fn open_show_stream(&mut self) -> Option<u8> {
let stream = self.read_parameter(Parameter::Showstream).width();
if (0..16).contains(&stream) {
let stream = stream as u8;
self.reads.insert(Dependency::OutputStream(stream));
if self.io.outputs.contains(&stream) {
return Some(stream);
}
}
None
}
fn write_show(
&mut self,
files: &mut impl SourceProvider,
stream: u8,
text: String,
span: Span,
) -> Result<(), Error> {
self.diagnostic_bytes = self.diagnostic_bytes.saturating_add(text.len());
if self.diagnostic_bytes > self.limits.tokens {
return self.fail("native diagnostic output limit exceeded");
}
files
.write_out(stream, &text)
.map_err(|error| self.error(error, span))?;
self.events
.push(Event::ShowRedirected { stream, text, span });
Ok(())
}
pub(super) fn show(
&mut self,
the: bool,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let text = if the {
let (mut head, mut tail) = if the {
let text = match self.the_value(files)? {
TheValue::Text(text) => text,
TheValue::Tokens(tokens) => {
@@ -266,7 +301,7 @@ impl Executor {
text
}
};
self.print_show_parts(&[&format!("> {text}.")])?
(format!("> {text}"), None)
} else {
let t = self.required_raw(files)?.token;
let macro_meaning = matches!(self.meaning(&t), Meaning::Macro(_));
@@ -278,14 +313,26 @@ impl Executor {
let meaning = self.meaning_string(&t)?;
if macro_meaning {
let split = meaning.find("macro:").unwrap() + "macro:".len();
self.print_show_parts(&[
&format!("> {name}{}", &meaning[..split]),
&format!("{}.", &meaning[split..]),
])?
(
format!("> {name}{}", &meaning[..split]),
Some(meaning[split..].to_owned()),
)
} else {
self.print_show_parts(&[&format!("> {name}{meaning}.")])?
(format!("> {name}{meaning}"), None)
}
};
let stream = self.open_show_stream();
if stream.is_none() {
tail.as_mut().unwrap_or(&mut head).push('.');
}
self.reads.insert(Dependency::NewLineChar);
let text = match &tail {
Some(tail) => self.format_show_parts(&[&head, tail], stream.is_none())?,
None => self.format_show_parts(&[&head], stream.is_none())?,
};
if let Some(stream) = stream {
return self.write_show(files, stream, format!("\n{text}\n"), span);
}
if text.len() > self.limits.tokens {
return self.fail("native diagnostic output limit exceeded");
}
@@ -321,6 +368,7 @@ impl Executor {
let span = self.current;
self.finish_text(true)?;
let index = self.register_index(files)?;
let stream = self.open_show_stream();
self.reads.insert(Dependency::BoxRegister(index));
self.reads.insert(Dependency::FontResources);
self.reads.insert(Dependency::EscapeChar);
@@ -339,9 +387,18 @@ impl Executor {
breadth,
depth,
self.limits.tokens,
stream.is_none(),
)
.map_err(|e| self.error(e, span))?;
self.reads.extend(reads);
if let Some(stream) = stream {
let extra = if self.state.box_register(index).is_some() {
"\n"
} else {
""
};
return self.write_show(files, stream, format!("\n{text}{extra}\n! OK\n"), span);
}
let context = self.diagnostic_context();
self.reserve_diagnostic(
text.len() + context.text.len() + 2 * "! OK (see the transcript file).\n".len(),
@@ -375,6 +432,373 @@ impl Executor {
.map_err(|e| self.error(e, span))?;
Ok(())
}
pub(super) fn show_activity(
&mut self,
command: Primitive,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let span = self.current;
if command == Primitive::Showlists {
self.finish_text(true)?;
}
let stream = self.open_show_stream();
let wrap = stream.is_none();
let body = match command {
Primitive::Showlists => {
let breadth = self.read_parameter(Parameter::Showboxbreadth).width();
let depth = self.read_parameter(Parameter::Showboxdepth).width();
let (body, dependencies) = self
.activity_lists(breadth, depth, wrap)
.map_err(|message| self.error(message, span))?;
self.reads.extend(dependencies);
body
}
Primitive::Showgroups => {
let lines = self.activity_groups();
self.format_show_parts(&lines.iter().map(String::as_str).collect::<Vec<_>>(), wrap)?
}
Primitive::Showifs => {
let lines = self.activity_conditionals();
self.format_show_parts(&lines.iter().map(String::as_str).collect::<Vec<_>>(), wrap)?
}
_ => unreachable!(),
};
if let Some(stream) = stream {
return self.write_show(files, stream, format!("\n\n\n{body}\n\n\n! OK\n"), span);
}
let context = self.diagnostic_context();
let online = self.read_parameter(Parameter::Tracingonline).width() > 0;
let destination = if online {
WriteDestination::TerminalAndLog
} else {
WriteDestination::Log
};
let text = format!("\n{body}\n\n");
let log_output = format!("{}\n{}\n", self.external_print("! OK."), context.text);
let ok = if online {
"! OK."
} else {
"! OK (see the transcript file)."
};
let output = format!("{}\n{}", self.external_print(ok), context.text);
self.reserve_diagnostic(text.len() + log_output.len(), &context)?;
files
.observe_diagnostic(destination, &text)
.map_err(|error| self.error(error, span))?;
files
.observe_diagnostic_pair(&log_output, &output)
.map_err(|error| self.error(error, span))?;
self.events.push(Event::Show(ShowReport {
output,
log_output,
the: false,
text,
context,
span,
}));
Ok(())
}
fn activity_conditionals(&mut self) -> Vec<String> {
self.reads.insert(Dependency::ConditionalState);
if self.conditionals.is_empty() {
return vec!["### no active conditionals".into()];
}
let frames = self.conditionals.clone();
frames
.iter()
.enumerate()
.rev()
.map(|(index, frame)| {
let mut description = self.trace_primitive_name(frame.primitive, frame.inverted);
if frame.limit == ConditionalLimit::Fi {
description.push_str(&self.trace_primitive_name(Primitive::Else, false));
}
if let Some((source, line)) = frame.origin.filter(|(_, line)| *line != 0) {
self.reads.insert(Dependency::InputPosition(source));
description.push_str(&format!(" entered on line {line}"));
}
format!("### level {}: {description}", index + 1)
})
.collect()
}
fn activity_groups(&mut self) -> Vec<String> {
use super::super::boxes::PackSpec;
self.reads.insert(Dependency::GroupState);
self.reads.insert(Dependency::EscapeChar);
let escape = u8::try_from(self.state.escapechar)
.ok()
.map(|value| char::from(value).to_string())
.unwrap_or_default();
let mut lines = Vec::new();
for (index, (kind, origin)) in self.state.open_groups().enumerate().rev() {
let level = index + 1;
let mut text = format!(
"### {} group (level {level})",
super::scheduling::group_name(kind)
);
if let Some((source, line)) = origin.filter(|(_, line)| *line != 0) {
self.reads.insert(Dependency::InputPosition(source));
text.push_str(&format!(" entered at line {line}"));
}
let detail = if let Some(frame) =
self.box_frames.iter().find(|frame| frame.depth == level)
{
let name = match frame.kind {
BoxKind::Horizontal => "hbox",
BoxKind::Vtop => "vtop",
_ if kind == GroupKind::Vcenter => "vcenter",
_ => "vbox",
};
let placement = match frame.destination {
boxes::Destination::Append => String::new(),
boxes::Destination::Shipout => format!("{escape}shipout"),
boxes::Destination::Register(number, global) => {
let prefix = if global {
format!("{escape}global")
} else {
String::new()
};
format!("{prefix}{escape}setbox{number}=")
}
boxes::Destination::Shift(amount) => {
let command = match (frame.paragraph.is_some(), amount.is_negative()) {
(false, false) => "moveright",
(false, true) => "moveleft",
(true, false) => "lower",
(true, true) => "raise",
};
format!(
"{escape}{command}{}pt",
registers::print_scaled_wide(i64::from(amount).abs())
)
}
boxes::Destination::Leaders(mode) => {
let command = match mode {
LeaderMode::Aligned => "leaders",
LeaderMode::Centered => "cleaders",
LeaderMode::Expanded => "xleaders",
};
format!("{escape}{command}")
}
boxes::Destination::Adjustment { .. } => format!("{escape}vadjust"),
boxes::Destination::Insertion { class } => format!("{escape}insert{class}"),
};
let size = match frame.spec {
PackSpec::To(value) if value != 0 => {
format!(" to{}pt", registers::print_scaled(value))
}
PackSpec::Spread(value) if value != 0 => {
format!(" spread{}pt", registers::print_scaled(value))
}
_ => String::new(),
};
if matches!(
frame.destination,
boxes::Destination::Adjustment { .. } | boxes::Destination::Insertion { .. }
) {
format!("{placement}{{")
} else {
format!("{placement}{escape}{name}{size}{{")
}
} else {
match kind {
GroupKind::Simple | GroupKind::MathGroup => "{".into(),
GroupKind::SemiSimple => format!("{escape}begingroup"),
GroupKind::Output => format!("{escape}output"),
GroupKind::NoAlign => format!("{escape}noalign{{"),
GroupKind::MathLeft => format!("{escape}left"),
GroupKind::MathShift if self.display.is_some() => "$$".into(),
GroupKind::MathShift => "$".into(),
GroupKind::MathChoice => format!("{escape}mathchoice{{"),
GroupKind::Discretionary => format!("{escape}discretionary{{"),
GroupKind::Align => "align entry".into(),
_ => String::new(),
}
};
if !detail.is_empty() {
text.push_str(&format!(" ({detail})"));
}
lines.push(text);
}
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 {
@@ -211,6 +211,7 @@ impl Executor {
1,
0,
self.limits.tokens,
true,
)
.map_err(|error| self.error(error, self.current))?;
self.reads.extend(reads);