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

842 lines
28 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 cancellation;
mod case;
mod context;
mod device;
mod diagnostics;
mod engine;
mod font_catalog;
mod fonts;
mod format_image;
pub use format_image::FormatImage;
mod hooks;
mod hyphenation;
mod input_profile;
mod insertions;
mod job;
mod ligature;
mod marks;
mod math;
mod math_accent;
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 reconstitute;
mod registers;
mod rule;
mod session;
mod state;
mod statistics;
mod vertical_break;
pub use statistics::{
HostResourceUsage, MaterialUsage, ResourceUsage, StackUsage, StateUsage, StatisticsPhase,
StatisticsReport,
};
use std::collections::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};
pub use diagnostics::{DiagnosticBox, DiagnosticNode, ShowBoxReport};
pub use engine::{EntryCheckpoint, Executor, Limits};
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::{
Delimiter, FieldSource, FractionSpec, MathChar, MathField, MathNode, MathRulePosition,
NativeDisplay, NativeMath, Noad, NoadClass, NoadSource, OperatorLimits,
};
pub use page_builder::{NativePageState, PageTrace, PageTraceReport};
pub use paragraph::{LineBreakCache, LineBreakWork, NativeParagraph, ParagraphMode, TextNode};
pub use paragraph_trace::{ParagraphBreakKind, ParagraphTrace, ParagraphTraceReport};
pub use parameters::{Parameter, ParameterValue};
pub use registers::{Flex, Glue, Register, RegisterKind, RegisterValue};
pub use rule::NativeRule;
pub use session::{
NativeSession, RevisionError, RevisionExecution, RevisionFailure, RevisionJob, SourceVersion,
};
pub use state::{CommandName, 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 {
/// 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())
}
/// 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 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(())
}
/// 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(())
}
/// 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())
}
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())
}
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())
}
}
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,
PdfImages,
GlyphUnicode,
ResourceStatistics,
PdfDeviceConfiguration {
pk_resolution: i32,
},
TextFont,
FontResources,
ParagraphMode,
ParagraphShape,
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,
AssignmentState,
TokenParameter(TokenParameter),
GlobalDefs,
Source(usize),
JobParameter(JobParameter),
JobName,
PdfCreationDate,
FileLookup {
name: String,
from: String,
},
FileModificationDate {
name: String,
from: String,
value: Option<String>,
},
InputStream(u8),
InputPosition(usize),
OutputStream(u8),
}
#[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),
BuiltParagraph(Box<NativeParagraph>),
BuiltMath(Box<NativeMath>),
BuiltDisplay(Box<NativeDisplay>),
VerticalMaterial(Vec<NativeVerticalNode>),
Shipout(Box<NativeShipout>),
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 {
#[serde(default)]
pub format_dumped: bool,
#[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,
pub sources: Vec<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>,
/// Reads made during this execution, not a license to reuse output after
/// state changes. Incremental execution/cache reuse is a later milestone.
pub reads: BTreeSet<Dependency>,
pub incoming_state: u64,
pub outgoing_state: u64,
pub steps: usize,
}
#[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<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: &[SourceFile],
profile: InputProfile,
message: impl Into<String>,
span: Span,
) -> Self {
let source = sources.get(span.source);
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 Execution {
/// 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> {
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();
for e in &self.events {
if let Event::PdfImageObject(image) = e {
image_objects.push(image.clone());
}
if let Event::Shipout(b) = e {
pages.push(b.display_list().map_err(|message| {
Error::at(
&self.sources,
self.state.input_profile(),
message,
b.box_node.span,
)
})?);
}
}
if let Some(first) = pages.first_mut() {
first.items.extend(
image_objects
.into_iter()
.map(crate::render::DisplayItem::PdfImageObject),
);
}
Ok(pages)
}
/// 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)
}
}