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

1188 lines
42 KiB
Rust

//! Route-D-owned TeX execution. No semantic renderer, source rewriting or VM
//! adapter participates in this path. Unsupported commands are errors.
mod boxes;
mod byte_translation;
pub use byte_translation::ByteTranslation;
mod cancellation;
mod case;
mod context;
mod device;
mod dependency_reads;
use dependency_reads::DependencyReads;
mod diagnostics;
mod direction;
mod dvi;
pub use direction::DirectionBoundary;
mod engine;
pub use engine::pdf_match::{RegexOutcome, RegexRequest, match_pdf_regex};
mod font_catalog;
mod fonts;
mod format_image;
pub use format_image::FormatImage;
mod hooks;
mod hyphenation;
mod input_profile;
mod xe_encoding;
pub use xe_encoding::XeLineFraming;
mod insertions;
mod job;
mod ligature;
mod marks;
mod math;
mod math_accent;
mod math_code;
mod math_delimiter;
mod math_fraction;
mod math_op;
mod math_ord;
mod math_rule;
mod math_scripts;
mod mouth;
mod page_builder;
mod paragraph;
mod paragraph_trace;
mod parameters;
mod random;
mod reconstitute;
mod registers;
mod rule;
mod session;
mod source_relocation;
mod source_relocation_events;
mod state;
mod statistics;
mod vertical_break;
pub use statistics::{
HostResourceUsage, MaterialUsage, ResourceUsage, StackUsage, StateUsage, StatisticsPhase,
StatisticsReport,
StepOffset,
};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
pub use boxes::{
BoxContent, BoxKind, GlueSetting, LeaderGlue, LeaderMode, LeaderPattern, NativeBox,
NativeVerticalNode,
};
pub use cancellation::Cancellation;
pub use case::CaseCode;
pub use context::{ContextFrame, ContextKind, InputContext};
pub use device::{NativeShipout, ShipoutDevice, ShipoutSpecial};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{
CheckpointCloneTimings, CheckpointDecision, CheckpointSource, ClosedSourceChange,
EntryCheckpoint, Executor, Limits, RelocatedShipoutSuffix, RetainedStateFingerprint, SuffixKernelTimings,
SuffixStateProofTimings,
};
pub use font_catalog::{
FontCatalog, FontCharacter, FontId, FontInstance, FontLimits, FontResource,
};
pub use fonts::{FontIntegers, MissingGlyph};
pub use hooks::TokenParameter;
pub use hyphenation::HyphenationLanguage;
pub use input_profile::InputProfile;
pub use insertions::NativeInsertion;
pub use job::{IoState, JobParameter, JobTime, OutputNode, OutputOperation, WriteDestination};
pub use marks::{NativeAdjustment, NativeMark, PageMarks, SplitMarks};
pub(crate) use math::paint_native_math;
pub use math::{
AccentStyle, Delimiter, FieldSource, FractionSpec, MathChar, MathField, MathNode, MathRulePosition,
NativeDisplay, NativeMath, Noad, NoadClass, NoadSource, OperatorLimits,
};
pub use math_code::MathCode;
pub use page_builder::{NativePageState, PageTrace, PageTraceReport};
pub use paragraph::{LineBreakCache, LineBreakWork, NativeParagraph, ParagraphMode, TextNode};
pub use paragraph_trace::{
ParagraphBreakKind, ParagraphLineFitTrace, ParagraphTrace, ParagraphTraceReport,
};
pub use parameters::{Parameter, ParameterValue};
pub(crate) use registers::print_scaled;
pub use registers::{Flex, Glue, Register, RegisterKind, RegisterValue};
pub use rule::NativeRule;
pub use session::{
NativeSession, PreparedRevisionExecution, ResumedExecution, RevisionError, RevisionExecution,
RevisionFailure, RevisionJob, SourceVersion,
};
pub use state::{CommandName, LinePenaltyKind, Macro, Meaning, Primitive, Profile, Replacement, State};
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
#[repr(u8)]
pub enum CatCode {
Escape,
BeginGroup,
EndGroup,
MathShift,
Alignment,
EndLine,
Parameter,
Superscript,
Subscript,
Ignored,
Space,
Letter,
Other,
Active,
Comment,
Invalid,
}
impl CatCode {
pub fn from_number(value: i32) -> Option<Self> {
Some(match value {
0 => Self::Escape,
1 => Self::BeginGroup,
2 => Self::EndGroup,
3 => Self::MathShift,
4 => Self::Alignment,
5 => Self::EndLine,
6 => Self::Parameter,
7 => Self::Superscript,
8 => Self::Subscript,
9 => Self::Ignored,
10 => Self::Space,
11 => Self::Letter,
12 => Self::Other,
13 => Self::Active,
14 => Self::Comment,
15 => Self::Invalid,
_ => return None,
})
}
}
#[derive(
Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
pub struct Span {
pub source: usize,
pub start: usize,
pub end: usize,
}
/// Causal token location, independent of a glyph's Unicode label or slot.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct TokenOrigin {
pub span: Span,
pub invocation: Option<Span>,
}
impl From<&Token> for TokenOrigin {
fn from(token: &Token) -> Self {
Self {
span: token.span,
invocation: token.invocation,
}
}
}
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum TokenKind {
Character(char, CatCode),
Command(CommandName),
}
impl TokenKind {
fn is_space(&self) -> bool {
*self == Self::Character(' ', CatCode::Space)
}
fn begin_group(&self) -> bool {
matches!(self, Self::Character(_, CatCode::BeginGroup))
}
fn end_group(&self) -> bool {
matches!(self, Self::Character(_, CatCode::EndGroup))
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct Token {
pub kind: TokenKind,
/// Origin in the source file, retained when the token enters a macro.
pub span: Span,
/// Invocation that most recently expanded this token (arguments keep their
/// own origin); not used for TeX token equality or macro parameter matching.
pub invocation: Option<Span>,
}
impl Token {
fn new(kind: TokenKind, span: Span) -> Self {
Self {
kind,
span,
invocation: None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct SourceFile {
pub name: String,
/// Original bytes, never a recoded shadow of the input file.
pub data: Vec<u8>,
}
/// Provenance and physical line separator of an in-memory TeX input file.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct GeneratedInput {
pub origin: Span,
pub separator: Option<char>,
}
/// File lookup belongs to the host. Execution never shells out to TeX or
/// searches a different engine when a file/primitive is absent.
pub trait SourceProvider {
fn match_pdf_regex(
&mut self,
request: &RegexRequest,
_cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
match_pdf_regex(request)
}
/// Change the TeX diagnostic selector. Mode zero suppresses the terminal.
fn set_interaction_mode(&mut self, _mode: u8) -> Result<(), String> {
Ok(())
}
/// Exact resource lookups and reads recorded by this execution's host.
fn execution_resource_trace(&self) -> Option<&crate::resources::ResourceTrace> {
None
}
fn resource_usage(&mut self) -> Result<Option<HostResourceUsage>, String> {
Ok(None)
}
fn read(&mut self, name: &str, from: &str) -> Result<SourceFile, String>;
fn resource(
&mut self,
_kind: crate::resources::ResourceKind,
_name: &str,
_from: &str,
) -> Result<crate::resources::LoadedResource, String> {
Err("host binary resource lookup unavailable".into())
}
/// Retain the lookup spelling when a format defers reopening the resource.
fn resource_with_lookup_path(
&mut self,
kind: crate::resources::ResourceKind,
name: &str,
from: &str,
) -> Result<(crate::resources::LoadedResource, std::path::PathBuf), String> {
let resource = self.resource(kind, name, from)?;
let path = resource.version.path.clone();
Ok((resource, path))
}
/// A missing VF permits the physical font path. Lookup and read errors do not.
fn virtual_font(
&mut self,
_name: &str,
_from: &str,
) -> Result<Option<crate::resources::LoadedResource>, String> {
Ok(None)
}
/// Look up a real named outline face in the host's resource namespace.
fn named_font(
&mut self,
_name: &str,
_style: crate::resources::FontStyle,
_from: &str,
) -> Result<Option<crate::resources::NamedFont>, String> {
Ok(None)
}
/// Apply an explicit optical size in TeX points, or the named face's default.
fn named_font_with_size(
&mut self,
name: &str,
style: crate::resources::FontStyle,
_optical_points: Option<f64>,
from: &str,
) -> Result<Option<crate::resources::NamedFont>, String> {
self.named_font(name, style, from)
}
/// Resolve the exact PostScript name of a PDF TrueType device font.
fn pdf_truetype(
&mut self,
_name: &str,
_from: &str,
) -> Result<Option<crate::resources::NamedFont>, String> {
Ok(None)
}
/// Resolve an exact PDF device name using the requested CFF charset kind.
fn pdf_cff(
&mut self,
_name: &str,
_from: &str,
_cid_keyed: bool,
) -> Result<Option<crate::resources::NamedFont>, String> {
Ok(None)
}
/// An exact lookup that can report a missing font file before trying another format.
fn optional_font_file(
&mut self, kind: crate::resources::ResourceKind, name: &str, from: &str,
) -> Result<Option<crate::resources::LoadedResource>, String> {
self.resource(kind, name, from).map(Some)
}
/// Read an actual PDF font map. A host that can distinguish missing
/// files from other failures can return None for TeX's warning path.
fn optional_font_map(
&mut self, name: &str, from: &str,
) -> Result<Option<crate::resources::LoadedResource>, String> {
self.resource(crate::resources::ResourceKind::Map, name, from).map(Some)
}
/// Read exact bytes through the normal TeX input policy. Missing inputs
/// return None. Denied or unavailable host operations remain errors.
fn optional_tex_input(
&mut self,
_name: &str,
_from: &str,
) -> Result<Option<crate::resources::LoadedResource>, String> {
Err("host optional TeX binary input unavailable".into())
}
/// Look up the byte length of a real TeX input resource.
fn file_size(&mut self, _name: &str, _from: &str) -> Result<Option<u64>, String> {
Err("host file size lookup unavailable".into())
}
/// Look up the PDF date of a real TeX input resource.
fn file_modification_date(
&mut self,
_name: &str,
_from: &str,
) -> Result<Option<String>, String> {
Err("host file modification date lookup unavailable".into())
}
fn pk_font(
&mut self,
_name: &str,
_dpi: u32,
_from: &str,
) -> Result<crate::resources::LoadedResource, String> {
Err("host PK font lookup unavailable".into())
}
/// Real driver policy, consulted only when the source requests zero.
fn default_pk_resolution(&mut self) -> Result<i32, String> {
Err("host PDF device configuration unavailable".into())
}
/// Optional observer for Message events (which are always retained in
/// Execution). Unlike stream operations, pure event consumers need no
/// external sink. The CLI observes live to preserve message/write order.
fn observe_message(&mut self, _text: &str) -> Result<(), String> {
Ok(())
}
fn observe_message_bytes(&mut self, text: &[u8]) -> Result<(), String> {
self.observe_message(&byte_translation::diagnostic_text(text))
}
/// Optional live observer for retained engine diagnostics. Unlike an
/// explicit write, a pure library consumer can inspect the typed event.
fn observe_diagnostic(
&mut self,
_destination: WriteDestination,
_text: &str,
) -> Result<(), String> {
Ok(())
}
/// Size of the entry read already validated by the host's prefix replay.
/// Hosts that report resource telemetry can opt in to resizing that read.
fn replayed_entry_bytes(&self) -> Option<u64> {
None
}
/// Observe resource accounting while preserving the typed report for replay.
fn observe_statistics(&mut self, report: &StatisticsReport) -> Result<(), String> {
self.observe_diagnostic(report.destination, &report.text)
}
/// Observe a diagnostic that starts at the current output column.
fn observe_inline_diagnostic(
&mut self,
destination: WriteDestination,
text: &str,
) -> Result<(), String> {
self.observe_diagnostic(destination, text)
}
/// Observe formatted diagnostic bytes, including intentional blank lines.
fn observe_raw_diagnostic(
&mut self,
destination: WriteDestination,
text: &str,
) -> Result<(), String> {
self.observe_diagnostic(destination, text)
}
/// Observe an opening or closing marker for a traced generated input.
fn observe_pseudo_input(&mut self, opening: bool) -> Result<(), String> {
self.observe_inline_diagnostic(
WriteDestination::TerminalAndLog,
if opening { "( " } else { ")" },
)
}
/// Resume both diagnostic channels after a log-only display. TeX starts
/// a line on both streams when either stream is still on a line.
fn observe_diagnostic_pair(&mut self, log: &str, terminal: &str) -> Result<(), String> {
self.observe_diagnostic(WriteDestination::Log, log)?;
self.observe_diagnostic(WriteDestination::TerminalOnly, terminal)
}
/// Observe an actual fail-stop error. Pure library users receive the same
/// typed error without needing a live terminal or log sink.
fn observe_error(&mut self, _error: &Error) -> Result<(), String> {
Ok(())
}
/// Open a real stream; missing files return None, other failures are errors.
/// Returned name is the resolved source identity; actual bytes are collected on read.
fn open_in(&mut self, _stream: u8, _name: &str, _from: &str) -> Result<Option<String>, String> {
Err("host input streams unavailable".into())
}
/// Include physical line endings. None means EOF, not an empty line.
fn read_line(&mut self, _stream: u8) -> Result<Option<Vec<u8>>, String> {
Err("host input streams unavailable".into())
}
/// Return original bytes through one delimiter of the requested framing.
/// Hosts with byte-framed streams can retain the existing UTF-8 path.
fn read_xe_line(&mut self, stream: u8, framing: XeLineFraming) -> Result<Option<Vec<u8>>, String> {
if matches!(framing, XeLineFraming::Utf16Le | XeLineFraming::Utf16Be) {
return Err("host UTF-16 input streams unavailable".into());
}
let bytes = self.read_line(stream)?;
if framing == XeLineFraming::Auto
&& bytes.as_deref().is_some_and(|data| XeLineFraming::detect(data).0.unit_width() == 2)
{
return Err("host UTF-16 input streams unavailable".into());
}
Ok(bytes)
}
fn close_in(&mut self, _stream: u8) -> Result<(), String> {
Err("host input streams unavailable".into())
}
fn open_out(&mut self, _stream: u8, _name: &str, _from: &str) -> Result<String, String> {
Err("host output streams unavailable".into())
}
fn write_out(&mut self, _stream: u8, _text: &str) -> Result<(), String> {
Err("host output streams unavailable".into())
}
/// Hosts that persist byte-mode TeX output must accept arbitrary bytes.
fn write_out_bytes(&mut self, stream: u8, bytes: &[u8]) -> Result<(), String> {
let text = std::str::from_utf8(bytes).map_err(|_| "host output stream requires UTF-8")?;
self.write_out(stream, text)
}
fn close_out(&mut self, _stream: u8) -> Result<(), String> {
Err("host output streams unavailable".into())
}
fn diagnostic(&mut self, _destination: WriteDestination, _text: &str) -> Result<(), String> {
Err("host diagnostic sink unavailable".into())
}
fn diagnostic_bytes(&mut self, destination: WriteDestination, bytes: &[u8]) -> Result<(), String> {
self.diagnostic(destination, &byte_translation::diagnostic_text(bytes))
}
}
pub struct NoFiles;
impl SourceProvider for NoFiles {
fn read(&mut self, name: &str, _: &str) -> Result<SourceFile, String> {
Err(format!("input file unavailable: {name}"))
}
}
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
)]
pub enum Dependency {
CatCode(char),
Meaning(CommandName),
Count(u16),
Register(Register),
Parameter(Parameter),
MagnificationState,
PdfFileState,
PdfCatalogState,
PdfInfoState,
PdfObjects,
PdfImages,
PdfLastPosition,
GlyphUnicode,
ResourceStatistics,
PdfDeviceConfiguration {
pk_resolution: i32,
},
TextFont,
FontResources,
ParagraphMode,
ParagraphShape,
LinePenalties(LinePenaltyKind),
PreviousParagraphLines,
Hyphenation,
BoxRegister(u16),
SplitMarks(u16),
SplitDiscards,
PageState,
PageMarks(u16),
MathCode(u8),
DelCode(u8),
SfCode(u8),
CaseCode(CaseCode, char),
MathFamily {
size: u8,
family: u8,
},
MathState,
BoxPackState,
VerticalState,
Toks(u16),
EndLineChar,
NewLineChar,
EscapeChar,
InteractionMode,
GroupState,
ConditionalState,
AssignmentState,
TokenParameter(TokenParameter),
GlobalDefs,
Source(usize),
JobParameter(JobParameter),
JobName,
PdfCreationDate,
PdfRandomState,
FileLookup {
name: String,
from: String,
},
FileModificationDate {
name: String,
from: String,
value: Option<String>,
},
InputStream(u8),
XeDefaultInputEncoding,
XeLineBreakLocale,
InputPosition(usize),
OutputStream(u8),
ParagraphToken,
UnicodeMathCode(u32),
UnicodeSfCode(u32),
UnicodeDelCode(u32),
XeCharClass(u32),
XeInterCharTokens(u32),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ShowReport {
pub output: String,
pub log_output: String,
pub the: bool,
pub text: String,
pub context: InputContext,
pub span: Span,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Event {
PdfImageObject(crate::pdf_image::PdfImageObject),
ShipoutTrace {
log: String,
terminal: String,
},
AssignmentTrace {
destination: WriteDestination,
text: String,
},
RestoreTrace {
retaining: bool,
destination: WriteDestination,
text: String,
},
CommandTrace {
destination: WriteDestination,
text: String,
},
MacroTrace {
destination: WriteDestination,
text: String,
},
Character(Token),
Paragraph(Span),
Message {
text: String,
span: Span,
},
Write {
destination: WriteDestination,
text: String,
span: Span,
},
DeferredOutput(OutputNode),
MissingGlyph(MissingGlyph),
ShowBox(ShowBoxReport),
Show(ShowReport),
ShowRedirected {
stream: u8,
text: String,
span: Span,
},
BuiltParagraph(Box<NativeParagraph>),
BuiltMath(Box<NativeMath>),
BuiltDisplay(Box<NativeDisplay>),
VerticalMaterial(Vec<NativeVerticalNode>),
Shipout(Box<NativeShipout>),
PdfForm(Box<crate::pdf_device::forms::ShippedForm>),
Statistics(Box<StatisticsReport>),
PageTrace(Box<PageTraceReport>),
ParagraphTrace(Box<ParagraphTraceReport>),
PseudoInput {
source: usize,
opening: bool,
traced: bool,
},
ConditionalTrace {
command: Primitive,
condition: Primitive,
inverted: bool,
level: usize,
origin: Option<(usize, usize)>,
destination: WriteDestination,
text: String,
},
GroupTrace {
entering: bool,
group_type: i32,
level: usize,
origin: Option<(usize, usize)>,
destination: WriteDestination,
text: String,
},
}
fn default_interaction_mode() -> u8 {
1 // Native jobs start with nonstop diagnostics.
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Execution<F = u64> {
#[serde(default)]
pub format_dumped: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
format_pdf_images: Vec<format_image::FormatPdfImage>,
#[serde(default)]
pub job_name: Option<String>,
#[serde(default = "default_interaction_mode")]
pub interaction_mode: u8,
pub native_page: Option<NativePageState>,
#[serde(default)]
pub split_discards: Vec<NativeVerticalNode>,
pub after_assignment: Option<Token>,
pub events: Vec<Event>,
pub state: State,
pub io: IoState,
/// Physical scanner position, independent of macro definition/call spans.
pub input_position: Option<(usize, usize)>,
pub paragraph_mode: ParagraphMode,
/// Physical and generated inputs in span-source order.
pub sources: Vec<std::sync::Arc<SourceFile>>,
/// Source IDs backed by the bytes delivered through an input stream.
#[serde(default)]
pub stream_sources: BTreeSet<usize>,
#[serde(default)]
pub generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
/// Dependencies observed over the execution. Suffix reuse additionally
/// validates the state and the reads that follow its checkpoint.
pub reads: BTreeSet<Dependency>,
/// Internal epochs relate active checkpoint cuts to repeated reads.
#[serde(skip)]
dependency_evidence: dependency_reads::DependencyEvidence,
/// Per-source observations distinguish suffix reads from identical prefix reads.
#[serde(default, skip_serializing_if = "Option::is_none")]
line_observations: Option<BTreeMap<usize, usize>>,
pub incoming_state: u64,
pub outgoing_state: F,
pub steps: usize,
/// Completed charge count for proving remaining box capacity at a splice.
#[serde(default, skip_serializing_if = "Option::is_none")]
box_nodes_created: Option<usize>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
reads_event_history: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
accounts_event_history: bool,
}
/// The exact final state is available for layout. Its fingerprint may still
/// require the canonical hash before a completed execution can be published.
pub struct DeferredStateFingerprint(FingerprintState);
enum FingerprintState {
Known(u64),
NeedsHash(Option<state::CommandFingerprintBase>),
}
impl fmt::Debug for DeferredStateFingerprint {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
FingerprintState::Known(value) => formatter.debug_tuple("Known").field(&value).finish(),
FingerprintState::NeedsHash(_) => formatter.write_str("NeedsHash"),
}
}
}
impl DeferredStateFingerprint {
fn known(value: u64) -> Self {
Self(FingerprintState::Known(value))
}
fn pending(prior: Option<&State>) -> Self {
Self(FingerprintState::NeedsHash(prior.map(State::command_fingerprint_base)))
}
fn calculate(&self, state: &State) -> u64 {
match &self.0 {
FingerprintState::Known(value) => *value,
FingerprintState::NeedsHash(prior) => state.fingerprint_with_base(prior.as_ref()),
}
}
}
impl<F> Execution<F> {
fn with_outgoing_state<T>(self, outgoing_state: T) -> Execution<T> {
Execution {
format_dumped: self.format_dumped,
format_pdf_images: self.format_pdf_images,
job_name: self.job_name,
interaction_mode: self.interaction_mode,
native_page: self.native_page,
split_discards: self.split_discards,
after_assignment: self.after_assignment,
events: self.events,
state: self.state,
io: self.io,
input_position: self.input_position,
paragraph_mode: self.paragraph_mode,
sources: self.sources,
stream_sources: self.stream_sources,
generated_inputs: self.generated_inputs,
reads: self.reads,
dependency_evidence: self.dependency_evidence,
line_observations: self.line_observations,
incoming_state: self.incoming_state,
outgoing_state,
steps: self.steps,
box_nodes_created: self.box_nodes_created,
reads_event_history: self.reads_event_history,
accounts_event_history: self.accounts_event_history,
}
}
}
impl Execution<DeferredStateFingerprint> {
fn needs_fingerprint(&self) -> bool {
matches!(self.outgoing_state.0, FingerprintState::NeedsHash(_))
}
fn finish_fingerprint(self) -> Execution {
let fingerprint = self.outgoing_state.calculate(&self.state);
self.with_outgoing_state(fingerprint)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ScannerStatus {
#[default]
Normal,
Defining(CommandName),
Matching(CommandName),
Absorbing,
Skipping,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Error {
pub scanner_status: ScannerStatus,
pub message: String,
/// The primary diagnostic was already accepted by the live observer.
pub message_reported: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub help: Option<String>,
pub span: Span,
pub source_name: String,
pub line: usize,
pub column: usize,
pub context: InputContext,
}
/// Actual progress at a failed/cancelled execution boundary. This is evidence,
/// not a resumable executor checkpoint or a successful document.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ExecutionEvidence {
pub sources: Vec<std::sync::Arc<SourceFile>>,
pub source_versions: Vec<SourceVersion>,
pub stream_sources: BTreeSet<usize>,
pub generated_inputs: std::collections::BTreeMap<usize, GeneratedInput>,
pub reads: BTreeSet<Dependency>,
pub events: Vec<Event>,
pub input_position: Option<(usize, usize)>,
pub incoming_state: u64,
pub outgoing_state: u64,
pub group_depth: usize,
pub paragraph_mode: ParagraphMode,
pub steps: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ExecutionFailure {
pub error: Box<Error>,
pub evidence: ExecutionEvidence,
}
impl Error {
fn at(
sources: &[impl std::borrow::Borrow<SourceFile>],
profile: InputProfile,
message: impl Into<String>,
span: Span,
) -> Self {
let source = sources.get(span.source).map(std::borrow::Borrow::borrow);
let name = source.map_or("<input>", |s| s.name.as_str()).to_owned();
let prefix = source.map_or(&[][..], |s| &s.data[..span.start.min(s.data.len())]);
let (mut line, mut column, mut carriage_return) = (1, 1, false);
for &c in prefix {
match c {
b'\r' => {
line += 1;
column = 1;
carriage_return = true;
}
b'\n' => {
if !carriage_return {
line += 1;
}
column = 1;
carriage_return = false;
}
_ => {
if profile == InputProfile::TeX8Bit || c & 0xc0 != 0x80 {
column += 1;
}
carriage_return = false;
}
}
}
Error {
scanner_status: ScannerStatus::Normal,
message: message.into(),
message_reported: false,
help: None,
span,
source_name: name,
line,
column,
context: InputContext::default(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}:{}:{}: {}",
self.source_name, self.line, self.column, self.message
)
}
}
impl std::error::Error for Error {}
impl<F> Execution<F> {
/// Paint actual shipped boxes using their captured device state. No
/// pagination or application of the job's final device settings.
pub fn shipout_display_lists(&self) -> Result<Vec<crate::render::DisplayList>, Error> {
self.shipout_display_lists_with(NativeShipout::display_list)
}
/// Lower shipped boxes, optionally reusing their immutable local layout.
/// The current revision still resolves all deferred and document-wide PDF data.
pub fn shipout_display_lists_with(
&self,
mut lower: impl FnMut(&NativeShipout) -> Result<crate::render::DisplayList, String>,
) -> Result<Vec<crate::render::DisplayList>, Error> {
if self.native_page.is_none() {
return Err(Error::at(
&self.sources,
self.state.input_profile(),
"shipout export requires native job execution",
Span::default(),
));
}
let mut pages = Vec::new();
let mut image_objects = Vec::new();
let mut forms = Vec::new();
for e in &self.events {
if let Event::PdfImageObject(image) = e {
image_objects.push(image.clone());
}
if let Event::PdfForm(form) = e {
let mut list = form.canvas.display_list().map_err(|message| {
Error::at(&self.sources, self.state.input_profile(), message, form.canvas.box_node.span)
})?;
list.pdf_resources.attributes = form.attributes.clone().into();
forms.push(crate::pdf_device::forms::FormDisplay {
form: form.form, resource_number: form.resource_number, list, xdv: None,
});
}
if let Event::Shipout(b) = e {
pages.push(lower(b).map_err(|message| {
Error::at(
&self.sources,
self.state.input_profile(),
message,
b.box_node.span,
)
})?);
}
}
if let Some(navigation) = &self.state.xdv_navigation {
forms.extend(navigation.split_forms(&mut pages).map_err(|message| {
Error::at(&self.sources, self.state.input_profile(), message, Span::default())
})?);
}
if !self.state.pdf_draft_mode() {
self.resolve_page_graphics_resources(&mut pages)?;
if let Some(navigation) = &self.state.xdv_navigation {
navigation.mark_resource_previews(&mut pages);
navigation.resolve_page_dictionaries(&mut pages).map_err(|message| {
Error::at(&self.sources, self.state.input_profile(), message, Span::default())
})?;
}
for form in &mut forms {
let attributes = std::mem::take(&mut form.list.pdf_resources.attributes);
self.resolve_page_graphics_resources(std::slice::from_mut(&mut form.list))?;
form.list.pdf_resources.attributes = attributes;
}
}
if let Some(first) = pages.first_mut() {
first.forms = forms;
first.items.extend(
image_objects
.into_iter()
.map(crate::render::DisplayItem::PdfImageObject),
);
}
Ok(pages)
}
fn resolve_page_graphics_resources(
&self,
pages: &mut [crate::render::DisplayList],
) -> Result<(), Error> {
use crate::pdf_device::page_resources::{
PageResources, PdfObjects, font_attributes_affect_paint,
};
use std::collections::btree_map::Entry;
use crate::render::DisplayItem;
let empty = PdfObjects::default();
let objects = self.state.pdf_objects.as_deref().unwrap_or(&empty);
let mut font_affects_paint = BTreeMap::new();
for page in pages.iter_mut() {
let states = page.items.iter().filter_map(|item| match item {
DisplayItem::PdfColor { program, .. } => Some(&program.graphics_states),
_ => None,
}).flatten().cloned().collect();
page.pdf_resources = PageResources::from_page(
page.pdf_resources.entries.clone(),
page.pdf_resources.attributes.clone(),
page.pdf_resources.objects,
&states,
objects,
).map_err(|message| Error::at(
&self.sources, self.state.input_profile(), message, Span::default(),
))?;
if self.state.fonts.pdf_settings.is_empty() {
continue;
}
for item in &page.items {
let DisplayItem::NativeGlyph { font, .. } = item else {
continue;
};
let affects_paint = match font_affects_paint.entry(font.id) {
Entry::Occupied(entry) => *entry.get(),
Entry::Vacant(entry) => {
let affects_paint = self.state.fonts.pdf_settings(font.id)
.filter(|settings| !settings.attributes.is_empty())
.map(|settings| font_attributes_affect_paint(&settings.attributes))
.transpose()
.map_err(|message| Error::at(
&self.sources, self.state.input_profile(), message, Span::default(),
))?
.unwrap_or(false);
*entry.insert(affects_paint)
}
};
if affects_paint {
page.pdf_resources.needs_pdf_for_preview = true;
break;
}
}
}
crate::pdf_device::page_attributes::resolve(pages, &self.state.pdf_pages_attributes, objects)
.map_err(|message| Error::at(
&self.sources, self.state.input_profile(), message, Span::default(),
))
}
/// Export the paragraphs already measured during token execution. No text
/// concatenation, source parser or final-state restyling participates.
pub fn document(&self) -> Result<crate::Document, Error> {
if self.native_page.is_some() {
return Err(Error::at(
&self.sources,
self.state.input_profile(),
"native jobs export actual shipout boxes; list measurement cannot rebuild their pagination",
Span::default(),
));
}
use crate::{HorizontalItem, Unit, VerticalGlue, VerticalItem};
// Native lists use TeX sp. The shared display/export boundary uses
// 1/65536 bp; convert once, after all TeX layout decisions.
fn bp(n: i64) -> i64 {
if n < 0 {
-((-n * 800 + 401) / 803)
} else {
(n * 800 + 401) / 803
}
}
fn export_line(line: &crate::Paragraph) -> crate::Paragraph {
let mut line = line.clone();
line.width = bp(line.width);
line.height = bp(line.height);
line.depth = bp(line.depth);
line.font_size = bp(line.font_size);
line.left_skip = bp(line.left_skip);
for n in &mut line.line_indents {
*n = bp(*n)
}
for n in &mut line.line_baselines {
*n = bp(*n)
}
for row in &mut line.lines {
for item in row {
match item {
HorizontalItem::Box(b) => {
b.width = bp(b.width);
b.height = bp(b.height);
b.depth = bp(b.depth);
b.italic = bp(b.italic);
b.raise = bp(b.raise);
b.size = b.size.map(bp);
}
HorizontalItem::Glue {
width,
stretch,
shrink,
..
} => {
*width = bp(*width);
*stretch = bp(*stretch);
*shrink = bp(*shrink);
}
_ => unreachable!("native packed lines contain only fixed boxes and glue"),
}
}
}
line
}
let mut units = Vec::new();
let mut text_width = 0;
for event in &self.events {
match event {
Event::VerticalMaterial(nodes) => {
let mut items = Vec::new();
for n in nodes {
match n {
NativeVerticalNode::Line(b) | NativeVerticalNode::Box(b) => {
text_width = text_width.max(b.width + b.shift);
items.push(VerticalItem::Paragraph(export_line(
&boxes::box_paragraph(*b.clone()),
)));
}
NativeVerticalNode::Glue(g)
| NativeVerticalNode::NamedGlue(g, _)
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => {
items.push(VerticalItem::StretchGlue(VerticalGlue::with_order(
bp(g.width as i64),
bp(g.stretch.amount as i64),
bp(g.shrink.amount as i64),
g.stretch.order,
)))
}
NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => {
items.push(VerticalItem::Glue(bp(*n as i64)))
}
NativeVerticalNode::Penalty(n) => {
items.push(VerticalItem::Penalty(*n as i64))
}
NativeVerticalNode::Rule(r) => {
let w = r.width.ok_or_else(|| {
Error::at(
&self.sources,
self.state.input_profile(),
"outer running rule requires native page packaging",
r.span,
)
})? as i64;
let h = i64::from(r.height.unwrap_or(0))
+ i64::from(r.depth.unwrap_or(0));
items.push(if w > 0 && h > 0 {
VerticalItem::Rule {
width: bp(w),
height: bp(h),
}
} else {
VerticalItem::Glue(bp(h))
});
}
NativeVerticalNode::Output(n) => {
return Err(Error::at(
&self.sources,
self.state.input_profile(),
"deferred output requires native job shipout",
n.span,
));
}
NativeVerticalNode::Mark(m) => {
return Err(Error::at(
&self.sources,
self.state.input_profile(),
"outer marks require native page ownership; cannot discard mark material",
m.span,
));
}
NativeVerticalNode::Insertion(n) => {
return Err(Error::at(
&self.sources,
self.state.input_profile(),
"outer insertion requires native page ownership",
n.span,
));
}
}
}
units.push(Unit::vertical(units.len() as u64, items));
}
Event::DeferredOutput(node) => {
return Err(Error::at(
&self.sources,
self.state.input_profile(),
"deferred I/O requires native shipout/list execution; cannot discard or flush at EOF",
node.span,
));
}
_ => {}
}
}
// Export canvas/page policy remains a host demo environment; page
// parameter primitives are not advertised until real page execution.
let mut document = crate::Document::new(648 * 65536, units).with_top_skip(10 * 65536);
// All native paragraph penalties are already frozen into the list;
// export must not apply document-wide paragraph heuristics again.
// Native pages use TeX's actual vertical glue packaging. Infinite
// terminal fill keeps the last page natural; earlier forced pages
// distribute finite stretch instead of applying a ragged demo policy.
document.ragged_bottom = false;
document.club_penalty = 0;
document.widow_penalty = 0;
document.text_width = bp(text_width).max(1);
document.h_offset = 72 * 65536;
document.v_offset = 72 * 65536;
Ok(document)
}
}