mod activity; use super::*; impl Executor { pub(super) fn trace_conditional( &mut self, command: Primitive, skipping: bool, files: &mut impl SourceProvider, ) -> Result<(), Error> { if self.state.profile() != Profile::EtexBootstrap || self.read_parameter(Parameter::Tracingifs).width() <= 0 { if !skipping && self.read_parameter(Parameter::Tracingcommands).width() > 1 { let inverted = command.conditional() && self.conditionals.last().is_some_and(|frame| frame.inverted); let command = self.trace_primitive_name(command, inverted); self.emit_command_trace(&command, true, files)?; } return Ok(()); } let frame = self.conditionals.last().expect("active condition"); let (condition, inverted, origin) = (frame.primitive, frame.inverted, frame.origin); let level = self.conditionals.len(); let mut record = self.command_trace_prefix(); self.reads.insert(Dependency::EscapeChar); let escape = u8::try_from(self.state.escapechar) .ok() .map(|c| char::from(c).to_string()) .unwrap_or_default(); let condition_name = format!("{condition:?}").to_ascii_lowercase(); let condition_text = if inverted { format!("{escape}unless{escape}{condition_name}") } else { format!("{escape}{condition_name}") }; if command.conditional() { record.push_str(&condition_text); record.push_str(": "); } else { let branch = format!("{command:?}").to_ascii_lowercase(); record.push_str(&format!("{escape}{branch}: {condition_text} ")); } record.push_str(&format!("(level {level})")); if let Some((source, line)) = origin { self.reads.insert(Dependency::InputPosition(source)); if line != 0 { record.push_str(&format!(" entered on line {line}")); } } let (destination, text) = self.emit_trace_record(&record, files)?; self.events.push(Event::ConditionalTrace { command, condition, inverted, level, origin, destination, text, }); Ok(()) } fn command_trace_prefix(&mut self) -> String { let mode = if self.writing { "no mode" } else if !self.math.is_empty() { if self.display.is_some() && self.math.len() == 1 { "display math mode" } else { "math mode" } } else if self.paragraph.is_some() { if self.restricted() { "restricted horizontal mode" } else { "horizontal mode" } } else if self.outer_vertical() { "vertical mode" } else { "internal vertical mode" }; let mut record = String::new(); if self.command_trace_mode != Some(mode) { self.command_trace_mode = Some(mode); record.push_str(mode); record.push_str(": "); } record } fn trace_primitive_name(&mut self, primitive: Primitive, inverted: bool) -> String { let name = format!("{primitive:?}").to_ascii_lowercase(); let kind = TokenKind::Command(CommandName::Control(name)); let command = self.string_token(&kind); if inverted { let unless = TokenKind::Command(CommandName::Control("unless".into())); return format!("{}{command}", self.string_token(&unless)); } command } pub(super) fn trace_command( &mut self, token: &Token, files: &mut impl SourceProvider, ) -> Result<(), Error> { let description = match self.meaning(token) { Meaning::Character(TokenKind::Character(c, CatCode::Space)) => { format!("blank space {c}") } Meaning::Primitive(Primitive::DiscretionaryHyphen) => "discretionary hyphen".into(), _ => self.meaning_string(token)?, }; self.emit_command_trace(&description, true, files) } pub(super) fn trace_frozen_command( &mut self, files: &mut impl SourceProvider, ) -> Result<(), Error> { let command = self.trace_primitive_name(Primitive::Relax, false); self.emit_command_trace(&command, true, files) } pub(super) fn trace_command_result( &mut self, result: &str, files: &mut impl SourceProvider, ) -> Result<(), Error> { self.emit_command_trace(result, false, files) } fn emit_command_trace( &mut self, command: &str, show_mode: bool, files: &mut impl SourceProvider, ) -> Result<(), Error> { let mut record = if show_mode { self.command_trace_prefix() } else { String::new() }; record.push_str(command); let (destination, text) = self.emit_trace_record(&record, files)?; self.events.push(Event::CommandTrace { destination, text }); Ok(()) } fn emit_trace_record( &mut self, record: &str, files: &mut impl SourceProvider, ) -> Result<(WriteDestination, String), Error> { let record = format!("{{{record}}}"); self.reads.insert(Dependency::NewLineChar); let mut text = self.print_show_parts(&[&record])?; if !text.ends_with('\n') { text.push('\n'); } 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"); } let destination = if self.read_parameter(Parameter::Tracingonline).width() > 0 { WriteDestination::TerminalAndLog } else { WriteDestination::Log }; files .observe_diagnostic(destination, &text) .map_err(|e| self.error(e, self.current))?; Ok((destination, text)) } pub(super) fn reserve_diagnostic( &mut self, output: usize, context: &InputContext, ) -> Result<(), Error> { let snapshot = context .frames .iter() .map(|f| { f.label.len() + f.before.len() + f.second.len() + match &f.kind { ContextKind::Macro(CommandName::Control(name)) => name.len(), ContextKind::Source { name, .. } => name.len(), _ => 0, } }) .sum::(); self.diagnostic_bytes = self .diagnostic_bytes .saturating_add(output) .saturating_add(snapshot); if self.diagnostic_bytes > self.limits.tokens { return self.fail("native diagnostic output limit exceeded"); } Ok(()) } pub(super) fn diagnostic_context(&mut self) -> InputContext { self.read_parameter(Parameter::Errorcontextlines); self.reads.insert(Dependency::EscapeChar); self.reads.insert(Dependency::NewLineChar); let context = self.input_context(); self.reads.extend(context.reads.iter().cloned()); context } pub(super) fn print_show_parts(&self, parts: &[&str]) -> Result { self.format_show_parts(parts, true) } fn format_show_parts(&self, parts: &[&str], wrap: bool) -> Result { let mut out = String::new(); let mut column = 0; let mut raw = |c: char| -> Result<(), Error> { if out.len() + c.len_utf8() + 1 > self.limits.tokens { return self.fail("native diagnostic output limit exceeded"); } out.push(c); if c == '\n' { column = 0; } else { column += 1; if wrap && column == 79 { out.push('\n'); column = 0; } } Ok(()) }; for (i, text) in parts.iter().enumerate() { if i > 0 { raw('\n')?; } for c in text.chars() { if c as i32 == self.state.newlinechar { raw('\n')?; } else { for c in super::super::context::encoded_character(c).chars() { raw(c)?; } } } } Ok(out) } fn open_show_stream(&mut self) -> Option { 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 (mut head, mut tail) = if the { let text = match self.the_value(files)? { TheValue::Text(text) => text, TheValue::Tokens(tokens) => { let mut text = String::new(); for t in tokens { if let TokenKind::Character(c, CatCode::Parameter) = t.kind { text.push(c); } let piece = self.message_token(&t); self.append_diagnostic(&mut text, &piece)?; } text } }; (format!("> {text}"), None) } else { let t = self.required_raw(files)?.token; let macro_meaning = matches!(self.meaning(&t), Meaning::Macro(_)); let name = if matches!(t.kind, TokenKind::Command(_)) { format!("{}=", self.string_token(&t.kind)) } else { String::new() }; let meaning = self.meaning_string(&t)?; if macro_meaning { let split = meaning.find("macro:").unwrap() + "macro:".len(); ( format!("> {name}{}", &meaning[..split]), Some(meaning[split..].to_owned()), ) } else { (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"); } let context = self.diagnostic_context(); let separator = if text.ends_with('\n') && !context .frames .first() .is_some_and(|f| matches!(f.kind, ContextKind::Macro(_))) { "" } else { "\n" }; let output = format!("{text}{separator}{}", context.text); let log_output = format!("{output}\n"); self.reserve_diagnostic(log_output.len(), &context)?; files .observe_diagnostic_pair(&log_output, &output) .map_err(|e| self.error(e, span))?; self.events.push(Event::Show(ShowReport { output, log_output, the, text, context, span, })); Ok(()) } pub(super) fn show_box(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> { 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); self.reads.insert(Dependency::NewLineChar); let breadth = self.read_parameter(Parameter::Showboxbreadth).width(); let depth = self.read_parameter(Parameter::Showboxdepth).width(); let online = self.read_parameter(Parameter::Tracingonline).width(); let destination = if online > 0 { WriteDestination::TerminalAndLog } else { WriteDestination::Log }; let (text, reads) = super::super::diagnostics::show_box( &self.state, index, 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(), &context, )?; self.events.push(Event::ShowBox(ShowBoxReport { context: context.clone(), index, breadth, depth, destination, text: text.clone(), span, })); files .observe_diagnostic(destination, &text) .map_err(|e| self.error(e, span))?; let log = format!("{}\n", self.external_print("! OK.")); let terminal = if online > 0 { log.clone() } else { format!( "{}\n", self.external_print("! OK (see the transcript file).") ) }; let log = format!("{log}{}\n", context.text); let terminal = format!("{terminal}{}", context.text); files .observe_diagnostic_pair(&log, &terminal) .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::>(), wrap)? } Primitive::Showifs => { let lines = self.activity_conditionals(); self.format_show_parts(&lines.iter().map(String::as_str).collect::>(), 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 { 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 { 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 } } impl Executor { pub(super) fn trace_macro_call( &mut self, definition: &Macro, call: &Token, files: &mut impl SourceProvider, ) -> Result<(), Error> { let command = self.message_token(call); let body = self.macro_token_text(definition, call.span)?; self.emit_macro_trace(&format!("{command}{body}"), true, files) } pub(super) fn trace_macro_argument( &mut self, definition: &Macro, index: usize, argument: &[Token], files: &mut impl SourceProvider, ) -> Result<(), Error> { let mut body = format!("{}{}<-", definition.parameter_chars[index], index + 1); let mut tally = 0; for token in argument { if tally >= 1000 { body.push_str( &self.string_token(&TokenKind::Command(CommandName::Control("ETC.".into()))), ); break; } let piece = self.message_token(token); tally += piece.chars().count(); if let TokenKind::Character(c, CatCode::Parameter) = token.kind { body.push(c); tally += 1; } body.push_str(&piece); } self.emit_macro_trace(&body, false, files) } fn emit_macro_trace( &mut self, record: &str, leading_newline: bool, files: &mut impl SourceProvider, ) -> Result<(), Error> { self.reads.insert(Dependency::NewLineChar); let mut text = self.print_show_parts(&[record])?; if leading_newline { text.insert(0, '\n'); } if !text.ends_with('\n') { text.push('\n'); } 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"); } let destination = if self.read_parameter(Parameter::Tracingonline).width() > 0 { WriteDestination::TerminalAndLog } else { WriteDestination::Log }; files .observe_raw_diagnostic(destination, &text) .map_err(|e| self.error(e, self.current))?; self.events.push(Event::MacroTrace { destination, text }); Ok(()) } } impl Executor { pub(super) fn trace_shipout( &mut self, b: &NativeBox, files: &mut impl SourceProvider, ) -> Result<(), Error> { if self.read_parameter(Parameter::Tracingoutput).width() <= 0 { return Ok(()); } self.reads.insert(Dependency::NewLineChar); self.reads.insert(Dependency::EscapeChar); self.reads.insert(Dependency::FontResources); let breadth = self.read_parameter(Parameter::Showboxbreadth).width(); let depth = self.read_parameter(Parameter::Showboxdepth).width(); let mut counters = [0; 10]; for (index, count) in counters.iter_mut().enumerate() { self.reads.insert(Dependency::Count(index as u16)); *count = self.state.count(index as u16); } let last = counters.iter().rposition(|count| *count != 0).unwrap_or(0); let label = counters[..=last] .iter() .map(i32::to_string) .collect::>() .join("."); let (tree, reads) = super::super::diagnostics::shipout_box( &self.state, b, breadth, depth, self.limits.tokens, ) .map_err(|error| self.error(error, self.current))?; self.reads.extend(reads); let heading = format!("\nCompleted box being shipped out [{label}]"); let log = if tree.starts_with(" []") { format!("{heading}{tree}") } else { format!("{heading}\n{tree}") }; let terminal = if self.read_parameter(Parameter::Tracingonline).width() > 0 { log.clone() } else { format!("{heading}\n") }; self.diagnostic_bytes = self .diagnostic_bytes .saturating_add(log.len()) .saturating_add(terminal.len()); if self.diagnostic_bytes > self.limits.tokens { return self.fail("native diagnostic output limit exceeded"); } files .observe_diagnostic_pair(&log, &terminal) .map_err(|error| self.error(error, self.current))?; self.events.push(Event::ShipoutTrace { log, terminal }); Ok(()) } }