Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -0,0 +1,940 @@
use super::super::boxes::{self, PackSpec, VerticalBuilder};
use super::*;
#[derive(Clone, Copy)]
pub(super) enum Destination {
Append,
Register(u16, bool),
Shift(i32),
Shipout,
Adjustment { pre: bool },
Insertion { class: u8 },
}
pub(super) struct BoxFrame {
kind: BoxKind,
spec: PackSpec,
group: GroupKind,
depth: usize,
destination: Destination,
paragraph: Option<super::super::paragraph::Builder>,
vertical: VerticalBuilder,
span: Span,
discretionary: Option<DiscretionaryFrame>,
math: Vec<super::super::math::MathBuilder>,
// An inner $...$ belongs to this box, even inside an outer display.
display: Option<super::display::DisplayFrame>,
}
struct DiscretionaryFrame {
parts: Vec<Vec<TextNode>>,
font: FontId,
span: Span,
math: Vec<super::super::math::MathBuilder>,
}
impl BoxFrame {
pub(super) fn collect_statistics(&self, c: &mut super::super::statistics::Collector) {
use super::super::statistics::Ownership::Active;
if let Some(p) = &self.paragraph {
c.paragraph_builder(p);
}
c.vertical(&self.vertical.nodes, Active);
if let Some(d) = &self.display {
d.collect_statistics(c);
}
for m in &self.math {
c.math_builder(m);
}
if let Some(d) = &self.discretionary {
for p in &d.parts {
c.text(p, Active);
}
for m in &d.math {
c.math_builder(m);
}
}
}
}
impl Executor {
pub(super) fn scan_rule(
&mut self,
horizontal: bool,
origin: TokenOrigin,
files: &mut impl SourceProvider,
) -> Result<NativeRule, Error> {
let span = origin.span;
let mut r = if horizontal {
NativeRule {
span,
origin: Some(origin),
derivation: None,
width: None,
height: Some(26214),
depth: Some(0),
}
} else {
NativeRule {
span,
origin: Some(origin),
derivation: None,
width: Some(26214),
height: None,
depth: None,
}
};
loop {
if self.keyword("width", files)? {
r.width = Some(self.dimension(false, false, files)?.amount);
} else if self.keyword("height", files)? {
r.height = Some(self.dimension(false, false, files)?.amount);
} else if self.keyword("depth", files)? {
r.depth = Some(self.dimension(false, false, files)?.amount);
} else {
break;
}
}
Ok(r)
}
pub(super) fn shift_box(
&mut self,
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let horizontal = matches!(p, Primitive::Moveleft | Primitive::Moveright);
if horizontal != (self.paragraph.is_none() && self.math.is_empty()) {
return self.fail("native box shift is incompatible with the current mode");
}
let n = self.dimension(false, false, files)?.amount;
let shift = if matches!(p, Primitive::Raise | Primitive::Moveleft) {
-n
} else {
n
};
self.scan_box(Destination::Shift(shift), files)
}
pub(super) fn unpackage(
&mut self,
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let vertical = matches!(p, Primitive::Unvbox | Primitive::Unvcopy);
if vertical && self.paragraph.is_some() {
if self.restricted() || !self.math.is_empty() {
return self.fail("native vertical unboxing requires vertical mode");
}
self.end_paragraph(files)?;
}
let index = self.register_index(files)?;
self.reads.insert(Dependency::BoxRegister(index));
let Some(b) = self.state.box_register(index) else {
return Ok(());
};
if !self.math.is_empty() || b.kind.is_unset() || (b.kind == BoxKind::Horizontal) == vertical
{
return self.fail("incompatible native box cannot be unboxed in this mode");
}
let copy = matches!(p, Primitive::Unhcopy | Primitive::Unvcopy);
let b = if copy {
let b = b.clone();
self.account_box(&b)?;
b
} else {
self.state.take_box(index).unwrap()
};
match b.content {
BoxContent::Horizontal(nodes) => self
.paragraph
.as_mut()
.expect("unhbox starts an actual paragraph")
.nodes
.extend(nodes),
BoxContent::Vertical(nodes) => {
let start = self.vertical.nodes.len();
self.vertical.extend(nodes);
// unpackage transfers nodes without append_to_vlist. In
// particular it neither inserts glue nor updates prev_depth.
self.emit_vertical(start);
}
}
Ok(())
}
pub(super) fn start_discretionary(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.paragraph.is_none() && self.math.is_empty() {
self.begin_paragraph(span, true)?;
}
self.finish_text(true)?;
self.begin_discretionary_part(
DiscretionaryFrame {
parts: Vec::new(),
font: self.state.text_font(),
span,
math: Vec::new(),
},
files,
)
}
fn begin_discretionary_part(
&mut self,
mut disc: DiscretionaryFrame,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.box_frames.len() >= self.limits.input_depth.min(32) {
return self.fail("native discretionary nesting capacity exceeded");
}
self.begin_group(GroupKind::Discretionary, files)?;
let open = loop {
let t = self.expanded_non_space(files)?.token;
if self.primitive(&t) != Some(Primitive::Relax) {
break t;
}
};
if !matches!(
self.meaning(&open),
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
) {
return self.fail("expected opening brace for native discretionary part");
}
disc.math = std::mem::take(&mut self.math);
self.box_frames.push(BoxFrame {
kind: BoxKind::Horizontal,
spec: PackSpec::Natural,
group: GroupKind::Discretionary,
depth: self.state.group_depth(),
destination: Destination::Append,
paragraph: self.paragraph.take(),
vertical: self.vertical.enter_nested(true),
span: disc.span,
discretionary: Some(disc),
math: Vec::new(),
display: self.display.take(),
});
let mut b = super::super::paragraph::Builder::default();
b.start(&self.state, open.span, false);
b.restricted = true;
b.font_step_limit = self.limits.steps.saturating_sub(self.steps);
b.ligature_carry = self.ligature_carry;
self.paragraph = Some(b);
Ok(())
}
fn finish_discretionary_part(
&mut self,
mut disc: DiscretionaryFrame,
part: Vec<TextNode>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if part.iter().any(|n| {
!matches!(
n,
TextNode::Glyph { .. }
| TextNode::Kern { .. }
| TextNode::Box(_)
| TextNode::Indent(_)
| TextNode::Rule(_)
)
}) {
return self.fail(
"improper native discretionary material: only glyphs, boxes, rules and kerns are allowed",
);
}
self.box_nodes_created = self.box_nodes_created.saturating_add(part.len());
if self.box_nodes_created > self.limits.tokens {
return self.fail("native discretionary node capacity exceeded");
}
disc.parts.push(part);
if disc.parts.len() < 3 {
return self.begin_discretionary_part(disc, files);
}
let replacement = disc.parts.pop().unwrap();
if !self.math.is_empty() && !replacement.is_empty() {
return self.fail("native math discretionary replacement must be empty");
}
let replacement_count = u8::try_from(replacement.len()).ok().ok_or_else(|| {
self.error(
"native discretionary replacement exceeds 255 nodes",
disc.span,
)
})?;
let post_break = disc.parts.pop().unwrap();
let pre_break = disc.parts.pop().unwrap();
let node = TextNode::Discretionary {
font: disc.font,
automatic: false,
hyphen_char: None,
pre_break,
post_break,
replacement_count,
};
if let Some(m) = self.math.last_mut() {
m.nodes.push(MathNode::Discretionary(Box::new(node)));
} else {
let parent = self
.paragraph
.as_mut()
.expect("discretionary parent horizontal list");
parent.nodes.push(node);
parent.nodes.extend(replacement);
}
Ok(())
}
pub(super) fn restricted(&self) -> bool {
self.paragraph.as_ref().is_some_and(|p| p.restricted)
}
pub(super) fn emit_vertical(&mut self, start: usize) {
if self.outer_vertical() && start < self.vertical.nodes.len() {
self.events.push(Event::VerticalMaterial(
self.vertical.nodes[start..].to_vec(),
));
}
if self.outer_vertical() {
if let Some(page) = self.native_page.as_mut() {
page.contributions.extend(self.vertical.take_nodes());
}
}
}
pub(super) fn account_box(&mut self, b: &NativeBox) -> Result<(), Error> {
self.box_nodes_created = self.box_nodes_created.saturating_add(b.node_count());
if self.box_nodes_created > self.limits.tokens {
return self.fail("native box node capacity exceeded");
};
Ok(())
}
pub(super) fn scan_box(
&mut self,
destination: Destination,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let token = loop {
let t = self.expanded_non_space(files)?.token;
if self.primitive(&t) != Some(Primitive::Relax) {
break t;
}
};
let p = self
.primitive(&token)
.ok_or_else(|| self.error("expected native box constructor", token.span))?;
self.box_command(p, destination, token.span, files)
}
pub(super) fn box_command(
&mut self,
p: Primitive,
destination: Destination,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use Primitive::*;
if p == Vsplit {
let index = self.register_index(files)?;
if !self.keyword("to", files)? {
return self.fail("expected to in native vsplit");
}
let height = self.dimension(false, false, files)?.amount;
self.reads.insert(Dependency::BoxRegister(index));
// Splitting clears all split classes globally, including a void box.
self.state.split_marks.clear();
let Some(original) = self.state.box_register(index) else {
return self.deliver_box(None, destination, files);
};
if !matches!(original.kind, BoxKind::Vertical | BoxKind::Vtop) {
return self.fail("native vsplit needs a vbox");
}
let max_depth = self.read_parameter(Parameter::Splitmaxdepth).width();
let skip = self.read_parameter(Parameter::Splittopskip).glue();
let original = self.state.take_box(index).unwrap();
let BoxContent::Vertical(mut nodes) = original.content else {
unreachable!()
};
let cut = super::super::vertical_break::find_break(
&nodes,
i64::from(height),
max_depth,
&mut self.steps,
self.limits.steps,
)
.map_err(|e| self.error(e, span))?;
let tail = nodes.split_off(cut.index);
self.collect_split_marks(&nodes)?;
let tail = super::super::vertical_break::prune_top(
tail,
skip,
&mut self.steps,
self.limits.steps,
)
.map_err(|e| self.error(e, span))?;
let remaining = if tail.is_empty() {
None
} else {
let b = boxes::vpack(
tail,
PackSpec::Natural,
1_073_741_823,
BoxKind::Vertical,
span,
)
.map_err(|e| self.error(e, span))?;
self.diagnose_box(&b, files)?;
self.account_box(&b)?;
Some(b)
};
// Mutate the source register without changing its saved eq level.
self.state.set_box(index, remaining);
let b = boxes::vpack(
nodes,
PackSpec::To(height),
max_depth,
BoxKind::Vertical,
span,
)
.map_err(|e| self.error(e, span))?;
self.diagnose_box(&b, files)?;
self.account_box(&b)?;
return self.deliver_box(Some(b), destination, files);
}
if p == Lastbox {
if !self.math.is_empty() {
return self.fail("lastbox is not allowed in native math mode");
}
let mut b = if let Some(par) = self.paragraph.as_mut() {
let protected=par.nodes.iter().enumerate().any(|(i,n)|matches!(n,TextNode::Discretionary{replacement_count,..}if *replacement_count>0 && i+usize::from(*replacement_count)+1==par.nodes.len()));
if protected {
None
} else {
match par.nodes.last() {
Some(TextNode::Box(b)) if b.native_box.is_some() => {
let Some(TextNode::Box(b)) = par.nodes.pop() else {
unreachable!()
};
b.native_box.map(|b| *b)
}
Some(TextNode::Indent(_)) => {
let Some(TextNode::Indent(width)) = par.nodes.pop() else {
unreachable!()
};
Some(NativeBox {
kind: BoxKind::Horizontal,
display: false,
width: i64::from(width),
height: 0,
depth: 0,
shift: 0,
content: BoxContent::Horizontal(Vec::new()),
diagnostic: Vec::new(),
setting: GlueSetting::default(),
badness: 0,
diagnostic_eligible: false,
excess: 0,
span: par.span,
})
}
_ => None,
}
}
} else {
if self.outer_vertical() && self.native_page.is_some() {
let page = self.native_page.as_mut().unwrap();
if page.contributions.is_empty() {
return self.fail("lastbox cannot take a box from the native current page");
}
let b = if matches!(
page.contributions.back(),
Some(NativeVerticalNode::Box(_) | NativeVerticalNode::Line(_))
) {
match page.contributions.pop_back().unwrap() {
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => Some(*b),
_ => unreachable!(),
}
} else {
None
};
let mut b = b;
if let Some(b) = &mut b {
b.shift = 0;
}
return self.deliver_box(b, destination, files);
}
if self.outer_vertical() {
return self.fail("lastbox cannot take material from the outer native page before native page ownership is implemented");
}
self.reads.insert(Dependency::VerticalState);
self.vertical
.take_last_box()
.map_err(|e| self.error(e, self.current))?
};
if let Some(b) = &mut b {
b.shift = 0;
}
return self.deliver_box(b, destination, files);
}
if matches!(p, Box | Copy) {
let index = self.register_index(files)?;
self.reads.insert(Dependency::BoxRegister(index));
let b = if p == Box {
self.state.take_box(index)
} else {
if let Some(b) = self.state.box_register(index).cloned() {
self.account_box(&b)?;
Some(b)
} else {
None
}
};
return self.deliver_box(b, destination, files);
}
if p == Vcenter && (!matches!(destination, Destination::Append) || self.math.is_empty()) {
return self.fail("vcenter requires native math mode and cannot be a box assignment");
}
let kind = match p {
Hbox => BoxKind::Horizontal,
Vbox | Vcenter => BoxKind::Vertical,
Vtop => BoxKind::Vtop,
_ => return self.fail("expected native box constructor"),
};
if self.box_frames.len() >= self.limits.input_depth.min(32) {
return self.fail("native box nesting capacity exceeded");
}
let spec = if self.keyword("to", files)? {
PackSpec::To(self.dimension(false, false, files)?.amount)
} else if self.keyword("spread", files)? {
PackSpec::Spread(self.dimension(false, false, files)?.amount)
} else {
PackSpec::Natural
};
let group = match kind {
BoxKind::Horizontal
if matches!(destination, Destination::Append | Destination::Shift(_))
&& self.paragraph.is_none()
&& self.math.is_empty() =>
{
GroupKind::AdjustedHbox
}
BoxKind::Horizontal => GroupKind::Hbox,
BoxKind::Vertical if p == Vcenter => GroupKind::Vcenter,
BoxKind::Vertical => GroupKind::Vbox,
BoxKind::Vtop => GroupKind::Vtop,
BoxKind::Unset { .. } => return self.fail("cannot package an unset box group"),
};
self.open_box_group(kind, spec, group, destination, span, files)
}
pub(super) fn start_adjustment(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.paragraph.is_none() && self.math.is_empty() {
return self.fail("vadjust requires native horizontal or math mode");
}
if self.box_frames.len() >= self.limits.input_depth.min(32) {
return self.fail("native box nesting capacity exceeded");
}
let pre = self.state.profile() == Profile::EtexBootstrap && self.keyword("pre", files)?;
self.open_box_group(
BoxKind::Vertical,
PackSpec::Natural,
GroupKind::Insertion,
Destination::Adjustment { pre },
span,
files,
)
}
pub(super) fn start_insertion(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let class = self.integer(files)?;
if !(0..255).contains(&class) {
return self.fail("native insertion class must be in 0..254");
}
if self.box_frames.len() >= self.limits.input_depth.min(32) {
return self.fail("native box nesting capacity exceeded");
}
self.open_box_group(
BoxKind::Vertical,
PackSpec::Natural,
GroupKind::Insertion,
Destination::Insertion { class: class as u8 },
span,
files,
)
}
fn open_box_group(
&mut self,
kind: BoxKind,
spec: PackSpec,
group: GroupKind,
destination: Destination,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
// scan_spec opens the save level before scan_left_brace expands input.
self.begin_group(group, files)?;
let open = loop {
let t = self.expanded_non_space(files)?.token;
if self.primitive(&t) != Some(Primitive::Relax) {
break t;
}
};
if !matches!(
self.meaning(&open),
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
) {
return self.fail("expected opening brace for native box");
}
let frame = BoxFrame {
kind,
spec,
group,
depth: self.state.group_depth(),
destination,
paragraph: self.paragraph.take(),
vertical: self.vertical.enter_nested(kind == BoxKind::Horizontal),
span,
discretionary: None,
math: std::mem::take(&mut self.math),
display: self.display.take(),
};
self.box_frames.push(frame);
if kind == BoxKind::Horizontal {
let mut b = super::super::paragraph::Builder::default();
b.start(&self.state, span, false);
b.font_step_limit = self.limits.steps.saturating_sub(self.steps);
b.restricted = true;
self.paragraph = Some(b);
} else {
self.normal_paragraph(files)?;
}
if group == GroupKind::Insertion {
return Ok(());
}
self.push_mode_hook(if kind == BoxKind::Horizontal {
TokenParameter::Everyhbox
} else {
TokenParameter::Everyvbox
})
}
pub(super) fn close_box_group(
&mut self,
files: &mut impl SourceProvider,
) -> Result<bool, Error> {
if !self
.box_frames
.last()
.is_some_and(|f| f.depth == self.state.group_depth())
{
return Ok(false);
}
self.finish_text(true)?;
let horizontal = self.restricted();
if !horizontal {
self.end_paragraph(files)?;
}
// TeX package: capture inner boxmaxdepth, unsave, then hpack/vpackage.
let max_depth = if matches!(
self.box_frames.last().unwrap().group,
GroupKind::Vcenter | GroupKind::Insertion
) {
// TeX uses natural vpack's maximum depth for vcenter and adjustments.
Some(1_073_741_823)
} else if self.box_frames.last().unwrap().discretionary.is_none() {
Some(self.read_parameter(Parameter::Boxmaxdepth).width())
} else {
None
};
let insertion_specs = matches!(
self.box_frames.last().unwrap().destination,
Destination::Insertion { .. }
)
.then(|| {
(
self.read_parameter(Parameter::Splittopskip).glue(),
self.read_parameter(Parameter::Splitmaxdepth).width(),
self.read_parameter(Parameter::Floatingpenalty).width(),
)
});
let frame = self.box_frames.pop().unwrap();
self.finish_group(frame.group, self.current, files)?;
if let Some(mut disc) = frame.discretionary {
let part = self.paragraph.take().unwrap().nodes;
self.paragraph = frame.paragraph;
self.vertical.leave_nested(frame.vertical, true);
self.math = std::mem::take(&mut disc.math);
self.display = frame.display;
self.finish_discretionary_part(disc, part, files)?;
return Ok(true);
}
self.reads
.insert(Dependency::Parameter(Parameter::Overfullrule));
self.reads.insert(Dependency::Parameter(Parameter::Hfuzz));
let mut adjustments = super::super::marks::MigratingMaterial::default();
let result = if horizontal {
let b = self.paragraph.take().unwrap();
let nodes = if frame.group == GroupKind::AdjustedHbox {
let (nodes, extracted) = super::super::marks::extract(b.nodes);
adjustments = extracted;
nodes
} else {
b.nodes
};
boxes::hpack(nodes, frame.spec, frame.span, &self.state)
} else {
boxes::vpack(
self.vertical.take_nodes(),
frame.spec,
max_depth.expect("vertical box maximum depth"),
frame.kind,
frame.span,
)
};
let b = result.map_err(|e| self.error(e, frame.span))?;
self.diagnose_box(&b, files)?;
self.account_box(&b)?;
self.paragraph = frame.paragraph;
self.vertical.leave_nested(frame.vertical, horizontal);
self.math = frame.math;
self.display = frame.display;
if !adjustments.pre.is_empty() {
let start = self.vertical.nodes.len();
self.vertical.extend(adjustments.pre);
self.emit_vertical(start);
}
if frame.group == GroupKind::Vcenter {
self.accept_box_math_field(b)?;
let Some(MathNode::Noad(n)) = self.math.last_mut().unwrap().nodes.last_mut() else {
unreachable!()
};
n.vcenter = true;
n.span = frame.span;
} else if let Destination::Adjustment { pre } = frame.destination {
let BoxContent::Vertical(nodes) = b.content else {
unreachable!("vadjust owns a vertical list");
};
let adjustment = NativeAdjustment { pre, nodes };
if let Some(math) = self.math.last_mut() {
math.nodes.push(MathNode::Adjustment(adjustment));
} else {
self.paragraph
.as_mut()
.unwrap()
.nodes
.push(TextNode::Adjustment(adjustment));
}
} else if let Destination::Insertion { class } = frame.destination {
let BoxContent::Vertical(nodes) = b.content else {
unreachable!("insert owns a vertical list");
};
let (split_top, split_depth, float_cost) =
insertion_specs.expect("saved inner insertion parameters");
let insertion = NativeInsertion {
class,
natural_size: b.height + b.depth,
split_top,
split_depth,
float_cost,
nodes,
span: frame.span,
};
if let Some(math) = self.math.last_mut() {
math.nodes.push(MathNode::Insertion(insertion));
} else if let Some(paragraph) = self.paragraph.as_mut() {
paragraph.nodes.push(TextNode::Insertion(insertion));
} else {
let start = self.vertical.nodes.len();
self.vertical.push(NativeVerticalNode::Insertion(insertion));
self.emit_vertical(start);
self.request_page();
}
} else {
self.deliver_box(Some(b), frame.destination, files)?;
}
let start = self.vertical.nodes.len();
self.vertical.extend(adjustments.post);
self.emit_vertical(start);
Ok(true)
}
pub(super) fn diagnose_box(
&mut self,
b: &NativeBox,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.state.last_badness = b.badness;
let vertical = b.kind != BoxKind::Horizontal;
let threshold = self
.read_parameter(if vertical {
Parameter::Vbadness
} else {
Parameter::Hbadness
})
.width();
let fuzz = self
.read_parameter(if vertical {
Parameter::Vfuzz
} else {
Parameter::Hfuzz
})
.width() as i64;
let report = b.diagnostic_eligible
&& if b.badness == 1_000_000 {
b.excess > fuzz || threshold < 100
} else {
b.badness > threshold
};
if report {
let label = if b.badness == 1_000_000 {
"Overfull"
} else if b.setting.sign < 0 {
"Tight"
} else if b.badness > 100 {
"Underfull"
} else {
"Loose"
};
let kind = if vertical { "vbox" } else { "hbox" };
files
.observe_message(&format!(
"\n{label} \\{kind} (badness {}, excess {}sp)\n",
b.badness, b.excess
))
.map_err(|e| self.error(e, b.span))?;
}
Ok(())
}
fn deliver_box(
&mut self,
mut b: Option<NativeBox>,
destination: Destination,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if let Destination::Shift(shift) = destination {
if let Some(b) = &mut b {
b.shift = i64::from(shift);
}
}
match destination {
Destination::Adjustment { .. } | Destination::Insertion { .. } => {
unreachable!("handled when the adjustment group closes")
}
Destination::Register(n, global) => {
let equivalent = b.is_none() && self.state.box_register(n).is_none();
self.assign_equivalence(Key::Box(n), global, equivalent, files, |state| {
state.assign_box(n, b, global);
})?;
}
Destination::Shipout => {
self.native_page_mut()?;
if let Some(b) = b {
self.pending_shipouts.push_back(b);
}
}
Destination::Append | Destination::Shift(_) => {
if let Some(b) = b {
if !self.math.is_empty() {
self.accept_box_math_field(b)?;
} else if let Some(p) = self.paragraph.as_mut() {
p.nodes.push(TextNode::Box(b.horizontal_item()));
p.space_factor = 1000;
} else {
let start = self.vertical.nodes.len();
self.append_vertical_box(NativeVerticalNode::Box(Box::new(b)))?;
self.emit_vertical(start);
self.request_page();
}
}
}
}
Ok(())
}
pub(super) fn append_vertical_box(&mut self, node: NativeVerticalNode) -> Result<(), Error> {
self.reads.insert(Dependency::VerticalState);
for p in [
Parameter::Baselineskip,
Parameter::Lineskip,
Parameter::Lineskiplimit,
] {
self.reads.insert(Dependency::Parameter(p));
}
self.vertical
.append_box(node, &self.state)
.map_err(|e| self.error(e, self.current))
}
pub(super) fn vertical_command(
&mut self,
p: Primitive,
origin: TokenOrigin,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use Primitive::*;
if self.paragraph.is_some() {
if self.restricted() {
return self.fail("vertical command in restricted horizontal mode");
};
self.end_paragraph(files)?;
}
let start = self.vertical.nodes.len();
let node = match p {
Vskip | Vfil | Vfill | Vss | Vfilneg => {
NativeVerticalNode::Glue(self.skip_glue(p, files)?)
}
Kern => NativeVerticalNode::Kern(self.dimension(false, false, files)?.amount),
Penalty => NativeVerticalNode::Penalty(self.integer(files)?),
Hrule => {
let r = self.scan_rule(true, origin, files)?;
if self.outer_vertical() && self.native_page.is_none() && r.width.is_none() {
return self
.fail("outer running rule requires native page packaging; specify width");
}
self.vertical.prev_depth = -1000 * 65536;
NativeVerticalNode::Rule(r)
}
_ => unreachable!(),
};
self.vertical.push(node);
self.emit_vertical(start);
if p == Penalty {
self.request_page();
}
Ok(())
}
pub(super) fn dimension_value(
&mut self,
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<i32, Error> {
if p == Primitive::Prevdepth {
if self.writing || self.paragraph.is_some() || !self.math.is_empty() {
return self.fail("prevdepth requires vertical mode");
}
self.reads.insert(Dependency::VerticalState);
return Ok(self.vertical.prev_depth);
}
let index = self.register_index(files)?;
self.reads.insert(Dependency::BoxRegister(index));
Ok(self.state.box_register(index).map_or(0, |b| match p {
Primitive::Wd => b.width as i32,
Primitive::Ht => b.height as i32,
Primitive::Dp => b.depth as i32,
_ => unreachable!(),
}))
}
pub(super) fn assign_box_dimension(
&mut self,
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let index = if p == Primitive::Prevdepth {
if self.paragraph.is_some() || !self.math.is_empty() {
return self.fail("prevdepth requires vertical mode");
};
None
} else {
Some(self.register_index(files)?)
};
self.optional_equals(files)?;
let n = self.dimension(false, false, files)?.amount;
if let Some(index) = index {
self.state.box_dimension(index, p, n)
} else {
self.vertical.prev_depth = n
};
Ok(())
}
}
@@ -0,0 +1,35 @@
use super::*;
impl Executor {
pub(super) fn case_character(&self, value: i32) -> Result<char, Error> {
self.check_input_character(value)?;
u32::try_from(value)
.ok()
.and_then(char::from_u32)
.ok_or_else(|| self.error("invalid case-code character number", self.current))
}
pub(super) fn change_case(
&mut self,
kind: CaseCode,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let mut tokens = self.scan_group(files)?;
for token in &mut tokens {
self.tick()?;
let c = match &mut token.kind {
TokenKind::Character(c, _) | TokenKind::Command(CommandName::Active(c)) => c,
TokenKind::Command(
CommandName::Control(_) | CommandName::Font(_) | CommandName::FrozenRelax,
) => continue,
};
self.reads.insert(Dependency::CaseCode(kind, *c));
let value = self.state.case_code(kind, *c);
if value != 0 {
*c = char::from_u32(value).expect("validated case-code scalar");
}
}
self.push_kind(
tokens.into_iter().map(InputToken::from).collect(),
TokenInputKind::BackedUp,
)
}
}
@@ -0,0 +1,123 @@
use super::*;
use crate::pdf_device::{PdfFileOptions, PdfPageData};
impl Executor {
pub(super) fn validate_pdf_final_state(&mut self) -> Result<(), Error> {
if let Some(options) = self.state.pdf_file_options.clone() {
self.reads.insert(Dependency::GlyphUnicode);
self.read_parameter(Parameter::Pdfgentounicode);
self.reads.insert(Dependency::PdfFileState);
let mode = self.read_parameter(Parameter::Pdfoutput).width();
if self.state.output_mode_set != Some(mode) {
return self.fail("native pdfoutput cannot change after output has started");
}
let major = self.read_parameter(Parameter::Pdfmajorversion).width();
let minor = self.read_parameter(Parameter::Pdfminorversion).width();
if options.major != major || i32::from(options.minor) != minor {
return self.fail("native PDF version cannot change after output has started");
}
}
Ok(())
}
pub(super) fn glyph_to_unicode(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let glyph = self.scan_expanded_group(files)?;
let glyph = self.token_list_text(&glyph);
let value = self.scan_expanded_group(files)?;
let value = self.token_list_text(&value);
self.reads.insert(Dependency::GlyphUnicode);
if !self.state.glyph_unicode.contains(&glyph)
&& self.state.glyph_unicode.len() >= self.limits.tokens
{
return self.fail("native glyph Unicode table capacity exceeded");
}
if let Some(warning) = self.state.glyph_unicode.define(glyph, &value) {
let text = format!("native PDF warning: {warning}");
files
.observe_message(&text)
.map_err(|e| self.error(e, self.current))?;
self.events.push(Event::Message {
text,
span: self.current,
});
}
Ok(())
}
pub(super) fn pdf_page_data(
&mut self,
files: &mut impl SourceProvider,
) -> Result<Option<PdfPageData>, Error> {
self.reads.insert(Dependency::PdfFileState);
let mode = self.read_parameter(Parameter::Pdfoutput).width();
if self
.state
.output_mode_set
.is_some_and(|previous| previous != mode)
{
return self.fail("native pdfoutput cannot change after output has started");
}
self.state.output_mode_set = Some(mode);
if mode <= 0 {
return Ok(None);
}
let major = self.read_parameter(Parameter::Pdfmajorversion).width();
let minor = self.read_parameter(Parameter::Pdfminorversion).width();
if major < 1 || !(0..=9).contains(&minor) {
return self.fail("invalid native PDF version");
}
if let Some(fixed) = &self.state.pdf_file_options {
if fixed.major != major || i32::from(fixed.minor) != minor {
return self.fail("native PDF version cannot change after output has started");
}
} else {
let mut object_compression = self
.read_parameter(Parameter::Pdfobjcompresslevel)
.width()
.clamp(0, 3) as u8;
if major == 1 && minor < 5 && object_compression > 0 {
object_compression = 0;
let text =
"native PDF warning: object streams require PDF 1.5 or greater; disabled"
.to_string();
files
.observe_message(&text)
.map_err(|e| self.error(e, self.current))?;
self.events.push(Event::Message {
text,
span: self.current,
});
}
let decimal_digits = self
.read_parameter(Parameter::Pdfdecimaldigits)
.width()
.clamp(0, 4) as u8;
let mut pk_resolution = self.read_parameter(Parameter::Pdfpkresolution).width();
if pk_resolution == 0 {
pk_resolution = files
.default_pk_resolution()
.map_err(|e| self.error(e, self.current))?;
self.reads
.insert(Dependency::PdfDeviceConfiguration { pk_resolution });
// pdfTeX initializes this eqtb integer directly. Do not create
// a new save entry, or discard an already pending restoration.
self.state.initialize_pdf_pk_resolution(pk_resolution);
}
self.state.pdf_file_options = Some(PdfFileOptions {
major,
minor: minor as u8,
object_compression,
decimal_digits,
pk_resolution: pk_resolution.clamp(72, 8000) as u32,
});
}
let level = self.read_parameter(Parameter::Pdfcompresslevel).width();
if level > 9 {
return self.fail("invalid native PDF compression level");
}
Ok(Some(PdfPageData {
file: self.state.pdf_file_options.clone().unwrap(),
stream_compression: level.max(0) as u8,
}))
}
}
@@ -0,0 +1,515 @@
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::<usize>();
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<String, Error> {
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 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)
}
pub(super) fn show(
&mut self,
the: bool,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let text = 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
}
};
self.print_show_parts(&[&format!("> {text}.")])?
} 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();
self.print_show_parts(&[
&format!("> {name}{}", &meaning[..split]),
&format!("{}.", &meaning[split..]),
])?
} else {
self.print_show_parts(&[&format!("> {name}{meaning}.")])?
}
};
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)?;
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,
)
.map_err(|e| self.error(e, span))?;
self.reads.extend(reads);
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(())
}
}
impl Executor {
pub(super) fn trace_macro_call(
&mut self,
definition: &Macro,
call: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Tracingmacros).width() > 0 {
let command = self.message_token(call);
let body = self.macro_token_text(definition, call.span)?;
self.emit_macro_trace(&format!("{command}{body}"), true, files)?;
}
Ok(())
}
pub(super) fn trace_macro_argument(
&mut self,
definition: &Macro,
index: usize,
argument: &[Token],
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Tracingmacros).width() > 0 {
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)?;
}
Ok(())
}
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::<Vec<_>>()
.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(())
}
}
@@ -0,0 +1,476 @@
//! TeX init_math / after_math / resume_after_display over owned native lists.
use super::super::boxes::{self, PackSpec};
use super::*;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum EquationSide {
Left,
Right,
}
pub(super) struct EquationNumber {
pub(super) side: EquationSide,
pub(super) box_: NativeBox,
}
pub(super) struct DisplayFrame {
previous_lines: usize,
pub(super) number_side: Option<EquationSide>,
// A completed alignment remains owned while closing assignments/$$ scan.
// It must not disappear from resource/failure observations on an error.
alignment: Option<boxes::VerticalBuilder>,
}
impl DisplayFrame {
pub(super) fn collect_statistics(&self, c: &mut super::super::statistics::Collector) {
if let Some(list) = &self.alignment {
c.vertical(&list.nodes, super::super::statistics::Ownership::Active);
}
}
pub(super) fn has_alignment(&self) -> bool {
self.alignment.is_some()
}
}
impl Executor {
pub(super) fn start_display(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let (previous_lines, pre_size) =
self.finish_paragraph(files, Parameter::Displaywidowpenalty, false)?;
// The display takes the second line following the broken text.
let shape =
super::super::paragraph::shaped_line(self.read_paragraph_shape(), previous_lines + 1);
let (indent, width) = if let Some(line) = shape {
(line.indent, i64::from(line.width))
} else {
let hang = self.read_parameter(Parameter::Hangindent).width() as i64;
let after = self.read_parameter(Parameter::Hangafter).width() as i64;
let applies = hang != 0
&& if after >= 0 {
previous_lines as i64 + 2 > after
} else {
previous_lines as i64 + 1 < -after
};
let width = self.read_parameter(Parameter::Hsize).width() as i64
- if applies { hang.abs() } else { 0 };
(if applies { hang.max(0) as i32 } else { 0 }, width)
};
self.begin_group(GroupKind::MathShift, files)?;
for (p, value) in [
(Parameter::Fam, ParameterValue::Integer(-1)),
(
Parameter::Predisplaysize,
ParameterValue::dimension(pre_size),
),
(
Parameter::Displaywidth,
ParameterValue::dimension(
i32::try_from(width)
.map_err(|_| self.error("native display width capacity exceeded", span))?,
),
),
(Parameter::Displayindent, ParameterValue::dimension(indent)),
] {
// TeX's internal eq_word_define is local regardless of globaldefs.
self.assign_traced_parameter(p, value, false, files)?;
}
self.display = Some(DisplayFrame {
previous_lines,
number_side: None,
alignment: None,
});
self.math.push(super::super::math::MathBuilder::new(
self.state.group_depth(),
None,
span,
));
self.push_mode_hook(TokenParameter::Everydisplay)?;
self.request_page();
Ok(())
}
pub(super) fn start_equation_number(
&mut self,
side: EquationSide,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.math.len() != 1
|| self.state.group_depth() != self.math[0].depth
|| self
.display
.as_ref()
.is_none_or(|d| d.number_side.is_some() || d.has_alignment())
{
return self.fail("native equation number requires outer display math");
}
if self.math.len() >= self.limits.input_depth.min(32) {
return self.fail("native math nesting capacity exceeded");
}
self.begin_group(GroupKind::MathShift, files)?;
self.assign_traced_parameter(Parameter::Fam, ParameterValue::Integer(-1), false, files)?;
self.display.as_mut().unwrap().number_side = Some(side);
self.math.push(super::super::math::MathBuilder::new(
self.state.group_depth(),
None,
span,
));
self.push_mode_hook(TokenParameter::Everymath)
}
pub(super) fn finish_display(
&mut self,
horizontal: &[TextNode],
mut number: Option<EquationNumber>,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let frame = self.display.take().unwrap();
let start = self.vertical.nodes.len();
let (material, adjustments) = super::super::marks::extract(horizontal.to_vec());
let mut b = boxes::hpack(material.clone(), PackSpec::Natural, span, &self.state)
.map_err(|e| self.error(e, span))?;
let width = self.read_parameter(Parameter::Displaywidth).width() as i64;
let left = number
.as_ref()
.is_some_and(|n| n.side == EquationSide::Left);
let mut e = number.as_ref().map_or(0, |n| n.box_.width);
let q = if number.is_some() {
let font = self.state.math_font(0, 2);
let quad = self
.state
.fonts
.font(font)
.map_err(|e| self.error(e, span))?
.parameters()[5];
e + i64::from(quad)
} else {
0
};
if b.width + q > width {
let mut shrink = [0i64; 4];
for node in &material {
if let TextNode::Glue(g) | TextNode::NamedGlue(g, _) = node {
shrink[usize::from(g.shrink.order)] += i64::from(g.shrink.amount);
}
}
let target = if e != 0
&& (b.width - shrink[0] + q <= width || shrink[1..].iter().any(|&n| n != 0))
{
Some(width - q)
} else {
e = 0;
(b.width > width).then_some(width)
};
if let Some(target) = target {
let target = i32::try_from(target)
.map_err(|_| self.error("native display width capacity exceeded", span))?;
b = boxes::hpack(material.clone(), PackSpec::To(target), span, &self.state)
.map_err(|e| self.error(e, span))?;
}
}
self.state.last_badness = b.badness;
let mut displacement = (width - b.width + 1).div_euclid(2);
if e > 0 && displacement < 2 * e {
displacement = (width - b.width - e + 1).div_euclid(2);
if matches!(
material.first(),
Some(TextNode::Glue(_) | TextNode::NamedGlue(_, _))
) {
displacement = 0;
}
}
let indent = self.read_parameter(Parameter::Displayindent).width() as i64;
let short = !left
&& indent + displacement
> self.read_parameter(Parameter::Predisplaysize).width() as i64;
let above = if short {
Parameter::Abovedisplayshortskip
} else {
Parameter::Abovedisplayskip
};
let below = if short {
Parameter::Belowdisplayshortskip
} else {
Parameter::Belowdisplayskip
};
let before = self.read_parameter(Parameter::Predisplaypenalty).width();
let after = self.read_parameter(Parameter::Postdisplaypenalty).width();
let separate_left = left && e == 0;
let separate_right = !left && e == 0 && number.is_some();
let above_glue = (!separate_left).then(|| self.read_parameter(above).glue());
let below_glue = (!separate_right).then(|| self.read_parameter(below).glue());
for g in [above_glue, below_glue].into_iter().flatten() {
if g.stretch.amount < 0 || g.shrink.amount < 0 || g.shrink.order != 0 {
return self.fail(
"unsupported negative flexibility or infinite shrink in native display skip",
);
}
}
// hpack diagnostics are actual packaging results, not page costs.
let threshold = self.read_parameter(Parameter::Hbadness).width();
let fuzz = self.read_parameter(Parameter::Hfuzz).width() as i64;
if b.diagnostic_eligible
&& if b.badness == 1_000_000 {
b.excess > fuzz || threshold < 100
} else {
b.badness > threshold
}
{
files
.observe_message(&format!(
"\n{} \\hbox (badness {}) in native display\n",
if b.badness == 1_000_000 {
"Overfull"
} else if b.setting.sign < 0 {
"Tight"
} else if b.badness > 100 {
"Underfull"
} else {
"Loose"
},
b.badness
))
.map_err(|e| self.error(e, span))?;
}
// The math boxes retain display status when packed into a normal line.
b.display = true;
if e != 0 {
let tag = number.take().unwrap().box_;
let space = i32::try_from(width - b.width - e - displacement)
.map_err(|_| self.error("native equation number gap capacity exceeded", span))?;
let kern = TextNode::Kern {
width: space,
explicit: false,
};
let boxed = TextNode::Box(b.horizontal_item());
let tag = TextNode::Box(tag.horizontal_item());
let line = if left {
displacement = 0;
vec![tag, kern, boxed]
} else {
vec![boxed, kern, tag]
};
b = boxes::hpack(line, PackSpec::Natural, span, &self.state)
.map_err(|e| self.error(e, span))?;
self.state.last_badness = b.badness;
}
b.shift = indent + displacement;
self.account_box(&b)?;
self.vertical.push(NativeVerticalNode::Penalty(before));
if let Some(glue) = above_glue {
self.vertical
.push(NativeVerticalNode::NamedGlue(glue, above));
} else {
let mut tag = number.take().unwrap().box_;
tag.shift = indent;
self.account_box(&tag)?;
self.append_vertical_box(NativeVerticalNode::Box(Box::new(tag)))?;
self.vertical.push(NativeVerticalNode::Penalty(10_000));
}
self.append_vertical_box(NativeVerticalNode::Box(Box::new(b.clone())))?;
if let Some(number) = number {
let mut tag = number.box_;
tag.shift = indent + width - tag.width;
self.account_box(&tag)?;
self.vertical.push(NativeVerticalNode::Penalty(10_000));
self.append_vertical_box(NativeVerticalNode::Box(Box::new(tag)))?;
}
self.vertical.extend(adjustments.post);
self.vertical.extend(adjustments.pre);
self.vertical.push(NativeVerticalNode::Penalty(after));
if let Some(glue) = below_glue {
self.vertical
.push(NativeVerticalNode::NamedGlue(glue, below));
}
let parameters = Parameter::ALL
.iter()
.map(|p| (*p, self.state.parameter(*p)))
.collect();
self.events
.push(Event::BuiltDisplay(Box::new(NativeDisplay {
parameters,
box_: b,
short_skips: short,
previous_lines: frame.previous_lines,
span,
})));
self.emit_vertical(start);
self.resume_after_display(span, files)
}
pub(super) fn finish_display_alignment(
&mut self,
list: boxes::VerticalBuilder,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.display.as_mut().unwrap().alignment = Some(list);
// fin_align's do_assignments runs in the empty display math list. In
// particular, the second closing shift is expanded before pop_nest.
let close = self.display_assignments(files)?;
if !matches!(
self.meaning(&close.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
) {
return self.fail("native display alignment must end with two math shifts");
}
let close = self.required_expanded(files)?;
if !matches!(
self.meaning(&close.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
) {
return self.fail("native display alignment must end with a second math shift");
}
self.math.pop().unwrap();
let before = self.read_parameter(Parameter::Predisplaypenalty).width();
let after = self.read_parameter(Parameter::Postdisplaypenalty).width();
let above = self.read_parameter(Parameter::Abovedisplayskip).glue();
let below = self.read_parameter(Parameter::Belowdisplayskip).glue();
let start = self.vertical.nodes.len();
self.vertical.push(NativeVerticalNode::Penalty(before));
self.vertical.push(NativeVerticalNode::NamedGlue(
above,
Parameter::Abovedisplayskip,
));
let pending = self.display.as_ref().unwrap().alignment.as_ref().unwrap();
if self.vertical.tail_depth() + pending.tail_depth() > self.limits.input_depth.min(128) {
return self.fail("native owned list tail depth capacity exceeded");
}
let list = self.display.as_mut().unwrap().alignment.take().unwrap();
self.vertical.prev_depth = list.prev_depth;
self.vertical.append_builder(list);
self.vertical.push(NativeVerticalNode::Penalty(after));
self.vertical.push(NativeVerticalNode::NamedGlue(
below,
Parameter::Belowdisplayskip,
));
self.emit_vertical(start);
self.display.take().unwrap();
self.resume_after_display(span, files)
}
fn display_assignments(
&mut self,
files: &mut impl SourceProvider,
) -> Result<InputToken, Error> {
use Primitive::*;
loop {
let t = self.expanded_non_space(files)?;
match self.meaning(&t.token) {
Meaning::Primitive(Relax) => continue,
Meaning::Primitive(p)
if p.page_dimension().is_some()
|| matches!(
p,
Global
| Long
| Outer
| Protected
| Def
| Gdef
| Edef
| Xdef
| Let
| Futurelet
| Chardef
| Mathchardef
| Catcode
| Lccode
| Uccode
| Sfcode
| Mathcode
| Delcode
| Count
| Countdef
| Dimen
| Dimendef
| Skip
| Skipdef
| Muskip
| Muskipdef
| Toks
| Toksdef
| Advance
| Multiply
| Divide
| Read
| Readline
| Font
| Fontdimen
| Hyphenchar
| Skewchar
| Textfont
| Scriptfont
| Scriptscriptfont
| Endlinechar
| Newlinechar
| Escapechar
| Globaldefs
| Time
| Day
| Month
| Year
| Spacefactor
| Setbox
| Parshape
| Wd
| Ht
| Dp
| Prevdepth
| Prevgraf
| Batchmode
| Nonstopmode
| Scrollmode
| Errorstopmode
| Interactionmode
| Deadcycles
| Insertpenalties
) =>
{
self.assignment(Some(p), None, files)?
}
Meaning::Count(n) => self.assignment(None, Some(Key::Count(n)), files)?,
Meaning::Toks(n) => self.assignment(None, Some(Key::Toks(n)), files)?,
Meaning::TokenParameter(p) => {
self.assignment(None, Some(Key::TokenParameter(p)), files)?
}
Meaning::Register(r) => self.assignment(None, Some(Key::Register(r)), files)?,
Meaning::Parameter(p) => self.assignment(None, Some(Key::Parameter(p)), files)?,
Meaning::Font(font) => {
self.reads.insert(Dependency::GlobalDefs);
self.select_traced_font(font, self.state.global(false), files)?;
self.finish_assignment()?;
}
_ => return Ok(t),
}
}
}
fn resume_after_display(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.finish_group(GroupKind::MathShift, span, files)?;
// Resume the same paragraph: no indent or parskip, but updated language
// minima and spacefactor after restoring the display's local state.
let mut p = super::super::paragraph::Builder::default();
p.start(&self.state, span, false);
p.font_step_limit = self.limits.steps.saturating_sub(self.steps);
self.reads.insert(Dependency::PreviousParagraphLines);
let lines = i32::try_from(self.vertical.previous_lines + 3)
.map_err(|_| self.error("native display line-count capacity exceeded", span))?;
self.vertical.previous_lines = lines as usize;
p.vertical_start = self.vertical.nodes.len();
self.paragraph = Some(p);
if let Some(t) = self.expanded(files)? {
if !matches!(
self.meaning(&t.token),
Meaning::Character(TokenKind::Character(_, CatCode::Space))
) {
self.unread(t)?;
}
}
self.request_page();
Ok(())
}
}
@@ -0,0 +1,151 @@
//! Typed e-TeX expressions. All arithmetic is in sp/mu-sp; no string evaluation.
use super::*;
impl Executor {
pub(super) fn quantity_expression(
&mut self,
kind: RegisterKind,
files: &mut impl SourceProvider,
) -> Result<RegisterValue, Error> {
self.quantity_expression_level(kind, files, false)
}
fn quantity_expression_level(
&mut self,
kind: RegisterKind,
files: &mut impl SourceProvider,
parenthesized: bool,
) -> Result<RegisterValue, Error> {
if self.expression_depth >= self.limits.input_depth.min(32) {
return self.fail("native expression nesting limit exceeded");
}
self.expression_depth += 1;
let result = self.quantity_expression_sum(kind, files, parenthesized);
self.expression_depth -= 1;
result
}
fn quantity_expression_sum(
&mut self,
kind: RegisterKind,
files: &mut impl SourceProvider,
parenthesized: bool,
) -> Result<RegisterValue, Error> {
let mut value = self.quantity_expression_term(kind, files)?;
loop {
let Some(next) = self.expanded(files)? else {
return Ok(normalize(value));
};
match next.token.kind {
TokenKind::Character(_, CatCode::Space) => continue,
TokenKind::Character(op @ ('+' | '-'), CatCode::Other) => {
let mut other = self.quantity_expression_term(kind, files)?;
if op == '-' {
other = map(other, |n| registers::bounded(-(n as i64)))
.map_err(|e| self.error(e, self.current))?;
}
value = add(value, other).map_err(|e| self.error(e, self.current))?;
}
_ if self.primitive(&next.token) == Some(Primitive::Relax) => {
if parenthesized {
return self.fail("missing ) in quantity expression");
}
return Ok(normalize(value));
}
_ => {
self.unread(next)?;
return Ok(normalize(value));
}
}
}
}
fn quantity_expression_term(
&mut self,
kind: RegisterKind,
files: &mut impl SourceProvider,
) -> Result<RegisterValue, Error> {
let mut value = self.quantity_expression_factor(kind, files)?;
let mut op = self.expression_operator(files)?;
while let Some(current) = op {
let numerator = self.expression_factor(files, 0)?;
op = self.expression_operator(files)?;
if current == '*' && op == Some('/') {
let denominator = self.expression_factor(files, 0)?;
value = scale(value, numerator, denominator)
.map_err(|e| self.error(e, self.current))?;
op = self.expression_operator(files)?;
} else if current == '*' {
value = scale(value, numerator, 1).map_err(|e| self.error(e, self.current))?;
} else {
value = scale(value, 1, numerator).map_err(|e| self.error(e, self.current))?;
}
}
Ok(normalize(value))
}
fn quantity_expression_factor(
&mut self,
kind: RegisterKind,
files: &mut impl SourceProvider,
) -> Result<RegisterValue, Error> {
let first = self.expanded_non_space(files)?;
if first.token.kind == TokenKind::Character('(', CatCode::Other) {
let value = self.quantity_expression_level(kind, files, true)?;
let close = self.expanded_non_space(files)?;
if close.token.kind != TokenKind::Character(')', CatCode::Other) {
return self.fail("missing ) in quantity expression");
}
Ok(value)
} else {
self.unread(first)?;
self.quantity(kind, files)
}
}
}
fn add(a: RegisterValue, b: RegisterValue) -> Result<RegisterValue, &'static str> {
Ok(match (a, b) {
(RegisterValue::Dimension(a), RegisterValue::Dimension(b)) => {
RegisterValue::Dimension(registers::bounded(a as i64 + b as i64)?)
}
(RegisterValue::Glue(a), RegisterValue::Glue(b)) => RegisterValue::Glue(a.add(b)?),
_ => unreachable!("expression scanner retains its quantity type"),
})
}
fn map(
value: RegisterValue,
mut f: impl FnMut(i32) -> Result<i32, &'static str>,
) -> Result<RegisterValue, &'static str> {
Ok(match value {
RegisterValue::Dimension(n) => RegisterValue::Dimension(f(n)?),
RegisterValue::Glue(g) => RegisterValue::Glue(g.map(f)?),
})
}
fn scale(
value: RegisterValue,
numerator: i32,
denominator: i32,
) -> Result<RegisterValue, &'static str> {
if denominator == 0 {
return Err("division by zero in quantity expression");
}
map(value, |n| {
let product = n as i64 * numerator as i64;
let divisor = denominator as i64;
let rounded = (product.abs() + divisor.abs() / 2) / divisor.abs();
registers::bounded(if (product < 0) ^ (divisor < 0) {
-rounded
} else {
rounded
})
})
}
fn normalize(value: RegisterValue) -> RegisterValue {
match value {
RegisterValue::Glue(mut g) => {
if g.stretch.amount == 0 {
g.stretch.order = 0;
}
if g.shrink.amount == 0 {
g.shrink.order = 0;
}
RegisterValue::Glue(g)
}
_ => value,
}
}
@@ -0,0 +1,165 @@
use super::*;
impl Executor {
pub(super) fn font_dimension_target(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(FontId, i32), Error> {
let n = self.integer(files)?;
let font = self.font_identifier(files)?;
self.state
.fonts
.fontdimen(font, n)
.map_err(|e| self.error(e, self.current))?;
Ok((font, n))
}
pub(super) fn font_dimension(
&mut self,
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<i32, Error> {
if p == Primitive::Fontdimen {
let (font, n) = self.font_dimension_target(files)?;
return self
.state
.fonts
.fontdimen(font, n)
.map_err(|e| self.error(e, self.current));
}
let font = self.font_identifier(files)?;
let slot = self.integer(files)?;
let slot = u8::try_from(slot)
.map_err(|_| self.error("font character index must be in 0..255", self.current))?;
let Some(m) = self
.state
.fonts
.font(font)
.map_err(|e| self.error(e, self.current))?
.metrics()
else {
return Ok(0);
};
let c = char::from(slot);
Ok(match p {
Primitive::Fontcharwd => m.width(c),
Primitive::Fontcharht => m.height(c),
Primitive::Fontchardp => m.depth(c),
Primitive::Fontcharic => m.italic(c),
_ => unreachable!(),
} as i32)
}
pub(super) fn font_identifier(
&mut self,
files: &mut impl SourceProvider,
) -> Result<FontId, Error> {
let t = self.expanded_non_space(files)?.token;
let font = match self.meaning(&t) {
Meaning::Font(f) => f,
Meaning::Primitive(Primitive::Font) => {
self.reads.insert(Dependency::TextFont);
self.state.text_font()
}
Meaning::Primitive(
p @ (Primitive::Textfont | Primitive::Scriptfont | Primitive::Scriptscriptfont),
) => {
let family = self.integer(files)?;
if !(0..16).contains(&family) {
return self.fail("native math family must be in 0..15");
}
let size = match p {
Primitive::Textfont => 0,
Primitive::Scriptfont => 1,
_ => 2,
};
self.reads.insert(Dependency::MathFamily {
size,
family: family as u8,
});
self.state.math_font(size, family as u8)
}
_ => return self.fail("expected native font identifier"),
};
self.reads.insert(Dependency::FontResources);
Ok(font)
}
pub(super) fn missing_glyph(
&mut self,
font: FontId,
slot: u8,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let tracing = self.read_parameter(Parameter::Tracinglostchars).width();
let online = self.read_parameter(Parameter::Tracingonline).width();
let destination = if tracing <= 0 {
None
} else if tracing > 1 || online > 0 {
Some(WriteDestination::TerminalAndLog)
} else {
Some(WriteDestination::Log)
};
// TeX print_ASCII renders nonprinting bytes in ^^ notation. This is
// the requested slot, not a Unicode-to-font substitution.
self.reads.insert(Dependency::NewLineChar);
let printed = if u8::try_from(self.state.newlinechar).ok() == Some(slot) {
"\n".into()
} else {
match slot {
0..=31 => format!("^^{}", char::from(slot + 64)),
127 => "^^?".into(),
128..=255 => format!("^^{slot:02x}"),
_ => char::from(slot).to_string(),
}
};
let newline = u8::try_from(self.state.newlinechar).ok().map(char::from);
let literal = |s: &str| {
s.chars()
.map(|c| if Some(c) == newline { '\n' } else { c })
.collect::<String>()
};
let message = destination.map(|_| {
// print_ASCII expands a byte's canonical ^^ string with newlinechar
// temporarily disabled. Literal diagnostic strings do not disable it.
let head = literal(if tracing > 2 {
"! Missing character: There is no "
} else {
"Missing character: There is no "
});
let tail = literal(&if tracing > 2 {
format!(
" (\"{slot:X}) in font {}.",
self.state.fonts.font(font).expect("loaded font").name()
)
} else {
format!(
" in font {}!",
self.state.fonts.font(font).expect("loaded font").name()
)
});
format!("{head}{printed}{tail}")
});
self.events.push(Event::MissingGlyph(MissingGlyph {
font,
slot,
tracing,
destination,
message: message.clone(),
span,
}));
if let (Some(destination), Some(message)) = (destination, message) {
let output = if message.ends_with('\n') {
message.clone()
} else {
format!("{message}\n")
};
files
.observe_diagnostic(destination, &output)
.map_err(|e| self.error(e, span))?;
if tracing > 2 {
let mut error = self.error(message, span);
error.message_reported = true;
return Err(error);
}
}
Ok(())
}
}
@@ -0,0 +1,98 @@
use super::*;
impl Executor {
pub(super) fn patterns(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
if !self.state.is_initex() {
return self.fail("patterns can be loaded only in native INITEX");
}
if self.state.hyphenation.sealed {
return self.fail("too late for patterns after paragraph hyphenation began");
}
let language = super::super::hyphenation::normalize_language(
self.state.parameter(Parameter::Language).width(),
);
self.reads
.insert(Dependency::Parameter(Parameter::Language));
let open = self.expanded_non_space(files)?.token;
if !matches!(
self.meaning(&open),
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
) {
return self.fail("patterns requires a begin-group token");
}
let (mut letters, mut weights, mut digit) = (Vec::new(), vec![0], false);
loop {
let t = self.required_expanded(files)?.token;
match self.meaning(&t) {
Meaning::Character(TokenKind::Character(
_,
code @ (CatCode::Space | CatCode::EndGroup),
)) => {
if !letters.is_empty() {
// A boundary cannot carry a break score outside the word.
if letters[0] == 0 {
weights[0] = 0;
}
if letters.last() == Some(&0) {
*weights.last_mut().unwrap() = 0;
}
self.state
.hyphenation
.insert(language, &letters, &weights, self.limits.tokens)
.map_err(|e| self.error(e, t.span))?;
}
if code == CatCode::EndGroup {
break;
}
letters.clear();
weights.clear();
weights.push(0);
digit = false;
}
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => {
if !digit && c.is_ascii_digit() {
if letters.len() < 63 {
*weights.last_mut().unwrap() = c as u8 - b'0';
digit = true;
}
} else {
let c = if c == '.' {
0
} else {
self.reads.insert(Dependency::CaseCode(CaseCode::Lower, c));
let n = self.state.case_code(CaseCode::Lower, c);
if n == 0 {
return self.fail("nonletter with zero lccode in patterns");
}
n
};
if letters.len() < 63 {
letters.push(c);
weights.push(0);
digit = false;
}
}
}
_ => return self.fail("bad token in hyphenation patterns"),
}
}
Ok(())
}
pub(super) fn set_language(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
if self.paragraph.is_none() || !self.math.is_empty() {
return self.fail("setlanguage requires horizontal mode");
}
let n = self.integer(files)?;
let mut language = HyphenationLanguage::from_state(&self.state);
language.language = super::super::hyphenation::normalize_language(n);
self.paragraph
.as_mut()
.unwrap()
.set_language(language)
.map_err(|e| self.error(e, self.current))?;
self.reads
.insert(Dependency::Parameter(Parameter::Lefthyphenmin));
self.reads
.insert(Dependency::Parameter(Parameter::Righthyphenmin));
Ok(())
}
}
@@ -0,0 +1,546 @@
use super::super::context::Pseudo;
use super::*;
impl InputFrame {
fn exhausted_tokens(&self) -> bool {
match self {
Self::Tokens { tokens, cursor, .. } => *cursor == tokens.len(),
Self::Hook { tokens, cursor, .. } | Self::Argument { tokens, cursor, .. } => {
*cursor == tokens.len()
}
Self::Macro {
definition, cursor, ..
} => *cursor == definition.replacement.len(),
_ => false,
}
}
}
impl Executor {
pub(super) fn discard_exhausted_tokens(&mut self) {
while self.inputs.last().is_some_and(InputFrame::exhausted_tokens) {
self.inputs.pop();
}
}
pub(super) fn raw(
&mut self,
files: &mut impl SourceProvider,
) -> Result<Option<InputToken>, Error> {
enum Next {
Token(Option<InputToken>),
Argument(Arc<[Token]>, Span),
Error(Span, String),
Boundary,
EndSource { source: usize, trace: Option<bool> },
EofHook,
}
loop {
self.observe_resource_stacks();
let Some(input) = self.inputs.last_mut() else {
return Ok(None);
};
let next = match input {
InputFrame::Tokens { tokens, cursor, .. } => {
let t = tokens.get(*cursor).cloned();
if t.is_some() {
*cursor += 1;
}
Next::Token(t)
}
InputFrame::Macro {
definition,
arguments,
cursor,
call,
..
} => match definition.replacement.get(*cursor) {
Some(Replacement::Token(t)) => {
let mut t = t.clone();
t.invocation = Some(*call);
*cursor += 1;
Next::Token(Some(t.into()))
}
Some(Replacement::Parameter(n)) => {
*cursor += 1;
Next::Argument(arguments[*n].clone(), *call)
}
None => Next::Token(None),
},
InputFrame::Argument {
tokens,
cursor,
call,
} => {
let t = tokens.get(*cursor).cloned().map(|mut t| {
t.invocation = Some(*call);
t.into()
});
if t.is_some() {
*cursor += 1;
}
Next::Token(t)
}
InputFrame::Source {
source,
mouth,
eof_seen,
pseudo_trace,
..
} => match mouth.next(&self.state, &mut self.reads) {
Ok(Some(token)) => {
self.input_position = Some((*source, mouth.line_number()));
Next::Token(Some(token.into()))
}
Ok(None) => {
if self.state.profile() == Profile::EtexBootstrap
&& !*eof_seen
&& !mouth.forced_eof()
{
self.reads
.insert(Dependency::TokenParameter(TokenParameter::Everyeof));
if self
.state
.token_parameter(TokenParameter::Everyeof)
.is_some()
{
*eof_seen = true;
self.input_position = Some((*source, mouth.enter_eof_line()));
Next::EofHook
} else {
Next::EndSource {
source: *source,
trace: *pseudo_trace,
}
}
} else {
Next::EndSource {
source: *source,
trace: *pseudo_trace,
}
}
}
Err((span, text)) => Next::Error(span, text),
},
InputFrame::Hook { tokens, cursor, .. } => {
let t = tokens.get(*cursor).cloned().map(InputToken::from);
if t.is_some() {
*cursor += 1;
}
Next::Token(t)
}
InputFrame::Boundary => Next::Boundary,
};
match next {
Next::Token(Some(token)) => {
self.current = token.token.invocation.unwrap_or(token.token.span);
self.tick()?;
if self.alignment_raw(&token)? {
continue;
}
self.reject_outer(&token.token, token.frozen)?;
return Ok(Some(token));
}
Next::EofHook => self.push_mode_hook(TokenParameter::Everyeof)?,
Next::EndSource { source, trace } => {
self.warn_input_eof(files)?;
if let Some(traced) = trace {
self.pseudo_input_boundary(source, false, traced, files)?;
}
self.inputs.pop();
self.restore_input_position();
}
Next::Token(None) => {
self.inputs.pop();
self.restore_input_position();
}
Next::Argument(tokens, call) => {
if !tokens.is_empty() {
if self.inputs.len() >= self.limits.input_depth {
return self.fail("native input stack limit exceeded");
}
self.inputs.push(InputFrame::Argument {
tokens,
cursor: 0,
call,
});
}
}
Next::Error(span, text) => return Err(self.error(text, span)),
Next::Boundary => return Ok(None),
}
}
}
fn restore_input_position(&mut self) {
if let Some(position) = self.inputs.iter().rev().find_map(|frame| match frame {
InputFrame::Source { source, mouth, .. } => Some((*source, mouth.line_number())),
_ => None,
}) {
self.input_position = Some(position);
}
}
pub(super) fn pseudo_input_boundary(
&mut self,
source: usize,
opening: bool,
traced: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if traced {
self.diagnostic_bytes =
self.diagnostic_bytes
.saturating_add(if opening { 3 } else { 1 });
if self.diagnostic_bytes > self.limits.tokens {
return self.fail("native diagnostic output limit exceeded");
}
files
.observe_pseudo_input(opening)
.map_err(|error| self.error(error, self.current))?;
}
self.events.push(Event::PseudoInput {
source,
opening,
traced,
});
Ok(())
}
pub(super) fn scan_tokens_input(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let origin = self.current;
let tokens = self.scan_group(files)?;
let rendered = self.token_list_text(&tokens);
let profile = self.state.input_profile();
let bytes = match profile {
InputProfile::UnicodeScalar => rendered.into_bytes(),
InputProfile::TeX8Bit => rendered
.chars()
.map(|c| {
u8::try_from(c as u32).map_err(|_| {
self.error("scantokens character exceeds byte profile", origin)
})
})
.collect::<Result<Vec<_>, _>>()?,
};
if bytes.len() > self.limits.tokens || self.inputs.len() >= self.limits.input_depth {
return self.fail("native scantokens input capacity exceeded");
}
self.reads.insert(Dependency::NewLineChar);
let separator = u8::try_from(self.state.newlinechar).ok().map(char::from);
let traced = self.read_parameter(Parameter::Tracingscantokens).width() > 0;
let source = self.sources.len();
let mouth = Mouth::generated(source, bytes.clone(), profile, separator);
self.sources.push(SourceFile {
name: "<scantokens>".into(),
data: bytes,
});
self.generated_inputs
.insert(source, GeneratedInput { origin, separator });
self.reads.insert(Dependency::Source(source));
self.inputs.push(InputFrame::Source {
source,
mouth,
eof_seen: false,
pseudo_trace: Some(traced),
group_boundary: self.state.group_depth(),
conditional_boundary: self.conditionals.len(),
});
self.input_position = Some((source, 0));
self.pseudo_input_boundary(source, true, traced, files)
}
fn context_token(&self, out: &mut Pseudo, token: &TokenKind, reads: &mut BTreeSet<Dependency>) {
match token {
TokenKind::Character(c, code) => {
out.character(*c);
if *code == CatCode::Parameter {
out.character(*c);
}
}
TokenKind::Command(name) => self.context_command(out, name, reads),
}
}
fn context_command(
&self,
out: &mut Pseudo,
name: &CommandName,
reads: &mut BTreeSet<Dependency>,
) {
match name {
CommandName::FrozenRelax => {
if let Ok(escape) = u8::try_from(self.state.escapechar) {
out.character(char::from(escape));
}
out.text("relax ");
}
CommandName::Font(font) => {
reads.insert(Dependency::FontResources);
if let Ok(escape) = u8::try_from(self.state.escapechar) {
out.character(char::from(escape));
}
out.text(&self.font_token_name(*font));
out.push(' ');
}
CommandName::Active(c) => out.character(*c),
CommandName::Control(name) => {
if let Ok(escape) = u8::try_from(self.state.escapechar) {
out.character(char::from(escape));
}
if name.is_empty() {
out.text("csname");
if let Ok(escape) = u8::try_from(self.state.escapechar) {
out.character(char::from(escape));
}
out.text("endcsname ");
} else {
if name.chars().count() == 1 {
reads.insert(Dependency::CatCode(name.chars().next().unwrap()));
}
out.text(name);
if name.chars().count() > 1
|| name
.chars()
.next()
.is_some_and(|c| self.state.catcode(c) == CatCode::Letter)
{
out.push(' ');
}
}
}
}
}
pub(super) fn input_context(&self) -> InputContext {
let mut frames = Vec::new();
let mut reads = BTreeSet::from([
Dependency::Parameter(Parameter::Errorcontextlines),
Dependency::EscapeChar,
Dependency::NewLineChar,
Dependency::EndLineChar,
]);
let mut top = true;
for frame in self.inputs.iter().rev() {
let mut out = Pseudo::new();
let (kind, label) = match frame {
InputFrame::Boundary => continue,
InputFrame::Hook {
parameter,
tokens,
cursor,
} => {
reads.insert(Dependency::TokenParameter(*parameter));
for (i, t) in tokens.iter().enumerate() {
if i == *cursor {
out.split();
}
self.context_token(&mut out, &t.kind, &mut reads);
}
if *cursor == tokens.len() {
out.split();
}
(
ContextKind::Hook(*parameter),
format!("<{}> ", parameter.name()),
)
}
InputFrame::Source { source, mouth, .. } => {
mouth.context(&mut out, self.state.endlinechar);
reads.insert(Dependency::Source(*source));
(
ContextKind::Source {
source: *source,
name: self.sources[*source].name.clone(),
line: mouth.line_number(),
},
format!("l.{} ", mouth.line_number()),
)
}
InputFrame::Tokens {
tokens,
cursor,
kind,
} => {
let exhausted = *cursor == tokens.len();
if matches!(kind, TokenInputKind::BackedUp) && exhausted && !top {
continue;
}
for (i, t) in tokens.iter().enumerate() {
if i == *cursor {
out.split();
}
self.context_token(&mut out, &t.token.kind, &mut reads);
}
if exhausted {
out.split();
}
match kind {
TokenInputKind::Inserted => {
(ContextKind::Inserted, "<inserted text> ".into())
}
TokenInputKind::Write => (ContextKind::Write, "<write> ".into()),
TokenInputKind::Mark => (ContextKind::Mark, "<mark> ".into()),
TokenInputKind::Output => (ContextKind::Output, "<output> ".into()),
TokenInputKind::BackedUp => (
ContextKind::BackedUp { exhausted },
if exhausted {
"<recently read> "
} else {
"<to be read again> "
}
.into(),
),
}
}
InputFrame::Argument { tokens, cursor, .. } => {
for (i, t) in tokens.iter().enumerate() {
if i == *cursor {
out.split();
}
self.context_token(&mut out, &t.kind, &mut reads);
}
if *cursor == tokens.len() {
out.split();
}
(ContextKind::Argument, "<argument> ".into())
}
InputFrame::Macro {
definition,
name,
cursor,
..
} => {
for t in &definition.prefix {
self.context_token(&mut out, t, &mut reads);
}
for (n, delimiter) in definition.parameters.iter().enumerate() {
out.text(&format!("{}{}", definition.parameter_chars[n], n + 1));
for t in delimiter {
self.context_token(&mut out, t, &mut reads);
}
}
out.text("->");
for (i, t) in definition.replacement.iter().enumerate() {
if i == *cursor {
out.split();
}
match t {
Replacement::Token(t) => {
self.context_token(&mut out, &t.kind, &mut reads)
}
Replacement::Parameter(n) => out.text(&format!(
"{}{}",
definition.parameter_chars.last().copied().unwrap_or('#'),
n + 1
)),
}
}
if *cursor == definition.replacement.len() {
out.split();
}
let label = match name {
CommandName::Font(font) => {
reads.insert(Dependency::FontResources);
let escape = u8::try_from(self.state.escapechar)
.ok()
.map(char::from)
.map(|c| c.to_string())
.unwrap_or_default();
format!("{escape}{} ", self.font_token_name(*font))
}
CommandName::FrozenRelax => unreachable!("frozen relax is not a macro"),
CommandName::Active(c) => c.to_string(),
CommandName::Control(name) => {
if name.chars().count() == 1 {
reads.insert(Dependency::CatCode(name.chars().next().unwrap()));
}
let escape = u8::try_from(self.state.escapechar)
.ok()
.map(char::from)
.map(|c| c.to_string())
.unwrap_or_default();
let space = name.chars().count() > 1
|| name
.chars()
.next()
.is_some_and(|c| self.state.catcode(c) == CatCode::Letter);
if name.is_empty() {
format!("{escape}csname{escape}endcsname ")
} else {
format!("{escape}{name}{}", if space { " " } else { "" })
}
}
};
(ContextKind::Macro(name.clone()), label)
}
};
let bottom = matches!(kind, ContextKind::Source { .. });
frames.push(out.finish(&label, kind, self.state.newlinechar));
top = false;
if bottom {
break;
}
}
let limit = self.state.parameter(Parameter::Errorcontextlines).width();
let mut text = String::new();
let mut column = 0;
let mut shown = -1;
for (i, frame) in frames.iter().enumerate() {
if i == 0 || matches!(frame.kind, ContextKind::Source { .. }) || shown < limit {
if i != 0 && (column != 0 || matches!(frame.kind, ContextKind::Macro(_))) {
text.push('\n');
column = 0;
}
for c in frame.label.chars() {
if c as i32 == self.state.newlinechar {
text.push('\n');
column = 0;
} else {
for c in super::super::context::encoded_character(c).chars() {
context_char(&mut text, &mut column, c, -1);
}
}
}
for c in frame.before.chars() {
context_char(&mut text, &mut column, c, self.state.newlinechar);
}
text.push('\n');
column = 0;
for c in frame.second.chars() {
context_char(&mut text, &mut column, c, self.state.newlinechar);
}
shown += 1;
} else if shown == limit {
if column != 0 {
text.push('\n');
column = 0;
}
for c in "...".chars() {
context_char(&mut text, &mut column, c, self.state.newlinechar);
}
shown += 1;
}
}
if !frames.is_empty() {
text.push('\n');
}
InputContext {
frames,
text,
reads,
}
}
}
fn context_char(out: &mut String, column: &mut usize, c: char, newline: i32) {
if c as i32 == newline {
out.push('\n');
*column = 0;
} else {
out.push(c);
*column += 1;
if *column == 79 {
out.push('\n');
*column = 0;
}
}
}
@@ -0,0 +1,218 @@
//! Queries and deletion operate on the current owned list, never its drawing.
use super::*;
#[derive(Clone, Copy)]
enum Tail {
Other(i32),
Glue(Glue, bool),
Kern(i32),
Penalty(i32),
}
impl Tail {
fn list(node: super::super::boxes::TailNodeRef<'_>) -> Self {
match node {
super::super::boxes::TailNodeRef::Vertical(n) => Self::vertical(n),
super::super::boxes::TailNodeRef::Text(n) => Self::text(n),
}
}
fn text(node: &TextNode) -> Self {
match node {
TextNode::Glue(g) | TextNode::NamedGlue(g, _) => Self::Glue(*g, false),
TextNode::Kern { width, .. } => Self::Kern(*width),
TextNode::Penalty(n) => Self::Penalty(*n),
TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }),
TextNode::MathChar(_) => Self::Other(0),
TextNode::Box(b) => Self::Other(b.native_box.as_ref().map_or(1, |b| {
if b.kind.is_unset() {
14
} else if b.kind == BoxKind::Horizontal {
1
} else {
2
}
})),
TextNode::Indent(_) => Self::Other(1),
TextNode::Rule(_) => Self::Other(3),
TextNode::Mark(_) => Self::Other(5),
TextNode::Adjustment(_) => Self::Other(6),
TextNode::Insertion(_) => Self::Other(4),
TextNode::Discretionary { .. } => Self::Other(8),
TextNode::Language(_) | TextNode::Output(_) => Self::Other(9),
TextNode::MathBoundary { .. } => Self::Other(10),
}
}
fn vertical(node: &NativeVerticalNode) -> Self {
match node {
NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => {
Self::Glue(*g, false)
}
NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => Self::Kern(*n),
NativeVerticalNode::Penalty(n) => Self::Penalty(*n),
_ => Self::Other(node.node_type()),
}
}
fn math(node: &MathNode) -> Self {
match node {
MathNode::Glue(g) => Self::Glue(*g, true),
MathNode::ExplicitSpace(g, _) => Self::Glue(*g, false),
MathNode::Kern { amount, .. } => Self::Kern(*amount),
MathNode::Penalty(n) => Self::Penalty(*n),
MathNode::Rule(_) => Self::Other(3),
MathNode::Mark(_) => Self::Other(5),
MathNode::Adjustment(_) => Self::Other(6),
MathNode::Insertion(_) => Self::Other(4),
MathNode::Discretionary(_) => Self::Other(8),
MathNode::Output(_) => Self::Other(9),
// e-TeX maps every node above unset_node (including styles and
// all noads) to unset_node + 2, rather than exposing raw tags.
MathNode::Noad(_)
| MathNode::Delimiter { .. }
| MathNode::Style(_)
| MathNode::Choice(_)
| MathNode::Fraction { .. } => Self::Other(15),
}
}
fn node_type(self) -> i32 {
match self {
Self::Other(n) => n,
Self::Glue(..) => 11,
Self::Kern(_) => 12,
Self::Penalty(_) => 13,
}
}
fn matches(self, p: Primitive) -> bool {
matches!(
(self, p),
(Self::Glue(..), Primitive::Unskip)
| (Self::Kern(_), Primitive::Unkern)
| (Self::Penalty(_), Primitive::Unpenalty)
)
}
}
impl Executor {
pub(super) fn last_quantity(&mut self, p: Primitive) -> (RegisterValue, RegisterKind) {
self.reads.insert(Dependency::ParagraphMode);
// write_out uses mode zero: even a nonempty current list is hidden
// from all last-item queries while expanding an immediate/late write.
if self.writing {
return Self::tail_quantity(p, None);
}
let tail = if let Some(b) = self.math.last() {
self.reads.insert(Dependency::MathState);
b.nodes.last().map(Tail::math)
} else if let Some(b) = &self.paragraph {
self.reads.insert(Dependency::BoxPackState);
if b.has_unpacked_text() {
Some(Tail::Other(0))
} else {
b.nodes.last().map(Tail::text)
}
} else {
self.reads.insert(Dependency::VerticalState);
let tail = self.vertical.tail_ref().map(Tail::list);
if tail.is_none() && self.outer_vertical() {
if let Some(page) = &self.native_page {
self.reads.insert(Dependency::PageState);
if let Some(node) = page.contributions.back() {
return Self::tail_quantity(p, Some(Tail::vertical(node)));
}
return match p {
Primitive::Lastskip => (
RegisterValue::Glue(page.last_glue.unwrap_or_default()),
RegisterKind::Skip,
),
Primitive::Lastkern => (
RegisterValue::Dimension(page.last_kern),
RegisterKind::Dimen,
),
Primitive::Lastnodetype => (
RegisterValue::Dimension(page.last_node_type.unwrap_or(-1)),
RegisterKind::Dimen,
),
_ => (
RegisterValue::Dimension(page.last_penalty),
RegisterKind::Dimen,
),
};
}
}
tail
};
Self::tail_quantity(p, tail)
}
fn tail_quantity(p: Primitive, tail: Option<Tail>) -> (RegisterValue, RegisterKind) {
match (p, tail) {
(Primitive::Lastnodetype, tail) => (
RegisterValue::Dimension(tail.map_or(-1, Tail::node_type)),
RegisterKind::Dimen,
),
(Primitive::Lastskip, Some(Tail::Glue(g, mu))) => (
RegisterValue::Glue(g),
if mu {
RegisterKind::Muskip
} else {
RegisterKind::Skip
},
),
(Primitive::Lastskip, _) => (RegisterValue::Glue(Glue::default()), RegisterKind::Skip),
(Primitive::Lastkern, Some(Tail::Kern(n)))
| (Primitive::Lastpenalty, Some(Tail::Penalty(n))) => {
(RegisterValue::Dimension(n), RegisterKind::Dimen)
}
_ => (RegisterValue::Dimension(0), RegisterKind::Dimen),
}
}
pub(super) fn delete_last(&mut self, p: Primitive) -> Result<(), Error> {
self.reads.insert(Dependency::ParagraphMode);
if self.math.is_empty()
&& self.paragraph.is_none()
&& self.outer_vertical()
&& self.native_page.is_none()
{
return self.fail("outer list deletion requires native page ownership");
}
if let Some(b) = self.math.last_mut() {
self.reads.insert(Dependency::MathState);
if b.nodes.last().is_some_and(|n| Tail::math(n).matches(p)) {
b.nodes.pop();
}
} else if let Some(b) = self.paragraph.as_mut() {
self.reads.insert(Dependency::BoxPackState);
// TeX cannot unlink a node belonging to a discretionary's
// unbroken replacement list: its replacement count must stay valid.
let protected = b.nodes.iter().enumerate().any(|(i, n)| {
matches!(n, TextNode::Discretionary { replacement_count, .. }
if *replacement_count > 0 && i + usize::from(*replacement_count) + 1 == b.nodes.len())
});
if !protected && b.nodes.last().is_some_and(|n| Tail::text(n).matches(p)) {
b.nodes.pop();
}
} else {
self.reads.insert(Dependency::VerticalState);
if self
.vertical
.tail_ref()
.is_some_and(|n| Tail::list(n).matches(p))
{
self.vertical
.remove_tail()
.map_err(|e| self.error(e, self.current))?;
} else if self.vertical.nodes.is_empty() && self.outer_vertical() {
if let Some(page) = &mut self.native_page {
self.reads.insert(Dependency::PageState);
if let Some(node) = page.contributions.back() {
if Tail::vertical(node).matches(p) {
page.contributions.pop_back();
}
} else if p != Primitive::Unskip || page.last_glue.is_some() {
return self.fail("cannot remove a node from the native current page");
}
}
}
}
Ok(())
}
}
@@ -0,0 +1,116 @@
use super::*;
impl Executor {
fn mark_class(&mut self, files: &mut impl SourceProvider) -> Result<u16, Error> {
let n = self.integer(files)?;
if !(0..=32767).contains(&n) {
return self.fail("native mark class must be in 0..32767");
}
Ok(n as u16)
}
pub(super) fn make_mark(
&mut self,
p: Primitive,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let class = if p == Primitive::Marks {
self.mark_class(files)?
} else {
0
};
let tokens = self.scan_expanded_group(files)?;
self.box_nodes_created = self.box_nodes_created.saturating_add(1 + tokens.len());
if self.box_nodes_created > self.limits.tokens {
return self.fail("native mark token/node capacity exceeded");
}
let mark = NativeMark {
class,
tokens: tokens.into(),
span,
};
if let Some(math) = self.math.last_mut() {
math.nodes.push(MathNode::Mark(mark));
} else if let Some(paragraph) = self.paragraph.as_mut() {
paragraph.nodes.push(TextNode::Mark(mark));
} else {
let start = self.vertical.nodes.len();
self.vertical.push(NativeVerticalNode::Mark(mark));
self.emit_vertical(start);
}
Ok(())
}
pub(super) fn expand_split_mark(
&mut self,
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use Primitive::*;
let class = if matches!(
p,
Splitfirstmarks | Splitbotmarks | Topmarks | Firstmarks | Botmarks
) {
self.mark_class(files)?
} else {
0
};
if matches!(
p,
Topmark | Firstmark | Botmark | Topmarks | Firstmarks | Botmarks
) {
self.native_page_mut()?;
self.reads.insert(Dependency::PageMarks(class));
let tokens = self
.state
.page_marks
.get(&class)
.and_then(|m| match p {
Topmark | Topmarks => m.top.as_ref(),
Firstmark | Firstmarks => m.first.as_ref(),
_ => m.bottom.as_ref(),
})
.map_or_else(Vec::new, |t| {
t.iter().cloned().map(InputToken::from).collect()
});
return self.push_kind(tokens, TokenInputKind::Mark);
}
self.reads.insert(Dependency::SplitMarks(class));
let tokens = self
.state
.split_marks
.get(&class)
.map(|marks| {
if matches!(p, Splitfirstmark | Splitfirstmarks) {
&marks.first
} else {
&marks.bottom
}
})
.map_or_else(Vec::new, |t| {
t.iter().cloned().map(InputToken::from).collect()
});
self.push_kind(tokens, TokenInputKind::Mark)
}
pub(super) fn collect_split_marks(
&mut self,
nodes: &[NativeVerticalNode],
) -> Result<(), Error> {
for n in nodes {
self.tick()?;
if let NativeVerticalNode::Mark(m) = n {
self.state
.split_marks
.entry(m.class)
.and_modify(|s| s.bottom = m.tokens.clone())
.or_insert_with(|| SplitMarks {
first: m.tokens.clone(),
bottom: m.tokens.clone(),
});
}
}
Ok(())
}
}
@@ -0,0 +1,817 @@
use super::super::boxes::{PackSpec, hpack};
use super::super::math::{self, FieldTarget, MathBuilder, MathGroupTarget};
use super::*;
use crate::math_engine_tex::MathStyle;
use crate::provenance::PaintSource;
impl Executor {
pub(super) fn accept_box_math_field(&mut self, b: NativeBox) -> Result<(), Error> {
if self.math.last().unwrap().pending.is_some() {
return self.fail("expected a grouped native math box field");
}
self.new_noad(NoadClass::Ord, MathField::Box(Box::new(b)), self.current);
Ok(())
}
fn scan_delimiter(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(super::super::math::Delimiter, PaintSource), Error> {
let (code, origin) = loop {
let t = self.expanded_non_space(files)?.token;
match self.meaning(&t) {
Meaning::Primitive(Primitive::Relax) => continue,
Meaning::Primitive(Primitive::Delimiter) => {
let n = self.integer(files)?;
if !(0..1 << 27).contains(&n) {
return self.fail("delimiter must be in 0..134217727");
}
break (n, TokenOrigin::from(&t));
}
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => {
let c = u8::try_from(c as u32)
.map_err(|_| self.error("delimiter character must be in 0..255", t.span))?;
self.reads.insert(Dependency::DelCode(c));
break (self.state.delcode(c), TokenOrigin::from(&t));
}
_ => return self.fail("expected native delimiter character or delimiter code"),
}
};
if code < 0 {
return self.fail("missing native delimiter: character has negative delcode");
}
Ok((
super::super::math::Delimiter::from_code(code as u32),
PaintSource::token(origin),
))
}
fn left_right(
&mut self,
opening: bool,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if opening {
if self.math.len() >= self.limits.input_depth.min(32) {
return self.fail("native math nesting capacity exceeded");
}
let left = self.scan_delimiter(files)?;
self.begin_group(GroupKind::MathLeft, files)?;
let mut b = MathBuilder::new(self.state.group_depth(), None, span);
b.left = Some(left);
self.math.push(b);
} else {
let b = self.math.last().unwrap();
if b.left.is_none() || b.depth != self.state.group_depth() {
return self.fail("unmatched native right delimiter");
}
let (right, source) = self.scan_delimiter(files)?;
let b = self.math.pop().unwrap();
let span = b.span;
let mut nodes = b.finish();
nodes.push(MathNode::Delimiter {
value: right,
opening: false,
source,
});
self.finish_group(GroupKind::MathLeft, span, files)?;
self.new_noad(NoadClass::Inner, MathField::List(nodes), span);
}
Ok(())
}
pub(super) fn math_font_assignment(
&mut self,
p: Primitive,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let family = self.integer(files)?;
if !(0..16).contains(&family) {
return self.fail("native math family must be in 0..15");
};
self.optional_equals(files)?;
let t = self.expanded_non_space(files)?.token;
let Meaning::Font(font) = self.meaning(&t) else {
return self.fail("expected actual native font selector");
};
let size = match p {
Primitive::Textfont => 0,
Primitive::Scriptfont => 1,
_ => 2,
};
let family = family as u8;
let equivalent = self.state.math_font(size, family) == font;
self.assign_equivalence(
Key::Mathfont(size, family),
global,
equivalent,
files,
|state| {
state.assign_mathfont(size, family, font, global);
},
)?;
Ok(())
}
fn math_code_char(
&mut self,
c: char,
token: &Token,
) -> Result<Option<(NoadClass, MathChar)>, Error> {
let c = u8::try_from(c as u32).map_err(|_| {
self.error(
"native 8-bit mathcode requires a byte character",
token.span,
)
})?;
self.reads.insert(Dependency::MathCode(c));
let code = self.state.mathcode(c);
if code == 32768 {
let mut t = token.clone();
t.kind = TokenKind::Command(CommandName::Active(c as char));
self.unread(t.into())?;
return Ok(None);
}
Ok(Some(self.decode_math_char(code)))
}
fn decode_math_char(&mut self, code: u16) -> (NoadClass, MathChar) {
let raw = (code >> 12) as u8;
let fam = self.read_parameter(Parameter::Fam).width();
(
NoadClass::from_code(if raw == 7 { 0 } else { raw }),
MathChar {
family: if raw == 7 && (0..16).contains(&fam) {
fam as u8
} else {
((code >> 8) & 15) as u8
},
slot: code as u8,
},
)
}
pub(super) fn start_math(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
// vmode math_shift first starts an indented paragraph in TeX.
if self.paragraph.is_none() {
self.begin_paragraph(token.span, true)?;
}
// init_math peeks raw, so ifmmode immediately after $ sees math mode.
let next = self.raw(files)?;
if !self.restricted()
&& next.as_ref().is_some_and(|t| {
matches!(
self.meaning(&t.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
)
})
{
return self.start_display(token.span, files);
};
if let Some(t) = next {
self.unread(t)?;
}
self.finish_text(true)?;
self.begin_group(GroupKind::MathShift, files)?;
self.assign_traced_parameter(Parameter::Fam, ParameterValue::Integer(-1), false, files)?;
self.math
.push(MathBuilder::new(self.state.group_depth(), None, token.span));
self.push_mode_hook(TokenParameter::Everymath)
}
fn new_noad(&mut self, class: NoadClass, nucleus: MathField, span: Span) {
self.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::Noad(Noad {
source: NoadSource::default(),
class,
limits: OperatorLimits::Display,
accent: None,
rule: None,
vcenter: false,
nucleus,
sub: None,
sup: None,
span,
}));
}
fn accept_math_field(&mut self, value: MathField, class: NoadClass, origin: TokenOrigin) {
let source = FieldSource::token(origin);
let b = self.math.last_mut().unwrap();
if let Some(target) = b.pending.take() {
math::put_field(&mut b.nodes, target, value, source)
} else {
self.new_noad(class, value, origin.span);
let Some(MathNode::Noad(n)) = self.math.last_mut().unwrap().nodes.last_mut() else {
unreachable!()
};
n.source.nucleus = source;
}
}
fn math_group(&mut self, span: Span, files: &mut impl SourceProvider) -> Result<(), Error> {
if self.math.len() >= self.limits.input_depth.min(32) {
return self.fail("native math nesting capacity exceeded");
};
let target = if let Some(p) = self.math.last_mut().unwrap().pending.take() {
p
} else {
self.new_noad(NoadClass::Ord, MathField::Empty, span);
FieldTarget::Nucleus(self.math.last().unwrap().nodes.len() - 1)
};
self.begin_group(GroupKind::MathGroup, files)?;
self.math.push(MathBuilder::new(
self.state.group_depth(),
Some(MathGroupTarget::Field(target)),
span,
));
Ok(())
}
fn start_math_choice(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let parent = self.math.last_mut().unwrap();
let node = parent.nodes.len();
parent.nodes.push(MathNode::Choice(Box::default()));
self.open_math_choice_branch(node, 0, span, files)
}
fn open_math_choice_branch(
&mut self,
node: usize,
branch: usize,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.math.len() >= self.limits.input_depth.min(32) {
return self.fail("native math nesting capacity exceeded");
}
self.begin_group(GroupKind::MathChoice, files)?;
self.math.push(MathBuilder::new(
self.state.group_depth(),
Some(MathGroupTarget::Choice { node, branch }),
span,
));
loop {
let open = self.expanded_non_space(files)?;
let meaning = self.meaning(&open.token);
if matches!(meaning, Meaning::Primitive(Primitive::Relax))
|| Self::suppresses_meaning(&open, &meaning)
{
continue;
}
if matches!(
meaning,
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
) {
return Ok(());
}
return self.fail("expected opening brace for native math choice");
}
}
fn close_math_group(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let b = self.math.last().unwrap();
let Some(target) = b.target else {
return self.fail("unbalanced native math group");
};
if self.state.group_depth() != b.depth || b.left.is_some() {
return self.fail("unbalanced native math group");
}
if b.pending.is_some() {
return self.fail("missing native math field");
}
match target {
MathGroupTarget::Field(target) => {
let b = self.math.pop().unwrap();
let (value, source) = math::field(b.finish());
self.finish_group(GroupKind::MathGroup, span, files)?;
math::put_field(
&mut self.math.last_mut().unwrap().nodes,
target,
value,
source,
);
}
MathGroupTarget::Choice { node, branch } => {
self.finish_group(GroupKind::MathChoice, span, files)?;
let b = self.math.pop().unwrap();
let origin = b.span;
let MathNode::Choice(branches) = &mut self.math.last_mut().unwrap().nodes[node]
else {
unreachable!("math choice stays owned by the parent list during scanning");
};
branches[branch] = b.finish();
if branch + 1 < branches.len() {
self.open_math_choice_branch(node, branch + 1, origin, files)?;
}
}
}
Ok(())
}
fn close_math(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
let side = self.display.as_ref().and_then(|frame| frame.number_side);
let layers = if side.is_some() { 2 } else { 1 };
if self.math.len() != layers || self.state.group_depth() != self.math[layers - 1].depth {
return self.fail("math shift closes an unfinished native math group");
}
let mut b = self.math.pop().unwrap();
let display = self.display.is_some();
if display {
let close = self.required_expanded(files)?;
if !matches!(
self.meaning(&close.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
) {
return self.fail("native display math must end with a second math shift");
}
}
let number = if let Some(side) = side {
let tag = self.convert_math(b, MathStyle::Text, false, files)?;
let mut box_ = hpack(
tag.horizontal.clone(),
PackSpec::Natural,
tag.span,
&self.state,
)
.map_err(|e| self.error(e, tag.span))?;
box_.display = true;
self.state.last_badness = box_.badness;
let span = tag.span;
self.events.push(Event::BuiltMath(Box::new(tag)));
self.finish_group(GroupKind::MathShift, span, files)?;
b = self.math.pop().unwrap();
Some(display::EquationNumber { side, box_ })
} else {
None
};
let style = if display {
MathStyle::Display
} else {
MathStyle::Text
};
let enabled = !display && !self.restricted();
let material = self.convert_math(b, style, enabled, files)?;
let span = material.span;
if display {
let horizontal = material.horizontal.clone();
self.events.push(Event::BuiltMath(Box::new(material)));
return self.finish_display(&horizontal, number, span, files);
}
let surround = self.read_parameter(Parameter::Mathsurround).width();
let p = self.paragraph.as_mut().unwrap();
p.nodes.push(TextNode::MathBoundary {
width: surround,
after: false,
});
p.nodes.extend(material.horizontal.iter().cloned());
p.nodes.push(TextNode::MathBoundary {
width: surround,
after: true,
});
p.space_factor = 1000;
self.events.push(Event::BuiltMath(Box::new(material)));
self.finish_group(GroupKind::MathShift, span, files)?;
Ok(())
}
fn convert_math(
&mut self,
b: MathBuilder,
style: MathStyle,
enabled: bool,
files: &mut impl SourceProvider,
) -> Result<NativeMath, Error> {
let span = b.span;
let nodes = b.finish();
self.reads.insert(Dependency::FontResources);
for p in [
Parameter::Delimiterfactor,
Parameter::Delimitershortfall,
Parameter::Nulldelimiterspace,
] {
self.reads.insert(Dependency::Parameter(p));
}
let converter = math::Converter {
state: &self.state,
horizontal_packs: std::cell::Cell::new(0),
last_pack_badness: std::cell::Cell::new(None),
missing: std::cell::RefCell::new(Vec::new()),
delimiter_glyphs: std::cell::Cell::new(0),
delimiter_glyph_limit: self.limits.tokens,
steps: std::cell::Cell::new(self.steps),
step_limit: self.limits.steps,
node_limit: self.limits.tokens,
};
converter.validate().map_err(|e| self.error(e, span))?;
let converted = converter.convert(&nodes, style, enabled);
let missing = converter.missing.take();
let horizontal_packs = converter.horizontal_packs.get();
let last_pack_badness = converter.last_pack_badness.get();
self.steps = converter.steps.get();
for (font, slot) in missing {
self.missing_glyph(font, slot, span, files)?;
}
let (horizontal, effective_classes, nodes) = converted.map_err(|e| self.error(e, span))?;
if let Some(badness) = last_pack_badness {
self.state.last_badness = badness;
}
for size in 0..3 {
for family in 0..16 {
self.reads.insert(Dependency::MathFamily { size, family });
}
}
let parameters = Parameter::ALL
.iter()
.map(|p| (*p, self.state.parameter(*p)))
.collect();
Ok(NativeMath {
noads: nodes,
effective_classes,
parameters,
horizontal,
penalties_enabled: enabled,
display: style == MathStyle::Display,
horizontal_packs,
last_pack_badness,
span,
})
}
pub(super) fn math_token(
&mut self,
token: &Token,
meaning: &Meaning,
files: &mut impl SourceProvider,
) -> Result<bool, Error> {
use Primitive::*;
self.reads.insert(Dependency::MathState);
if !self.math.is_empty() {
self.math_tokens_processed += 1;
if self.math_tokens_processed > self.limits.tokens {
return self.fail("native math token/list capacity exceeded");
}
}
if self.math.is_empty() {
if matches!(meaning, Meaning::Primitive(Eqno | Leqno)) {
return self.fail("native equation number requires outer display math");
}
if matches!(meaning, Meaning::Primitive(Mathchoice)) {
return self.fail("native math choice requires math mode");
}
if matches!(
meaning,
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
) {
self.start_math(token, files)?;
return Ok(true);
}
return Ok(false);
}
if self.math.last().unwrap().pending.is_some() {
match meaning {
Meaning::Character(TokenKind::Character(_, CatCode::Space))
| Meaning::Primitive(Relax) => return Ok(true),
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup)) => {
self.math_group(token.span, files)?;
return Ok(true);
}
Meaning::Character(TokenKind::Character(_, CatCode::Letter | CatCode::Other))
| Meaning::CharGiven(_)
| Meaning::MathCharGiven(_)
| Meaning::Primitive(Mathchar | Char | Delimiter) => {}
_ => return self.fail("expected a native math field character or group"),
}
}
match meaning {
Meaning::Character(TokenKind::Character(c, code)) => match code {
CatCode::MathShift => self.close_math(files)?,
CatCode::Space => {}
CatCode::BeginGroup => self.math_group(token.span, files)?,
CatCode::EndGroup => self.close_math_group(token.span, files)?,
CatCode::Superscript | CatCode::Subscript => {
let b = self.math.last_mut().unwrap();
if !matches!(b.nodes.last(), Some(MathNode::Noad(_))) {
self.new_noad(NoadClass::Ord, MathField::Empty, token.span)
}
let b = self.math.last_mut().unwrap();
let i = b.nodes.len() - 1;
let MathNode::Noad(n) = &b.nodes[i] else {
unreachable!()
};
let sup = *code == CatCode::Superscript;
if if sup {
n.sup.is_some()
} else {
n.sub.is_some()
} {
return self.fail("double native math script");
};
b.pending = Some(if sup {
FieldTarget::Sup(i)
} else {
FieldTarget::Sub(i)
});
}
CatCode::Letter | CatCode::Other => {
if let Some((class, c)) = self.math_code_char(*c, token)? {
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
_ => return self.fail("unsupported native math category"),
},
Meaning::CharGiven(c) => {
if let Some((class, c)) = self.math_code_char(*c as char, token)? {
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
Meaning::MathCharGiven(code) => {
let (class, c) = self.decode_math_char(*code);
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
Meaning::Primitive(p) => match p {
Halign => self.start_alignment(*p, token.span, files)?,
Mathchoice => self.start_math_choice(token.span, files)?,
Eqno | Leqno => self.start_equation_number(
if *p == Eqno {
display::EquationSide::Right
} else {
display::EquationSide::Left
},
token.span,
files,
)?,
Vcenter => self.box_command(*p, boxes::Destination::Append, token.span, files)?,
Hbox | Vbox | Vtop | Box | Copy | Setbox | Wd | Ht | Dp | Lastbox | Raise
| Lower | Vsplit | Mark | Marks | Vadjust | Insert | Shipout | Openout
| Closeout | Write | Pdfcolorstack | Pdfsave | Pdfsetmatrix | Pdfrestore
| Ignorespaces | Unskip | Unkern | Unpenalty => {
return Ok(false);
}
Unhbox | Unhcopy => {
self.unpackage(*p, files)?;
}
Vrule => {
let r = self.scan_rule(false, TokenOrigin::from(token), files)?;
self.math.last_mut().unwrap().nodes.push(MathNode::Rule(r));
}
Left | Right => self.left_right(*p == Left, token.span, files)?,
Mathchar | Char | Delimiter => {
let n = self.integer(files)?;
if *p == Char {
let c = u8::try_from(n)
.map_err(|_| self.error("char must be in 0..255", token.span))?;
if let Some((class, c)) = self.math_code_char(c as char, token)? {
self.accept_math_field(
MathField::Char(c),
class,
TokenOrigin::from(token),
)
}
} else if *p == Delimiter {
if !(0..1 << 27).contains(&n) {
return self.fail("delimiter must be in 0..134217727");
}
let (class, c) = self.decode_math_char((n >> 12) as u16);
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token));
} else {
if !(0..32768).contains(&n) {
return self.fail("mathchar must be in 0..32767");
};
let (class, c) = self.decode_math_char(n as u16);
self.accept_math_field(MathField::Char(c), class, TokenOrigin::from(token))
}
}
Mathord | Mathop | Mathbin | Mathrel | Mathopen | Mathclose | Mathpunct
| Mathinner => {
let class = match p {
Mathord => 0,
Mathop => 1,
Mathbin => 2,
Mathrel => 3,
Mathopen => 4,
Mathclose => 5,
Mathpunct => 6,
_ => 7,
};
self.new_noad(NoadClass::from_code(class), MathField::Empty, token.span);
let b = self.math.last_mut().unwrap();
b.pending = Some(FieldTarget::Nucleus(b.nodes.len() - 1));
}
Radical => {
let code = self.integer(files)?;
if !(0..1 << 27).contains(&code) {
return self.fail("radical must be in 0..134217727");
}
let delimiter = math::Delimiter::from_code(code as u32);
self.new_noad(NoadClass::Ord, MathField::Empty, token.span);
let builder = self.math.last_mut().unwrap();
let Some(MathNode::Noad(n)) = builder.nodes.last_mut() else {
unreachable!()
};
n.source.operator = PaintSource::token(TokenOrigin::from(token));
builder.pending =
Some(FieldTarget::Radical(builder.nodes.len() - 1, delimiter));
}
Overline | Underline => {
self.new_noad(NoadClass::Ord, MathField::Empty, token.span);
let b = self.math.last_mut().unwrap();
let i = b.nodes.len() - 1;
let MathNode::Noad(n) = &mut b.nodes[i] else {
unreachable!()
};
n.rule = Some(if *p == Overline {
MathRulePosition::Over
} else {
MathRulePosition::Under
});
n.source.operator = PaintSource::token(TokenOrigin::from(token));
b.pending = Some(FieldTarget::Nucleus(i));
}
Mathaccent => {
let code = self.integer(files)?;
if !(0..32768).contains(&code) {
return self.fail("mathaccent must be in 0..32767");
}
let (_, accent) = self.decode_math_char(code as u16);
self.new_noad(NoadClass::Ord, MathField::Empty, token.span);
let b = self.math.last_mut().unwrap();
let i = b.nodes.len() - 1;
let MathNode::Noad(n) = &mut b.nodes[i] else {
unreachable!()
};
n.accent = Some(accent);
n.source.operator = PaintSource::token(TokenOrigin::from(token));
b.pending = Some(FieldTarget::Nucleus(i));
}
Limits | Nolimits | Displaylimits => {
let Some(MathNode::Noad(n)) = self.math.last_mut().unwrap().nodes.last_mut()
else {
return self.fail("native limits switch requires an operator noad");
};
if n.class != NoadClass::Op {
return self.fail("native limits switch requires an operator noad");
}
n.limits = match p {
Limits => OperatorLimits::AboveBelow,
Nolimits => OperatorLimits::Side,
_ => OperatorLimits::Display,
};
}
Displaystyle | Textstyle | Scriptstyle | Scriptscriptstyle => self
.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::Style(match p {
Displaystyle => MathStyle::Display,
Textstyle => MathStyle::Text,
Scriptstyle => MathStyle::Script,
_ => MathStyle::ScriptScript,
})),
Explicitspace => {
let space = match self.explicit_space()? {
TextNode::NamedGlue(glue, parameter) => {
MathNode::ExplicitSpace(glue, Some(parameter))
}
TextNode::Glue(glue) => MathNode::ExplicitSpace(glue, None),
_ => unreachable!(),
};
self.math.last_mut().unwrap().nodes.push(space);
}
Hskip | Hfil | Hfill | Hss | Hfilneg => {
let g = self.skip_glue(*p, files)?;
self.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::ExplicitSpace(g, None));
}
Mskip => {
let g = self.skip_glue(*p, files)?;
self.math.last_mut().unwrap().nodes.push(MathNode::Glue(g));
}
Mkern | Kern => {
let n = self.dimension(*p == Mkern, false, files)?.amount;
self.math.last_mut().unwrap().nodes.push(MathNode::Kern {
amount: n,
mu: *p == Mkern,
explicit: true,
})
}
ItalicCorrection => {
self.math.last_mut().unwrap().nodes.push(MathNode::Kern {
amount: 0,
mu: false,
explicit: false,
});
}
Penalty => {
let n = self.integer(files)?;
self.math
.last_mut()
.unwrap()
.nodes
.push(MathNode::Penalty(n));
}
Over | Atop | Above | Overwithdelims | Atopwithdelims | Abovewithdelims => {
let b = self.math.last_mut().unwrap();
let ambiguous = b.numerator.is_some();
// Own the suspended numerator before scanning delimiter/dimension
// input, so a real scanner error or cancellation retains it.
if !ambiguous {
b.numerator = Some(math::PendingFraction {
numerator: std::mem::take(&mut b.nodes),
specification: FractionSpec::default(),
origin: TokenOrigin::from(token),
});
}
if matches!(p, Overwithdelims | Atopwithdelims | Abovewithdelims) {
let (left, source) = self.scan_delimiter(files)?;
if !ambiguous {
let spec = &mut self
.math
.last_mut()
.unwrap()
.numerator
.as_mut()
.unwrap()
.specification;
spec.left = left;
spec.left_source = source;
}
let (right, source) = self.scan_delimiter(files)?;
if !ambiguous {
let spec = &mut self
.math
.last_mut()
.unwrap()
.numerator
.as_mut()
.unwrap()
.specification;
spec.right = right;
spec.right_source = source;
}
}
let thickness = match p {
Above | Abovewithdelims => {
Some(self.dimension(false, false, files)?.amount)
}
Atop | Atopwithdelims => Some(0),
_ => None,
};
if ambiguous {
return self.fail("ambiguous native generalized fraction");
}
self.math
.last_mut()
.unwrap()
.numerator
.as_mut()
.unwrap()
.specification
.thickness = thickness;
}
Noboundary => {}
Global | Long | Outer | Protected | Def | Gdef | Edef | Xdef | Let | Futurelet
| Afterassignment | Aftergroup | Immediate | Chardef | Mathchardef | Catcode
| Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode
| Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip
| Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline
| Font | Fontdimen | Hyphenchar | Skewchar | Textfont | Scriptfont
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
| Parshape => {
return Ok(false);
}
_ => return self.fail(format!("unsupported native math primitive: {p:?}")),
},
Meaning::Count(_)
| Meaning::Toks(_)
| Meaning::TokenParameter(_)
| Meaning::Register(_)
| Meaning::Parameter(_)
| Meaning::Font(_) => return Ok(false),
Meaning::Undefined => return Ok(false),
_ => return self.fail("unsupported native math meaning"),
}
if self
.math
.iter()
.map(|b| b.nodes.len() + b.numerator.as_ref().map_or(0, |n| n.numerator.len()))
.sum::<usize>()
> self.limits.tokens
{
return self.fail("native math node capacity exceeded");
}
Ok(true)
}
}
@@ -0,0 +1,182 @@
use super::*;
impl Executor {
// Advance saved boundaries as their stack frames close, even with tracing off.
// A new frame at the same depth then still counts as opened in this file.
fn cross_input_boundary(&mut self, depth: usize, group: bool) -> bool {
let mut crossed = false;
for frame in self.inputs.iter_mut().rev() {
if let InputFrame::Source {
group_boundary,
conditional_boundary,
..
} = frame
{
let boundary = if group {
group_boundary
} else {
conditional_boundary
};
if *boundary != depth {
break;
}
*boundary -= 1;
crossed = true;
}
}
crossed
}
pub(super) fn warn_group_close(
&mut self,
kind: GroupKind,
level: usize,
origin: Option<(usize, usize)>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.cross_input_boundary(level, true) {
let tracing = self.read_parameter(Parameter::Tracingnesting).width();
if tracing > 0 {
let name = self.nesting_group(kind, level, origin);
self.emit_nesting_warning(
format!("Warning: end of {name} of a different file"),
tracing,
files,
)?;
}
}
Ok(())
}
pub(super) fn finish_conditional(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let depth = self.conditionals.len();
if self.cross_input_boundary(depth, false) {
let tracing = self.read_parameter(Parameter::Tracingnesting).width();
if tracing > 0 {
let name = self.nesting_condition(depth - 1, false);
self.emit_nesting_warning(
format!("Warning: end of {name} of a different file"),
tracing,
files,
)?;
}
}
self.conditionals.pop();
Ok(())
}
pub(super) fn warn_input_eof(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
let Some(InputFrame::Source {
group_boundary,
conditional_boundary,
..
}) = self.inputs.last()
else {
return Ok(());
};
let (groups, conditions) = (*group_boundary, *conditional_boundary);
if groups == self.state.group_depth() && conditions == self.conditionals.len() {
return Ok(());
}
let tracing = self.read_parameter(Parameter::Tracingnesting).width();
if tracing <= 0 {
return Ok(());
}
let open_groups: Vec<_> = self
.state
.open_groups()
.enumerate()
.skip(groups)
.rev()
.collect();
let mut warnings = String::new();
for (index, (kind, origin)) in open_groups {
let name = self.nesting_group(kind, index + 1, origin);
warnings.push_str(&format!("Warning: end of file when {name} is incomplete\n"));
}
for index in (conditions..self.conditionals.len()).rev() {
let name = self.nesting_condition(index, true);
warnings.push_str(&format!("Warning: end of file when {name} is incomplete\n"));
}
if tracing > 1 {
if let Some(InputFrame::Source { mouth, .. }) = self.inputs.last_mut() {
mouth.advance_eof_context();
}
}
self.emit_nesting_warning(warnings, tracing, files)
}
fn nesting_group(
&mut self,
kind: GroupKind,
level: usize,
origin: Option<(usize, usize)>,
) -> String {
let mut name = format!(
"{} group (level {level})",
super::scheduling::group_name(kind)
);
if let Some((source, line)) = origin {
self.reads.insert(Dependency::InputPosition(source));
if line != 0 {
name.push_str(&format!(" entered at line {line}"));
}
}
name
}
fn nesting_condition(&mut self, index: usize, eof: bool) -> String {
let frame = &self.conditionals[index];
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 mut name = String::new();
if frame.inverted {
name.push_str(&format!("{escape}unless"));
}
name.push_str(&escape);
name.push_str(&format!("{:?}", frame.primitive).to_ascii_lowercase());
if eof && frame.limit == ConditionalLimit::Fi {
name.push_str(&format!("{escape}else"));
}
if let Some((source, line)) = frame.origin {
self.reads.insert(Dependency::InputPosition(source));
if line != 0 {
name.push_str(&format!(" entered on line {line}"));
}
}
name
}
fn emit_nesting_warning(
&mut self,
warning: String,
tracing: i32,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.reads.insert(Dependency::NewLineChar);
let lines: Vec<_> = warning.lines().collect();
let mut text = self.print_show_parts(&lines)?;
if !text.ends_with('\n') {
text.push('\n');
}
if tracing > 1 {
let context = self.diagnostic_context();
text.push_str(&context.text);
self.reserve_diagnostic(text.len(), &context)?;
} else {
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
.observe_diagnostic(WriteDestination::TerminalAndLog, &text)
.map_err(|e| self.error(e, self.current))
}
}
@@ -0,0 +1,356 @@
use super::super::boxes::{self, PackSpec, VerticalBuilder};
use super::*;
pub(super) struct OutputFrame {
depth: usize,
paragraph: Option<super::super::paragraph::Builder>,
vertical: VerticalBuilder,
math: Vec<super::super::math::MathBuilder>,
display: Option<super::display::DisplayFrame>,
}
impl OutputFrame {
pub(super) fn collect_statistics(&self, c: &mut super::super::statistics::Collector) {
if let Some(p) = &self.paragraph {
c.paragraph_builder(p);
}
c.vertical(
&self.vertical.nodes,
super::super::statistics::Ownership::Active,
);
for m in &self.math {
c.math_builder(m);
}
}
}
impl Executor {
pub(super) fn outer_vertical(&self) -> bool {
self.box_frames.is_empty() && self.output_frame.is_none() && self.alignments.is_empty()
}
pub(super) fn native_page_mut(&mut self) -> Result<&mut NativePageState, Error> {
if self.native_page.is_none() {
return self.fail("native page/output execution requires a native job target");
}
self.reads.insert(Dependency::PageState);
Ok(self.native_page.as_mut().unwrap())
}
pub(super) fn page_dimension_value(&mut self, p: Primitive) -> Result<i32, Error> {
let value = self
.native_page_mut()?
.dimension(p.page_dimension().unwrap());
i32::try_from(value).map_err(|_| self.error("native page dimension overflow", self.current))
}
pub(super) fn request_page(&mut self) {
if self.outer_vertical() {
if let Some(page) = self.native_page.as_mut() {
page.requested = true;
}
}
}
pub(super) fn process_native_pages(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
while let Some(b) = self.pending_shipouts.pop_front() {
self.ship_box(b, files)?;
}
if self.native_page.is_none() {
return Ok(());
}
loop {
self.read_parameter(Parameter::Tracingpages);
let mut trace = Vec::new();
let next = self.native_page.as_mut().unwrap().advance(
&mut self.state,
&mut self.reads,
&mut self.steps,
self.limits.steps,
&mut trace,
);
for trace in trace {
let destination = if self.read_parameter(Parameter::Tracingonline).width() > 0 {
WriteDestination::TerminalAndLog
} else {
WriteDestination::Log
};
self.reads.insert(Dependency::NewLineChar);
let text = self.print_show_parts(&[&trace.text()])?;
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
.observe_diagnostic(destination, &text)
.map_err(|e| self.error(e, self.current))?;
self.events.push(Event::PageTrace(Box::new(PageTraceReport {
trace,
text,
destination,
span: self.current,
})));
}
let next = next.map_err(|e| self.error(e, self.current))?;
let Some(next) = next else {
return Ok(());
};
self.reads.insert(Dependency::PageState);
for p in [Parameter::Vsize, Parameter::Maxdepth, Parameter::Topskip] {
self.reads.insert(Dependency::Parameter(p));
}
if self.state.box_register(255).is_some() {
return self.fail("native box255 is not void before output");
}
self.state.assign_parameter(
Parameter::Outputpenalty,
ParameterValue::Integer(next.penalty),
true,
);
for marks in self.state.page_marks.values_mut() {
if marks.bottom.is_some() {
marks.top = marks.bottom.clone();
marks.first = None;
}
}
for node in &next.nodes {
self.tick()?;
if let NativeVerticalNode::Mark(m) = node {
let marks = self.state.page_marks.entry(m.class).or_default();
if marks.first.is_none() {
marks.first = Some(m.tokens.clone());
}
marks.bottom = Some(m.tokens.clone());
}
}
for marks in self.state.page_marks.values_mut() {
if marks.first.is_none() {
marks.first = marks.top.clone();
}
}
let b = boxes::vpack(
next.nodes,
PackSpec::To(next.goal),
next.max_depth,
BoxKind::Vertical,
self.current,
)
.map_err(|e| self.error(e, self.current))?;
self.state.last_badness = b.badness;
self.account_box(&b)?;
self.state.set_box(255, Some(b));
self.reads
.insert(Dependency::TokenParameter(TokenParameter::Output));
if let Some(tokens) = self.state.token_parameter(TokenParameter::Output).cloned() {
let max = self.read_parameter(Parameter::Maxdeadcycles).width();
if self.native_page.as_ref().unwrap().dead_cycles >= max {
return self.fail("native output loop: too many consecutive dead cycles");
}
self.native_page.as_mut().unwrap().dead_cycles += 1;
self.native_page.as_mut().unwrap().output_active = true;
if self.inputs.len() >= self.limits.input_depth {
return self.fail("native output input stack limit exceeded");
}
self.output_frame = Some(OutputFrame {
depth: self.state.group_depth() + 1,
paragraph: self.paragraph.take(),
vertical: std::mem::take(&mut self.vertical),
math: std::mem::take(&mut self.math),
display: self.display.take(),
});
self.inputs.push(InputFrame::Tokens {
tokens: tokens.iter().cloned().map(InputToken::from).collect(),
cursor: 0,
kind: TokenInputKind::Output,
});
self.begin_group(GroupKind::Output, files)?;
self.normal_paragraph(files)?;
let open = loop {
let t = self.expanded_non_space(files)?.token;
if self.primitive(&t) != Some(Primitive::Relax) {
break t;
}
};
if !matches!(
self.meaning(&open),
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
) {
return self.fail("expected opening brace in native output routine");
}
return Ok(());
}
let b = self.state.take_box(255).unwrap();
self.native_page
.as_mut()
.unwrap()
.resume_contributions(Vec::new());
self.ship_box(b, files)?;
}
}
pub(super) fn close_output_group(
&mut self,
files: &mut impl SourceProvider,
) -> Result<bool, Error> {
if !self
.output_frame
.as_ref()
.is_some_and(|f| f.depth == self.state.group_depth())
{
return Ok(false);
}
if !matches!(self.inputs.last(),Some(InputFrame::Tokens{tokens,cursor,kind:TokenInputKind::Output|TokenInputKind::BackedUp})if *cursor==tokens.len())
|| self.inputs.iter().any(|f| matches!(f, InputFrame::Tokens { tokens, cursor, kind: TokenInputKind::Output } if *cursor != tokens.len()))
{
return self.fail("unbalanced native output routine");
}
self.inputs.pop();
if matches!(self.inputs.last(),Some(InputFrame::Tokens{tokens,cursor,kind:TokenInputKind::Output})if *cursor==tokens.len())
{
self.inputs.pop();
}
self.end_paragraph(files)?;
self.finish_group(GroupKind::Output, self.current, files)?;
if self.state.box_register(255).is_some() {
return self.fail("native output routine did not empty box255");
}
let nodes = self.vertical.take_nodes();
let frame = self.output_frame.take().unwrap();
self.paragraph = frame.paragraph;
self.vertical = frame.vertical;
self.math = frame.math;
self.display = frame.display;
let page = self.native_page.as_mut().unwrap();
page.output_active = false;
page.resume_contributions(nodes);
page.requested = true;
Ok(true)
}
pub(super) fn ship_box(
&mut self,
b: NativeBox,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.native_page_mut()?;
let h_offset = i64::from(self.read_parameter(Parameter::Hoffset).width());
let v_offset = i64::from(self.read_parameter(Parameter::Voffset).width());
const MAX_DIMEN: i64 = 1_073_741_823;
if b.height > MAX_DIMEN
|| b.depth > MAX_DIMEN
|| b.height + b.depth + v_offset > MAX_DIMEN
|| b.width + h_offset > MAX_DIMEN
{
return self.fail("huge native page cannot be shipped out");
}
let magnification = self.prepare_magnification()?;
let pdf = self.pdf_page_data(files)?;
let horizontal_origin =
i64::from(self.read_parameter(Parameter::Pdfhorigin).width()) + h_offset;
let vertical_origin =
i64::from(self.read_parameter(Parameter::Pdfvorigin).width()) + v_offset;
let mut page_width = i64::from(self.read_parameter(Parameter::Pdfpagewidth).width());
let mut page_height = i64::from(self.read_parameter(Parameter::Pdfpageheight).width());
if page_width == 0 {
page_width = b.width + 2 * horizontal_origin;
}
if page_height == 0 {
page_height = b.height + b.depth + 2 * vertical_origin;
}
let device = ShipoutDevice {
magnification,
page_width,
page_height,
horizontal_origin,
vertical_origin,
pdf,
};
self.trace_shipout(&b, files)?;
let current = self.current;
let pdf_color_start = if device.pdf.is_some() {
self.pdf_colors.start_page()
} else {
Vec::new()
};
let mut pdf_color_steps = Vec::new();
let mut pdf_graphics_steps = Vec::new();
let mut graphics_stack = Vec::new();
let outputs = b.output_nodes();
let mut graphics_positions = if outputs.iter().any(|node| node.is_pdf_graphics()) {
b.pdf_graphics_positions().into_iter()
} else {
Vec::new().into_iter()
};
for output in outputs {
if let OutputOperation::PdfColor { stack, action } = &output.operation {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF color operation to DVI");
}
pdf_color_steps.push(self.ship_pdf_color(*stack, action, output.span, files)?);
} else if output.is_pdf_graphics() {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF graphics operation to DVI");
}
let point = graphics_positions.next().ok_or_else(|| {
self.error("missing positioned PDF graphics node", output.span)
})?;
pdf_graphics_steps.push(self.ship_pdf_graphics(
output,
point,
&mut graphics_stack,
files,
)?);
} else {
self.output_node(output, files)?;
}
}
if graphics_positions.next().is_some() {
return self.fail("unexpected positioned PDF graphics node");
}
if let Some((_, span)) = graphics_stack.last() {
return Err(self.error(
format!(
"{} unmatched \\pdfsave after page shipout",
graphics_stack.len()
),
*span,
));
}
self.current = current;
self.native_page.as_mut().unwrap().dead_cycles = 0;
let before = self.statistics_before_shipout(&b, files)?;
self.events.push(Event::Shipout(Box::new(NativeShipout {
box_node: b,
device,
pdf_color_start,
pdf_color_steps,
pdf_graphics_steps,
})));
self.statistics_after_shipout(before, files)?;
Ok(())
}
pub(super) fn end_native_job(&mut self, token: Token) -> Result<bool, Error> {
if !self.outer_vertical() || self.paragraph.is_some() || !self.math.is_empty() {
return self.fail("end is not allowed in an internal native mode");
}
let page = self.native_page.as_ref().unwrap();
if page.nodes.is_empty() && page.contributions.is_empty() && page.dead_cycles == 0 {
return Ok(true);
}
self.unread(token.clone().into())?;
let width = self.read_parameter(Parameter::Hsize).width();
let b = boxes::hpack(Vec::new(), PackSpec::To(width), token.span, &self.state)
.map_err(|e| self.error(e, token.span))?;
let page = self.native_page.as_mut().unwrap();
// its_all_over appends directly, without append_to_vlist/baselineskip.
page.contributions
.push_back(NativeVerticalNode::Box(Box::new(b)));
page.contributions.push_back(NativeVerticalNode::Glue(Glue {
canonical_zero: false,
stretch: Flex {
amount: 65536,
order: 2,
},
..Glue::default()
}));
page.contributions
.push_back(NativeVerticalNode::Penalty(-1_073_741_824));
page.requested = true;
Ok(false)
}
}
@@ -0,0 +1,594 @@
use super::*;
impl Executor {
pub(super) fn append_italic_correction(&mut self) -> Result<(), Error> {
self.reads.insert(Dependency::ParagraphMode);
self.reads.insert(Dependency::BoxPackState);
let Some(paragraph) = self.paragraph.as_ref() else {
return self.fail("italic correction requires horizontal or math mode");
};
let italic = match paragraph.nodes.last() {
Some(TextNode::Glyph { glyph, .. } | TextNode::MathChar(glyph)) => glyph.italic,
_ => return Ok(()),
};
self.reads.insert(Dependency::FontResources);
let width = i32::try_from(italic)
.map_err(|_| self.error("native italic correction overflow", self.current))?;
self.paragraph.as_mut().unwrap().nodes.push(TextNode::Kern {
width,
explicit: true,
});
Ok(())
}
pub(super) fn explicit_space(&mut self) -> Result<TextNode, Error> {
let glue = self.read_parameter(Parameter::Spaceskip).glue();
if glue != Glue::default() {
return Ok(TextNode::NamedGlue(glue, Parameter::Spaceskip));
}
self.reads.insert(Dependency::TextFont);
self.reads.insert(Dependency::FontResources);
let font = self
.state
.fonts
.font(self.state.text_font())
.map_err(|error| self.error(error, self.current))?;
Ok(TextNode::Glue(font.space()))
}
pub(super) fn read_parameter(&mut self, p: Parameter) -> ParameterValue {
self.reads.insert(Dependency::Parameter(p));
self.state.parameter(p)
}
pub(super) fn read_paragraph_shape(
&mut self,
) -> &[super::super::paragraph::ParagraphShapeLine] {
self.reads.insert(Dependency::ParagraphShape);
self.state.paragraph_shape()
}
pub(super) fn assign_paragraph_shape(
&mut self,
shape: Vec<super::super::paragraph::ParagraphShapeLine>,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let equivalent = shape.is_empty() && self.read_paragraph_shape().is_empty();
self.assign_equivalence(Key::ParagraphShape, global, equivalent, files, |state| {
state.assign_paragraph_shape(shape, global);
})
}
pub(super) fn scan_paragraph_shape(
&mut self,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use super::super::paragraph::ParagraphShapeLine;
self.optional_equals(files)?;
let count = self.integer(files)?.max(0) as usize;
if count > self.limits.tokens / 2 {
return self.fail("native paragraph shape capacity exceeded");
}
let mut shape = Vec::new();
for _ in 0..count {
shape.push(ParagraphShapeLine {
indent: self.dimension(false, false, files)?.amount,
width: self.dimension(false, false, files)?.amount,
});
}
self.assign_paragraph_shape(shape, global, files)
}
pub(super) fn paragraph_shape_dimension(
&mut self,
primitive: Primitive,
files: &mut impl SourceProvider,
) -> Result<i32, Error> {
let index = self.integer(files)?;
let shape = self.read_paragraph_shape();
if index <= 0 {
return Ok(0);
}
let index = (index - 1) as usize;
let (line, is_indent) = match primitive {
Primitive::Parshapeindent => (index, true),
Primitive::Parshapelength => (index, false),
Primitive::Parshapedimen => (index / 2, index % 2 == 0),
_ => unreachable!("paragraph shape dimension primitive"),
};
Ok(super::super::paragraph::shaped_line(shape, line)
.map_or(0, |line| if is_indent { line.indent } else { line.width }))
}
pub(super) fn assign_integer_target(
&mut self,
key: Key,
value: i32,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if matches!(
key,
Key::Delcode(_) | Key::Mathcode(_) | Key::Catcode(_) | Key::Sfcode(_)
) {
return self.fail("code tables are not arithmetic registers");
}
if key == Key::Spacefactor {
if !(1..32768).contains(&value) {
return self.fail("spacefactor must be in 1..32767");
}
let Some(b) = self.paragraph.as_mut() else {
return self.fail("spacefactor requires horizontal mode");
};
b.space_factor = value;
} else {
let equivalent = match key {
Key::Count(n) => self.state.count(n) == value,
Key::Endlinechar => self.state.endlinechar == value,
Key::Newlinechar => self.state.newlinechar == value,
Key::Escapechar => self.state.escapechar == value,
Key::Globaldefs => self.state.globaldefs == value,
Key::Job(p) => self.state.job_parameter(p) == Some(value),
Key::Parameter(p) => self.state.parameter(p) == ParameterValue::Integer(value),
_ => false,
};
self.assign_equivalence(key.clone(), global, equivalent, files, |state| {
state.assign_integer(key, value, global);
})?;
}
Ok(())
}
pub(super) fn begin_paragraph(&mut self, span: Span, indent: bool) -> Result<(), Error> {
self.vertical.previous_lines = 0;
self.reads
.insert(Dependency::Parameter(Parameter::Lefthyphenmin));
self.reads
.insert(Dependency::Parameter(Parameter::Righthyphenmin));
self.reads
.insert(Dependency::Parameter(Parameter::Parindent));
self.reads.insert(Dependency::Parameter(Parameter::Parskip));
let mut b = super::super::paragraph::Builder::default();
b.start(&self.state, span, indent);
b.ligature_carry = self.ligature_carry;
b.font_step_limit = self.limits.steps.saturating_sub(self.steps);
b.vertical_start = self.vertical.nodes.len();
if self.outer_vertical() || !self.vertical.nodes.is_empty() {
self.vertical
.push(NativeVerticalNode::NamedGlue(b.parskip, Parameter::Parskip));
}
self.paragraph = Some(b);
self.push_mode_hook(TokenParameter::Everypar)?;
if self.native_page.is_some() && self.outer_vertical() {
self.emit_vertical(0);
self.paragraph.as_mut().unwrap().vertical_start = 0;
self.request_page();
}
Ok(())
}
pub(super) fn finish_text(&mut self, right_boundary: bool) -> Result<(), Error> {
let Some(p) = self.paragraph.as_mut() else {
return Ok(());
};
let before = p.font_steps;
p.ligature_carry = self.ligature_carry;
p.font_step_limit = before.saturating_add(self.limits.steps.saturating_sub(self.steps));
let result = p.finish_text(right_boundary);
self.ligature_carry = p.ligature_carry;
self.steps = self
.steps
.saturating_add(p.font_steps.saturating_sub(before));
result.map_err(|e| self.error(e, self.current))
}
pub(super) fn text_character(
&mut self,
c: char,
code: CatCode,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let before = self.paragraph.as_ref().map_or(0, |p| p.font_steps);
if let Some(p) = self.paragraph.as_mut() {
p.ligature_carry = self.ligature_carry;
p.font_step_limit = before.saturating_add(self.limits.steps.saturating_sub(self.steps));
}
let result = self.text_character_inner(c, code, token, files);
if let Some(p) = self.paragraph.as_ref() {
self.ligature_carry = p.ligature_carry;
}
let after = self.paragraph.as_ref().map_or(0, |p| p.font_steps);
self.steps = self.steps.saturating_add(after.saturating_sub(before));
result
}
fn text_character_inner(
&mut self,
c: char,
code: CatCode,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if code == CatCode::Space {
if let Some(b) = self.paragraph.as_mut() {
self.reads.insert(Dependency::TextFont);
self.reads
.insert(Dependency::Parameter(Parameter::Spaceskip));
self.reads
.insert(Dependency::Parameter(Parameter::Xspaceskip));
b.space(&self.state)
.map_err(|e| self.error(e, token.invocation.unwrap_or(token.span)))?;
}
return Ok(());
}
let slot=u8::try_from(c as u32).map_err(|_|self.error("native text font character requires an 8-bit slot; Unicode shaping is not implemented",token.span))?;
if self.paragraph.is_none() {
self.begin_paragraph(token.invocation.unwrap_or(token.span), true)?;
}
self.reads.insert(Dependency::SfCode(slot));
self.paragraph
.as_mut()
.unwrap()
.adjust_space_factor(self.state.sfcode(slot));
if !self.restricted() {
let language = HyphenationLanguage::from_state(&self.state);
let b = self.paragraph.as_mut().unwrap();
if b.current_language.language != language.language {
b.set_language(language)
.map_err(|e| self.error(e, token.span))?;
}
for p in [
Parameter::Language,
Parameter::Lefthyphenmin,
Parameter::Righthyphenmin,
] {
self.reads.insert(Dependency::Parameter(p));
}
}
self.reads.insert(Dependency::FontResources);
let font = self.state.text_font();
self.reads.insert(Dependency::TextFont);
let missing = self
.paragraph
.as_mut()
.unwrap()
.character(
c,
TokenOrigin::from(token),
&self.state,
self.state.text_font(),
self.state.hyphen_character(self.state.text_font()),
)
.map_err(|e| self.error(e, token.invocation.unwrap_or(token.span)))?;
for c in missing {
self.missing_glyph(font, c.slot, token.invocation.unwrap_or(c.origin), files)?;
}
Ok(())
}
pub(super) fn end_paragraph(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
self.finish_paragraph(files, Parameter::Widowpenalty, true)
.map(|_| ())
}
pub(super) fn finish_paragraph(
&mut self,
files: &mut impl SourceProvider,
final_widow: Parameter,
reset: bool,
) -> Result<(usize, i32), Error> {
self.finish_text(true)?;
if self.restricted() {
return Ok((0, -1073741823));
}
let Some(b) = self.paragraph.take() else {
return Ok((self.vertical.previous_lines, -1073741823));
};
self.reads.insert(Dependency::PreviousParagraphLines);
if b.nodes.is_empty() {
self.emit_vertical(b.vertical_start);
if reset {
self.normal_paragraph(files)?;
}
return Ok((self.vertical.previous_lines, -1073741823));
}
let mut b = b;
b.previous_lines = self.vertical.previous_lines;
for p in Parameter::ALL {
self.reads.insert(Dependency::Parameter(*p));
}
self.reads.insert(Dependency::ParagraphShape);
self.reads.insert(Dependency::Hyphenation);
for n in &b.nodes {
if let super::super::paragraph::TextNode::Glyph { original, .. } = n {
for c in original.chars() {
self.reads.insert(Dependency::CaseCode(CaseCode::Lower, c));
}
}
}
self.reads.insert(Dependency::FontResources);
self.reads.insert(Dependency::TextFont);
let start = b.vertical_start;
let span = b.span;
let mut trace = super::super::paragraph_trace::Tracer::new(
&self.state,
self.limits.tokens.saturating_sub(self.diagnostic_bytes),
);
let result = super::super::paragraph::finish(
b,
&self.state,
final_widow,
&mut self.steps,
self.limits.steps,
&mut trace,
self.line_break_cache.as_deref(),
);
let records = trace.into_records();
if !records.is_empty() {
self.reads.insert(Dependency::EscapeChar);
self.reads.insert(Dependency::NewLineChar);
let destination = if self.read_parameter(Parameter::Tracingonline).width() > 0 {
WriteDestination::TerminalAndLog
} else {
WriteDestination::Log
};
let mut text = String::new();
for record in &records {
if let Some(line) = record.text(self.state.escapechar) {
let part = self.print_show_parts(&[&line])?;
if !part.is_empty() {
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
text.push_str(&part);
}
}
}
if !text.ends_with('\n') {
text.push('\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");
}
files
.observe_diagnostic(destination, &text)
.map_err(|e| self.error(e, self.current))?;
self.events
.push(Event::ParagraphTrace(Box::new(ParagraphTraceReport {
records,
text,
destination,
span,
})));
}
let p = result.map_err(|e| self.error(e, self.current))?;
let lines = p.previous_lines + p.lines.len();
if i32::try_from(lines).is_err() {
return self.fail("native paragraph line-count capacity exceeded");
}
if p.pass > 0 {
self.state.hyphenation.sealed = true;
}
for (font, slot, span) in &p.missing_glyphs {
self.missing_glyph(*font, *slot, *span, files)?;
}
self.state.last_badness = *p.packed_badness.last().unwrap_or(&0);
for (i, bad) in p.packed_badness.iter().enumerate() {
if p.packed_diagnostic[i]
&& if *bad == 1_000_000 {
p.packed_excess[i] > p.parameters[&Parameter::Hfuzz].width() as i64
|| p.parameters[&Parameter::Hbadness].width() < 100
} else {
*bad > p.parameters[&Parameter::Hbadness].width()
}
{
files
.observe_message(&format!(
"\n{} \\hbox (badness {}) in native paragraph line {}\n",
if *bad == 1_000_000 {
"Overfull"
} else if p.packed_shrinking[i] {
"Tight"
} else if *bad > 100 {
"Underfull"
} else {
"Loose"
},
bad,
i + 1
))
.map_err(|e| self.error(e, self.current))?;
}
}
for (i, line) in p.line_boxes.iter().enumerate() {
if let Some(pre) = p.line_pre_adjustments.get(i) {
self.vertical.extend(pre.iter().cloned());
}
self.append_vertical_box(NativeVerticalNode::Line(Box::new(line.clone())))?;
self.vertical.extend(p.line_adjustments[i].iter().cloned());
if let Some(penalty) = p.interline_penalties.get(i)
&& *penalty != 0
{
self.vertical.push(NativeVerticalNode::Penalty(*penalty));
}
}
self.emit_vertical(start);
self.vertical.previous_lines = lines;
let result = (lines, p.pre_display_size);
self.events.push(Event::BuiltParagraph(Box::new(p)));
if reset {
self.normal_paragraph(files)?;
}
Ok(result)
}
pub(super) fn normal_paragraph(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
for (parameter, value) in [
(Parameter::Looseness, ParameterValue::Integer(0)),
(Parameter::Hangindent, ParameterValue::dimension(0)),
(Parameter::Hangafter, ParameterValue::Integer(1)),
] {
if self.state.parameter(parameter) != value {
self.assign_traced_parameter(parameter, value, false, files)?;
}
}
if !self.read_paragraph_shape().is_empty() {
self.assign_paragraph_shape(Vec::new(), false, files)?;
}
Ok(())
}
pub(super) fn horizontal_command(
&mut self,
p: Primitive,
origin: TokenOrigin,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let span = origin.span;
if self.paragraph.is_none() {
if matches!(p, Primitive::Penalty | Primitive::Kern) {
return self
.fail("vertical kern/penalty requires native vertical-mode command execution");
}
self.begin_paragraph(span, true)?;
}
self.finish_text(true)?;
let node = match p {
Primitive::Hskip
| Primitive::Hfil
| Primitive::Hfill
| Primitive::Hss
| Primitive::Hfilneg => TextNode::Glue(self.skip_glue(p, files)?),
Primitive::Kern => TextNode::Kern {
width: self.dimension(false, false, files)?.amount,
explicit: true,
},
Primitive::Penalty => TextNode::Penalty(self.integer(files)?),
Primitive::DiscretionaryHyphen => {
self.reads.insert(Dependency::TextFont);
self.reads.insert(Dependency::FontResources);
let font = self.state.text_font();
let mut hyphen_char = self.state.hyphen_character(font);
if let Some(c) = hyphen_char {
let slot = c as u8;
if !self.state.font_has_slot(font, slot) {
self.missing_glyph(font, slot, span, files)?;
hyphen_char = None;
}
}
TextNode::Discretionary {
font,
automatic: false,
hyphen_char,
pre_break: hyphen_char
.into_iter()
.map(|c| super::super::paragraph::hyphen_node(&self.state, font, c, origin))
.collect(),
post_break: Vec::new(),
replacement_count: 0,
}
}
_ => unreachable!(),
};
if let Some(m) = self.math.last_mut() {
m.nodes.push(MathNode::Discretionary(Box::new(node)));
} else {
self.paragraph.as_mut().unwrap().nodes.push(node);
}
Ok(())
}
pub(super) fn define_font(
&mut self,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let name = self.command(files)?;
self.define_traced(name.clone(), Meaning::Font(FontId::NULL), global, files)?;
self.optional_equals(files)?;
let file = self.filename(files)?;
let size = if self.keyword("at", files)? {
crate::tfm::FontSize::At(self.dimension(false, false, files)?.amount as i64)
} else if self.keyword("scaled", files)? {
crate::tfm::FontSize::Scaled(self.integer(files)?)
} else {
crate::tfm::FontSize::Design
};
self.reads.insert(Dependency::FontResources);
let defaults = FontIntegers {
hyphen: self.read_parameter(Parameter::Defaulthyphenchar).width(),
skew: self.read_parameter(Parameter::Defaultskewchar).width(),
};
let from = self.sources[self.current.source].name.clone();
let font = self
.state
.fonts
.load(files, &file, &from, size, name.clone(), defaults)
.map_err(|e| self.error(e, self.current))?;
self.define_traced(name, Meaning::Font(font), global, files)?;
Ok(())
}
pub(super) fn hyphenation(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
let open = self.expanded_non_space(files)?.token;
if !matches!(
self.meaning(&open),
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup))
) {
return self.fail("hyphenation requires a begin-group token");
}
let language = super::super::hyphenation::normalize_language(
self.state.parameter(Parameter::Language).width(),
);
self.reads
.insert(Dependency::Parameter(Parameter::Language));
let (mut word, mut points, mut count) = (String::new(), Vec::new(), 0);
loop {
let t = self.required_expanded(files)?.token;
let meaning = self.meaning(&t);
let c = match meaning {
Meaning::Character(TokenKind::Character(_, CatCode::Space | CatCode::EndGroup)) => {
if count > 1 {
self.state
.hyphenation
.exceptions
.entry(language)
.or_default()
.insert(word.clone(), points.clone());
}
if matches!(
meaning,
Meaning::Character(TokenKind::Character(_, CatCode::EndGroup))
) {
break;
}
word.clear();
points.clear();
count = 0;
continue;
}
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => c,
Meaning::CharGiven(c) => char::from(c),
Meaning::Primitive(Primitive::Char) => {
let n = self.integer(files)?;
char::from(u8::try_from(n).map_err(|_| {
self.error("hyphenation character must be in 0..255", self.current)
})?)
}
_ => return self.fail("improper token in hyphenation exceptions"),
};
if c == '-' {
if count < 63 {
points.push(count);
}
continue;
}
self.reads.insert(Dependency::CaseCode(CaseCode::Lower, c));
let lower = self.state.case_code(CaseCode::Lower, c);
if lower == 0 {
return self.fail("hyphenation character must have nonzero lccode");
}
if count < 63 {
word.push(char::from_u32(lower).expect("validated case code"));
count += 1;
}
}
Ok(())
}
}
@@ -0,0 +1,82 @@
use super::*;
use crate::pdf_device::{ColorResult, PdfColorProgram, PdfColorStackAction};
impl Executor {
fn scan_pdf_color_program(
&mut self,
files: &mut impl SourceProvider,
) -> Result<PdfColorProgram, Error> {
let tokens = self.scan_expanded_group(files)?;
let literal = self.token_list_text(&tokens);
PdfColorProgram::parse(literal).map_err(|message| self.error(message, self.current))
}
pub(super) fn init_pdf_color_stack(
&mut self,
files: &mut impl SourceProvider,
) -> Result<usize, Error> {
let replay_on_page = self.keyword("page", files)?;
// Device-color operators are independent of the coordinate origin.
if !self.keyword("direct", files)? {
self.keyword("page", files)?;
}
let initial = self.scan_pdf_color_program(files)?;
self.pdf_colors
.allocate(initial, replay_on_page)
.map_err(|message| self.error(message, self.current))
}
pub(super) fn scan_pdf_color_action(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.native_page.is_none() || self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("PDF color stack requires a native PDF job");
}
let number = self.integer(files)?;
let stack = usize::try_from(number)
.ok()
.filter(|&n| self.pdf_colors.contains(n))
.ok_or_else(|| self.error(format!("unknown PDF color stack {number}"), span))?;
let action = if self.keyword("set", files)? {
PdfColorStackAction::Set(Arc::new(self.scan_pdf_color_program(files)?))
} else if self.keyword("push", files)? {
PdfColorStackAction::Push(Arc::new(self.scan_pdf_color_program(files)?))
} else if self.keyword("pop", files)? {
PdfColorStackAction::Pop
} else if self.keyword("current", files)? {
PdfColorStackAction::Current
} else {
return self.fail("expected set, push, pop, or current for PDF color stack");
};
self.defer_output(OutputNode {
operation: OutputOperation::PdfColor { stack, action },
span,
})
}
pub(super) fn ship_pdf_color(
&mut self,
stack: usize,
action: &PdfColorStackAction,
span: Span,
files: &mut impl SourceProvider,
) -> Result<Option<Arc<PdfColorProgram>>, Error> {
self.current = span;
self.tick()?;
let warning = match self.pdf_colors.apply(stack, action) {
ColorResult::Applied(program) => return Ok(program),
ColorResult::EmptyStack => {
format!("pdfTeX warning: pdftex: pop empty color page stack {stack}\n")
}
ColorResult::UnknownStack => {
format!("Color stack {stack} is not initialized for use!\n")
}
};
files
.observe_diagnostic(WriteDestination::TerminalAndLog, &warning)
.map_err(|message| self.error(message, span))?;
Ok(None)
}
}
@@ -0,0 +1,77 @@
use super::*;
use crate::pdf_device::{PdfGraphics, PdfMatrix};
impl Executor {
pub(super) fn scan_pdf_graphics(
&mut self,
command: Primitive,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.native_page.is_none() || self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("PDF graphics operation not allowed in DVI mode");
}
let operation = match command {
Primitive::Pdfsave => OutputOperation::PdfSave,
Primitive::Pdfrestore => OutputOperation::PdfRestore,
Primitive::Pdfsetmatrix => {
let tokens = self.with_scanner(ScannerStatus::Absorbing, |scanner| {
scanner.scan_expanded_group_mode(files, false)
})?;
OutputOperation::PdfSetMatrix(tokens)
}
_ => unreachable!(),
};
self.defer_output(OutputNode { operation, span })
}
pub(super) fn ship_pdf_graphics(
&mut self,
node: &OutputNode,
point: [i64; 2],
saved: &mut Vec<([i64; 2], Span)>,
files: &mut impl SourceProvider,
) -> Result<PdfGraphics, Error> {
self.current = node.span;
self.tick()?;
match &node.operation {
OutputOperation::PdfSave => {
saved.push((point, node.span));
Ok(PdfGraphics::Save)
}
OutputOperation::PdfSetMatrix(tokens) => {
let text = self.token_list_text(tokens);
let matrix = PdfMatrix::parse(&text)
.map_err(|error| self.error(format!("\\pdfsetmatrix: {error}"), node.span))?;
Ok(PdfGraphics::Matrix(matrix))
}
OutputOperation::PdfRestore => {
let (shift, warning) = match saved.pop() {
Some((previous, _)) if previous == point => ([0, 0], None),
Some(([x, y], _)) => {
let shift = [x - point[0], y - point[1]];
(
shift,
Some(format!(
"Misplaced \\pdfrestore by ({}sp, {}sp)",
(-shift[0]) as u32,
(-shift[1]) as u32
)),
)
}
None => ([0, 0], Some("\\pdfrestore: missing \\pdfsave".to_owned())),
};
if let Some(warning) = warning {
let diagnostic = format!("pdfTeX warning: pdftex: {warning}\n");
files
.observe_diagnostic(WriteDestination::TerminalAndLog, &diagnostic)
.map_err(|error| self.error(error, node.span))?;
}
// pdfTeX moves its logical device origin before emitting Q.
// The restored PDF CTM stays anchored at the save point.
Ok(PdfGraphics::Restore { shift })
}
_ => unreachable!(),
}
}
}
@@ -0,0 +1,163 @@
use super::*;
use crate::{
pdf_image::{PageBox, PdfImage, PdfImageObject, PdfImageUse},
resources::ResourceKind,
};
#[derive(Clone)]
pub(super) struct RegisteredImage {
image: Arc<PdfImageUse>,
attributes: Option<Vec<Token>>,
}
impl Executor {
pub(super) fn pdf_image_quantity(&mut self, command: Primitive) -> i32 {
self.reads.insert(Dependency::PdfImages);
match (command, self.pdf_images.last()) {
(Primitive::Pdflastximage, Some(image)) => image.image.id as i32,
(Primitive::Pdflastximagepages, Some(image)) => image.image.image.page_count as i32,
_ => 0,
}
}
fn check_pdf_image(&mut self) -> Result<(), Error> {
if self.native_page.is_none() || self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("PDF image operation requires a native PDF job");
}
Ok(())
}
pub(super) fn scan_pdf_image(
&mut self,
token: &Token,
immediate: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.check_pdf_image()?;
let mut dimensions = [None; 3];
loop {
let index = if self.keyword("width", files)? {
0
} else if self.keyword("height", files)? {
1
} else if self.keyword("depth", files)? {
2
} else {
break;
};
dimensions[index] = Some(self.dimension(false, false, files)?.amount);
}
let attributes = if self.keyword("attr", files)? {
self.with_scanner(ScannerStatus::Absorbing, |scanner| {
scanner.scan_expanded_group_mode(files, false)
})?
} else {
Vec::new()
};
if self.keyword("named", files)? {
return self.fail("native PDF image named destinations require PDF object support");
}
let page = if self.keyword("page", files)? {
let page = self.integer(files)?;
usize::try_from(page)
.map_err(|_| self.error("required page does not exist", token.span))?
} else {
1
};
if self.keyword("colorspace", files)? {
return self.fail("native PDF image colorspace requires PDF object support");
}
let mut page_box = PageBox::default();
for (keyword, kind) in [
("mediabox", PageBox::Media),
("cropbox", PageBox::Crop),
("bleedbox", PageBox::Bleed),
("trimbox", PageBox::Trim),
("artbox", PageBox::Art),
] {
if self.keyword(keyword, files)? {
page_box = kind;
break;
}
}
let filename = self.scan_expanded_group(files)?;
let filename = self.token_list_text(&filename);
let filename = self.decode_filename(filename)?.replace('"', "");
let from = self.source_name(token.span);
self.reads.insert(Dependency::FileLookup {
name: filename.clone(),
from: from.clone(),
});
let source = files
.resource(ResourceKind::Tex, &filename, &from)
.map_err(|error| {
self.error(
format!("cannot find image file {filename}: {error}"),
token.span,
)
})?;
let image = PdfImage::read(source, page, page_box)
.and_then(|image| PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions))
.map_err(|error| self.error(error, token.span))?;
let id = image.id;
self.pdf_images.push(RegisteredImage {
image: Arc::new(image),
attributes: Some(attributes),
});
if immediate {
self.declare_pdf_image(id)?;
}
Ok(())
}
// A PDF image object is emitted once, when used at shipout or immediately.
// Expansion took place during registration, but escapechar and catcodes
// belong to the token printer at the time of writing the object.
pub(super) fn declare_pdf_image(&mut self, id: usize) -> Result<(), Error> {
let registered = &mut self.pdf_images[id - 1];
let Some(tokens) = registered.attributes.take() else {
return Ok(());
};
let image = registered.image.clone();
let text = self.token_list_text(&tokens);
let attributes = if self.state.input_profile() == InputProfile::TeX8Bit {
text.chars()
.map(|character| u8::try_from(u32::from(character)))
.collect::<Result<Vec<_>, _>>()
.map_err(|_| {
self.error(
"PDF attribute character outside TeX 8-bit profile",
self.current,
)
})?
} else {
text.into_bytes()
};
self.events
.push(Event::PdfImageObject(PdfImageObject { image, attributes }));
Ok(())
}
pub(super) fn reference_pdf_image(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.check_pdf_image()?;
let id = self.integer(files)?;
self.reads.insert(Dependency::PdfImages);
let image = usize::try_from(id)
.ok()
.and_then(|id| id.checked_sub(1))
.and_then(|index| self.pdf_images.get(index))
.map(|registered| registered.image.clone())
.ok_or_else(|| self.error(format!("cannot find referenced object {id}"), token.span))?;
self.defer_output(OutputNode {
operation: OutputOperation::PdfImage {
image,
origin: token.into(),
},
span: token.span,
})
}
}
@@ -0,0 +1,645 @@
//! Native dimension/glue scanners. Integer fixed-point throughout; font-relative
//! units and magnification require their real native state, never demo values.
use super::super::registers;
use super::*;
#[derive(Clone, Copy)]
enum Target {
Register(Register),
Parameter(Parameter),
Value(i32),
Expression(RegisterValue, RegisterKind),
}
impl Target {
fn kind(self) -> RegisterKind {
match self {
Self::Register(r) => r.kind,
Self::Parameter(p) => p.kind().unwrap(),
Self::Value(_) => RegisterKind::Dimen,
Self::Expression(_, kind) => kind,
}
}
}
impl Executor {
pub(super) fn skip_glue(
&mut self,
primitive: Primitive,
files: &mut impl SourceProvider,
) -> Result<Glue, Error> {
use Primitive::*;
if matches!(primitive, Hskip | Vskip | Mskip) {
let kind = if primitive == Mskip {
RegisterKind::Muskip
} else {
RegisterKind::Skip
};
let RegisterValue::Glue(glue) = self.quantity(kind, files)? else {
unreachable!()
};
return Ok(glue);
}
Ok(Glue {
canonical_zero: false,
stretch: Flex {
amount: match primitive {
Hfilneg | Vfilneg => -65536,
Hfil | Vfil | Hfill | Vfill | Hss | Vss => 65536,
_ => unreachable!(),
},
order: if matches!(primitive, Hfill | Vfill) {
2
} else {
1
},
},
shrink: if matches!(primitive, Hss | Vss) {
Flex {
amount: 65536,
order: 1,
}
} else {
Flex::default()
},
..Glue::default()
})
}
pub(super) fn glue_component(
&mut self,
primitive: Primitive,
files: &mut impl SourceProvider,
) -> Result<i32, Error> {
self.begin_value_scan()?;
let value = self.quantity(RegisterKind::Skip, files);
self.scanner_depth -= 1;
let RegisterValue::Glue(glue) = value? else {
unreachable!()
};
Ok(match primitive {
Primitive::Gluestretch => glue.stretch.amount,
Primitive::Glueshrink => glue.shrink.amount,
Primitive::Gluestretchorder => i32::from(glue.stretch.order),
Primitive::Glueshrinkorder => i32::from(glue.shrink.order),
_ => unreachable!(),
})
}
pub(super) fn prepare_magnification(&mut self) -> Result<i32, Error> {
self.reads.insert(Dependency::MagnificationState);
let mag = self.read_parameter(Parameter::Mag).width();
if let Some(previous) = self.state.magnification_set
&& previous != mag
{
return self.fail(format!(
"incompatible native magnification ({mag}); previous value {previous}"
));
}
if !(1..=32768).contains(&mag) {
return self.fail("illegal native magnification: expected 1..32768");
}
self.state.magnification_set = Some(mag);
Ok(mag)
}
pub(super) fn scan_register(
&mut self,
p: Primitive,
files: &mut impl SourceProvider,
) -> Result<Register, Error> {
let kind = match p {
Primitive::Dimen => RegisterKind::Dimen,
Primitive::Skip => RegisterKind::Skip,
Primitive::Muskip => RegisterKind::Muskip,
_ => unreachable!(),
};
Ok(Register {
kind,
index: self.register_index(files)?,
})
}
pub(super) fn read_register(&mut self, register: Register) -> RegisterValue {
self.reads.insert(Dependency::Register(register));
self.state.register(register)
}
pub(super) fn register_integer(&mut self, register: Register) -> Result<i32, Error> {
if register.kind == RegisterKind::Muskip {
return self.fail("incompatible mu units in integer/dimension scan");
}
Ok(self.read_register(register).width())
}
fn register_operand(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<Option<Target>, Error> {
match self.meaning(token) {
Meaning::Primitive(p @ (Primitive::Gluestretch | Primitive::Glueshrink)) => {
Ok(Some(Target::Value(self.glue_component(p, files)?)))
}
Meaning::Primitive(p @ (Primitive::Lastskip | Primitive::Lastkern)) => {
let (value, kind) = self.last_quantity(p);
Ok(Some(Target::Expression(value, kind)))
}
Meaning::Primitive(
p @ (Primitive::Fontdimen
| Primitive::Fontcharwd
| Primitive::Fontcharht
| Primitive::Fontchardp
| Primitive::Fontcharic),
) => Ok(Some(Target::Value(self.font_dimension(p, files)?))),
Meaning::Primitive(
p @ (Primitive::Dimexpr | Primitive::Glueexpr | Primitive::Muexpr),
) => {
let kind = match p {
Primitive::Dimexpr => RegisterKind::Dimen,
Primitive::Glueexpr => RegisterKind::Skip,
_ => RegisterKind::Muskip,
};
Ok(Some(Target::Expression(
self.quantity_expression(kind, files)?,
kind,
)))
}
Meaning::Primitive(p) if p.page_dimension().is_some() => {
Ok(Some(Target::Value(self.page_dimension_value(p)?)))
}
Meaning::Primitive(
p @ (Primitive::Wd | Primitive::Ht | Primitive::Dp | Primitive::Prevdepth),
) => Ok(Some(Target::Value(self.dimension_value(p, files)?))),
Meaning::Primitive(
p @ (Primitive::Parshapeindent
| Primitive::Parshapelength
| Primitive::Parshapedimen),
) => Ok(Some(Target::Value(
self.paragraph_shape_dimension(p, files)?,
))),
Meaning::Register(r) => Ok(Some(Target::Register(r))),
Meaning::Parameter(p) if p.kind().is_some() => Ok(Some(Target::Parameter(p))),
Meaning::Primitive(p @ (Primitive::Dimen | Primitive::Skip | Primitive::Muskip)) => {
Ok(Some(Target::Register(self.scan_register(p, files)?)))
}
_ => Ok(None),
}
}
fn integer_operand(&mut self, token: &Token) -> bool {
if matches!(self.meaning(token),Meaning::Primitive(p)if p.page_dimension().is_some()||matches!(p, Primitive::Deadcycles | Primitive::Insertpenalties))
{
return true;
}
if let Meaning::Parameter(p) = self.meaning(token) {
return p.kind().is_none();
}
matches!(
self.meaning(token),
Meaning::Count(_)
| Meaning::CharGiven(_)
| Meaning::MathCharGiven(_)
| Meaning::Primitive(
Primitive::Count
| Primitive::Lccode
| Primitive::Uccode
| Primitive::Sfcode
| Primitive::Mathcode
| Primitive::Catcode
| Primitive::Endlinechar
| Primitive::Newlinechar
| Primitive::Escapechar
| Primitive::Globaldefs
| Primitive::Time
| Primitive::Day
| Primitive::Month
| Primitive::Year
| Primitive::Inputlineno
| Primitive::Pdflastximage
| Primitive::Pdflastximagepages
| Primitive::Pdflastximagecolordepth
| Primitive::Numexpr
| Primitive::Etexversion
| Primitive::Currentgrouplevel
| Primitive::Currentgrouptype
| Primitive::Badness
| Primitive::Lastpenalty
| Primitive::Lastnodetype
| Primitive::Gluestretchorder
| Primitive::Glueshrinkorder
| Primitive::Parshape
| Primitive::Prevgraf
| Primitive::Spacefactor
| Primitive::Hyphenchar
| Primitive::Skewchar
)
)
}
/// TeX keyword lookahead expands, skips initial spaces, and returns partially
/// matched tokens to the input on failure, preserving their categories.
pub(super) fn keyword(
&mut self,
keyword: &str,
files: &mut impl SourceProvider,
) -> Result<bool, Error> {
let mut scanned = Vec::new();
for (i, c) in keyword.chars().enumerate() {
let next = loop {
let next = self.expanded(files)?;
if i == 0 && next.as_ref().is_some_and(|t| t.token.kind.is_space()) {
continue;
}
break next;
};
let Some(next) = next else {
self.push_kind(scanned, TokenInputKind::BackedUp)?;
return Ok(false);
};
let matched =
matches!(next.token.kind,TokenKind::Character(ch,_) if ch.eq_ignore_ascii_case(&c));
scanned.push(next);
if !matched {
self.push_kind(scanned, TokenInputKind::BackedUp)?;
return Ok(false);
}
}
Ok(true)
}
fn sign(&mut self, files: &mut impl SourceProvider) -> Result<(i64, InputToken), Error> {
let mut sign = 1;
loop {
let t = self.expanded_non_space(files)?;
match t.token.kind {
TokenKind::Character('+', CatCode::Other) => {}
TokenKind::Character('-', CatCode::Other) => sign = -sign,
_ => return Ok((sign, t)),
}
}
}
fn dimension_bound(&self, n: i128) -> Result<i32, Error> {
if n.abs() > registers::MAX_DIMENSION as i128 {
return self.fail("TeX dimension overflow");
}
Ok(n as i32)
}
fn optional_space(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
if let Some(t) = self.expanded(files)?
&& !t.token.kind.is_space()
{
self.unread(t)?;
}
Ok(())
}
pub(super) fn dimension(
&mut self,
math: bool,
infinite: bool,
files: &mut impl SourceProvider,
) -> Result<Flex, Error> {
self.begin_value_scan()?;
let result = self.dimension_inner(math, infinite, files);
self.scanner_depth -= 1;
result
}
fn dimension_inner(
&mut self,
math: bool,
infinite: bool,
files: &mut impl SourceProvider,
) -> Result<Flex, Error> {
let (mut sign, first) = self.sign(files)?;
if let Some(r) = self.register_operand(&first.token, files)? {
if (r.kind() == RegisterKind::Muskip) != math {
return self.fail("incompatible mu units in dimension scan");
}
let n = self.read_target(r).width();
return Ok(Flex {
amount: self.dimension_bound(sign as i128 * n as i128)?,
order: 0,
});
}
let internal = self.integer_operand(&first.token);
let decimal = matches!(
first.token.kind,
TokenKind::Character('0'..='9' | '.' | ',', CatCode::Other)
);
let point = matches!(
first.token.kind,
TokenKind::Character('.' | ',', CatCode::Other)
);
let mut has_point = point;
let mut whole = if point {
0
} else if decimal {
self.unread(first)?;
let mut n = 0i64;
while let Some(t) = self.expanded(files)? {
if let TokenKind::Character(c @ '0'..='9', CatCode::Other) = t.token.kind {
n = n * 10 + c as i64 - '0' as i64;
self.bounded(n)?;
} else {
if matches!(
t.token.kind,
TokenKind::Character('.' | ',', CatCode::Other)
) {
has_point = true;
} else if !t.token.kind.is_space() {
self.unread(t)?;
}
break;
}
}
n
} else {
if internal {
self.internal_integer_from(first, files)? as i64
} else {
self.unread(first)?;
self.integer(files)? as i64
}
};
if whole < 0 {
sign = -sign;
whole = -whole;
}
let mut fraction = 0i64;
if has_point {
let mut digits = Vec::new();
while let Some(t) = self.expanded(files)? {
if let TokenKind::Character(c @ '0'..='9', CatCode::Other) = t.token.kind {
if digits.len() < 17 {
digits.push(c as i64 - '0' as i64);
}
} else {
if !t.token.kind.is_space() {
self.unread(t)?;
}
break;
}
}
for d in digits.into_iter().rev() {
fraction = (fraction + d * 131072) / 10;
}
fraction = (fraction + 1) / 2;
}
let mut fixed = whole as i128 * 65536 + fraction as i128;
let mut sp_whole = i128::from(whole);
if infinite && self.keyword("fil", files)? {
let mut order = 1;
while self.keyword("l", files)? {
order += 1;
if order > 3 {
return self.fail("glue order exceeds filll");
}
}
self.optional_space(files)?;
return Ok(Flex {
amount: self.dimension_bound(sign as i128 * fixed)?,
order,
});
}
// Internal dimensions (and integers interpreted as sp) may be units.
let t = self.expanded_non_space(files)?;
let unit = if let Some(r) = self.register_operand(&t.token, files)? {
if (r.kind() == RegisterKind::Muskip) != math {
return self.fail("incompatible mu units in internal unit");
}
Some(self.read_target(r).width())
} else if self.integer_operand(&t.token) {
if math {
return self.fail("incompatible mu units in internal unit");
}
Some(self.internal_integer_from(t, files)?)
} else {
self.unread(t)?;
None
};
if let Some(unit) = unit {
return Ok(Flex {
amount: self.dimension_bound(sign as i128 * fixed * unit as i128 / 65536)?,
order: 0,
});
}
let amount = if math {
if !self.keyword("mu", files)? {
return self.fail("math glue requires mu units");
}
fixed
} else {
let font_unit = if self.keyword("em", files)? {
Some(6)
} else if self.keyword("ex", files)? {
Some(5)
} else {
None
};
if let Some(n) = font_unit {
self.reads.insert(Dependency::TextFont);
self.reads.insert(Dependency::FontResources);
let unit = self
.state
.fonts
.fontdimen(self.state.text_font(), n)
.map_err(|e| self.error(e, self.current))?;
self.optional_space(files)?;
return Ok(Flex {
amount: self
.dimension_bound(sign as i128 * fixed * i128::from(unit) / 65536)?,
order: 0,
});
}
if self.keyword("true", files)? {
let mag = self.prepare_magnification()?;
// TeX first truncates the magnification conversion to a
// 16.16 number, then converts the physical unit separately.
if mag != 1000 {
fixed = fixed * 1000 / i128::from(mag);
sp_whole = fixed / 65536;
}
}
let mut ratio = None;
for (name, num, den) in [
("pt", 1, 1),
("in", 7227, 100),
("pc", 12, 1),
("cm", 7227, 254),
("mm", 7227, 2540),
("bp", 7227, 7200),
("dd", 1238, 1157),
("cc", 14856, 1157),
("sp", 0, 1),
] {
if self.keyword(name, files)? {
ratio = Some((num, den));
break;
}
}
let Some((num, den)) = ratio else {
return self.fail("missing or unsupported native dimension unit");
};
if num == 0 {
// The sp branch ignores the original fractional part. Only
// an actual non-unit mag adjustment normalizes its carry.
sp_whole
} else {
fixed * num / den
}
};
self.optional_space(files)?;
Ok(Flex {
amount: self.dimension_bound(sign as i128 * amount)?,
order: 0,
})
}
fn glue(&mut self, math: bool, files: &mut impl SourceProvider) -> Result<Glue, Error> {
let (sign, first) = self.sign(files)?;
let width = if let Some(r) = self.register_operand(&first.token, files)? {
if (r.kind() == RegisterKind::Muskip) != math {
return self.fail("incompatible mu units in glue scan");
}
match self.read_target(r) {
RegisterValue::Glue(g) => {
if sign > 0 {
return Ok(g);
}
return g
.map(|n| registers::bounded(sign * n as i64))
.map_err(|e| self.error(e, self.current));
}
RegisterValue::Dimension(n) => n as i64 * sign,
}
} else {
self.unread(first)?;
self.dimension(math, false, files)?.amount as i64 * sign
};
let stretch = if self.keyword("plus", files)? {
self.dimension(math, true, files)?
} else {
Flex::default()
};
let shrink = if self.keyword("minus", files)? {
self.dimension(math, true, files)?
} else {
Flex::default()
};
Ok(Glue {
canonical_zero: false,
width: width as i32,
stretch,
shrink,
})
}
pub(super) fn quantity(
&mut self,
kind: RegisterKind,
files: &mut impl SourceProvider,
) -> Result<RegisterValue, Error> {
if kind == RegisterKind::Dimen {
Ok(RegisterValue::Dimension(
self.dimension(false, false, files)?.amount,
))
} else {
Ok(RegisterValue::Glue(
self.glue(kind == RegisterKind::Muskip, files)?,
))
}
}
pub(super) fn assign_quantity(
&mut self,
register: Register,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.optional_equals(files)?;
let value = self.quantity(register.kind, files)?;
let equivalent =
matches!(value, RegisterValue::Dimension(_)) && self.state.register(register) == value;
self.assign_equivalence(
Key::Register(register),
global,
equivalent,
files,
|state| {
state.assign_register(register, value, global);
},
)
}
pub(super) fn register_arithmetic(
&mut self,
register: Register,
primitive: Primitive,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let old = self.read_register(register);
let value = self.quantity_arithmetic(old, register.kind, primitive, files)?;
let equivalent =
matches!(value, RegisterValue::Dimension(_)) && self.state.register(register) == value;
self.assign_equivalence(
Key::Register(register),
global,
equivalent,
files,
|state| {
state.assign_register(register, value, global);
},
)
}
fn read_target(&mut self, target: Target) -> RegisterValue {
match target {
Target::Value(n) => RegisterValue::Dimension(n),
Target::Expression(value, _) => value,
Target::Register(r) => self.read_register(r),
Target::Parameter(p) => match self.read_parameter(p) {
ParameterValue::Quantity(q) => q,
_ => unreachable!(),
},
}
}
pub(super) fn parameter_arithmetic(
&mut self,
p: Parameter,
primitive: Primitive,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let ParameterValue::Quantity(old) = self.read_parameter(p) else {
unreachable!()
};
let value = self.quantity_arithmetic(old, p.kind().unwrap(), primitive, files)?;
self.assign_traced_parameter(p, ParameterValue::Quantity(value), global, files)
}
fn quantity_arithmetic(
&mut self,
old: RegisterValue,
kind: RegisterKind,
primitive: Primitive,
files: &mut impl SourceProvider,
) -> Result<RegisterValue, Error> {
self.optional_by(files)?;
let value = if primitive == Primitive::Advance {
let other = self.quantity(kind, files)?;
match (old, other) {
(RegisterValue::Dimension(a), RegisterValue::Dimension(b)) => {
RegisterValue::Dimension(self.dimension_bound(a as i128 + b as i128)?)
}
(RegisterValue::Glue(a), RegisterValue::Glue(b)) => {
RegisterValue::Glue(a.add(b).map_err(|e| self.error(e, self.current))?)
}
_ => unreachable!(),
}
} else {
let n = self.integer(files)? as i64;
let scale = |v: i32| {
if primitive == Primitive::Multiply {
registers::bounded(v as i64 * n)
} else if n == 0 {
Err("division by zero")
} else {
registers::bounded(v as i64 / n)
}
};
match old {
RegisterValue::Dimension(v) => {
RegisterValue::Dimension(scale(v).map_err(|e| self.error(e, self.current))?)
}
RegisterValue::Glue(g) => {
RegisterValue::Glue(g.map(scale).map_err(|e| self.error(e, self.current))?)
}
}
};
Ok(value)
}
}
@@ -0,0 +1,237 @@
use super::*;
impl Executor {
pub(super) fn trace_restore(
&mut self,
key: &Key,
retaining: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let action = if retaining { "retaining" } else { "restoring" };
let (destination, text) = self.emit_equivalence_trace(key, action, files)?;
self.events.push(Event::RestoreTrace {
retaining,
destination,
text,
});
Ok(())
}
pub(super) fn assign_equivalence(
&mut self,
key: Key,
global: bool,
equivalent: bool,
files: &mut impl SourceProvider,
update: impl FnOnce(&mut State),
) -> Result<(), Error> {
let repeated = !global && equivalent && self.state.profile() == Profile::EtexBootstrap;
if self.read_parameter(Parameter::Tracingassigns).width() > 0 {
let action = if repeated {
"reassigning"
} else if global {
"globally changing"
} else {
"changing"
};
let (destination, text) = self.emit_equivalence_trace(&key, action, files)?;
self.events
.push(Event::AssignmentTrace { destination, text });
}
if !repeated {
update(&mut self.state);
if self.read_parameter(Parameter::Tracingassigns).width() > 0 {
let (destination, text) = self.emit_equivalence_trace(&key, "into", files)?;
self.events
.push(Event::AssignmentTrace { destination, text });
}
}
Ok(())
}
pub(super) fn define_traced(
&mut self,
name: CommandName,
meaning: Meaning,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let current = self.state.meaning(&name);
let equivalent = match (&current, &meaning) {
(Meaning::Macro(old), Meaning::Macro(new)) => Arc::ptr_eq(old, new),
_ => current == meaning,
};
self.assign_equivalence(
Key::Command(name.clone()),
global,
equivalent,
files,
|state| {
state.define(name, meaning, global);
},
)
}
pub(super) fn select_traced_font(
&mut self,
font: FontId,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let equivalent = self.state.text_font() == font;
self.assign_equivalence(Key::Font, global, equivalent, files, |state| {
state.assign_font(font, global);
})
}
pub(super) fn assign_traced_parameter(
&mut self,
parameter: Parameter,
value: ParameterValue,
global: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let equivalent = matches!(
value,
ParameterValue::Integer(_) | ParameterValue::Quantity(RegisterValue::Dimension(_))
) && self.state.parameter(parameter) == value;
self.assign_equivalence(
Key::Parameter(parameter),
global,
equivalent,
files,
|state| {
state.assign_parameter(parameter, value, global);
},
)
}
fn emit_equivalence_trace(
&mut self,
key: &Key,
action: &str,
files: &mut impl SourceProvider,
) -> Result<(WriteDestination, String), Error> {
let value = self.equivalence_text(key)?;
self.reads.insert(Dependency::NewLineChar);
let mut text = self.print_show_parts(&[&format!("{{{action} {value}}}")])?;
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_inline_diagnostic(destination, &text)
.map_err(|e| self.error(e, self.current))?;
Ok((destination, text))
}
fn equivalence_text(&mut self, key: &Key) -> Result<String, Error> {
self.reads.insert(Dependency::EscapeChar);
let escape = u8::try_from(self.state.escapechar)
.ok()
.map(char::from)
.map(|c| c.to_string())
.unwrap_or_default();
let (name, value) = match key {
Key::Command(command) => {
let token = Token::new(TokenKind::Command(command.clone()), self.current);
return Ok(format!(
"{}={}",
self.string_token(&token.kind),
self.meaning_string(&token)?
));
}
Key::Catcode(c) => (
format!("catcode{}", *c as u32),
(self.state.catcode(*c) as u8).to_string(),
),
Key::Count(index) => (
format!("count{index}"),
self.state.count(*index).to_string(),
),
Key::Toks(index) => (
format!("toks{index}"),
self.token_list_text(&self.state.tokens(*index)),
),
Key::TokenParameter(parameter) => {
let tokens = self.state.token_parameter(*parameter).cloned();
let value = tokens.map_or_else(String::new, |tokens| self.token_list_text(&tokens));
(parameter.name(), value)
}
Key::Endlinechar => ("endlinechar".into(), self.state.endlinechar.to_string()),
Key::Newlinechar => ("newlinechar".into(), self.state.newlinechar.to_string()),
Key::Escapechar => ("escapechar".into(), self.state.escapechar.to_string()),
Key::Globaldefs => ("globaldefs".into(), self.state.globaldefs.to_string()),
Key::Job(parameter) => {
let value = self
.state
.job_parameter(*parameter)
.ok_or_else(|| self.error("native job time unavailable", self.current))?;
(
format!("{parameter:?}").to_ascii_lowercase(),
value.to_string(),
)
}
Key::Register(register) => (
format!("{}{}", register.kind.name(), register.index),
self.read_register(*register)
.text(register.kind == RegisterKind::Muskip),
),
Key::Parameter(parameter) => {
let value = self.read_parameter(*parameter);
let text = match value {
ParameterValue::Quantity(quantity) => {
quantity.text(parameter.kind() == Some(RegisterKind::Muskip))
}
ParameterValue::Integer(value) => value.to_string(),
};
(parameter.name(), text)
}
Key::ParagraphShape => (
"parshape".into(),
self.read_paragraph_shape().len().to_string(),
),
Key::Font => {
self.reads.insert(Dependency::FontResources);
let font = self.font_token_name(self.state.text_font());
return Ok(format!("current font={escape}{font}"));
}
Key::Box(index) => {
let (rendered, reads) = super::super::diagnostics::show_box(
&self.state,
*index,
1,
0,
self.limits.tokens,
)
.map_err(|error| self.error(error, self.current))?;
self.reads.extend(reads);
let (_, value) = rendered.split_once('=').expect("box diagnostic header");
(format!("box{index}"), value.trim_end_matches('\n').into())
}
Key::Mathcode(c) => (format!("mathcode{c}"), self.state.mathcode(*c).to_string()),
Key::Delcode(c) => (format!("delcode{c}"), self.state.delcode(*c).to_string()),
Key::Sfcode(c) => (format!("sfcode{c}"), self.state.sfcode(*c).to_string()),
Key::CaseCode(kind, c) => (
format!("{}{}", kind.name(), *c as u32),
self.state.case_code(*kind, *c).to_string(),
),
Key::Mathfont(size, family) => {
self.reads.insert(Dependency::FontResources);
let name = ["textfont", "scriptfont", "scriptscriptfont"][*size as usize];
let font = self.font_token_name(self.state.math_font(*size, *family));
(format!("{name}{family}"), format!("{escape}{font}"))
}
Key::Spacefactor => unreachable!("spacefactor has no group save record"),
};
Ok(format!("{escape}{name}={value}"))
}
}
@@ -0,0 +1,46 @@
//! TeX scanner states and outer validation at real token-read boundaries.
use super::*;
impl Executor {
pub(super) fn with_scanner<T>(
&mut self,
status: ScannerStatus,
scan: impl FnOnce(&mut Self) -> Result<T, Error>,
) -> Result<T, Error> {
let saved = std::mem::replace(&mut self.scanner_status, status);
let result = scan(self);
self.scanner_status = saved;
result
}
pub(super) fn normal_raw(
&mut self,
files: &mut impl SourceProvider,
) -> Result<InputToken, Error> {
self.with_scanner(ScannerStatus::Normal, |s| s.required_raw(files))
}
pub(super) fn reject_outer(&mut self, token: &Token, literal: bool) -> Result<(), Error> {
if literal || self.scanner_status == ScannerStatus::Normal {
return Ok(());
}
if let Meaning::Macro(definition) = self.meaning(token) {
if definition.outer {
let where_ = match self.scanner_status.clone() {
ScannerStatus::Normal => unreachable!(),
ScannerStatus::Defining(name) => format!(
"definition of {}",
self.string_token(&TokenKind::Command(name))
),
ScannerStatus::Matching(name) => {
format!("use of {}", self.string_token(&TokenKind::Command(name)))
}
ScannerStatus::Absorbing => "token list text".into(),
ScannerStatus::Skipping => "skipped conditional text".into(),
};
return Err(self.error(
format!("forbidden outer control sequence while scanning {where_}"),
token.invocation.unwrap_or(token.span),
));
}
}
Ok(())
}
}
@@ -0,0 +1,199 @@
//! Actual token scheduling at assignment completion and after unsave.
use super::*;
impl Executor {
pub(super) fn finish_assignment(&mut self) -> Result<(), Error> {
self.reads.insert(Dependency::AssignmentState);
if let Some(token) = self.after_assignment.take() {
self.unread(token.into())?;
}
Ok(())
}
pub(super) fn schedule_after_group(
&mut self,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let token = self.required_raw(files)?.token;
self.reads.insert(Dependency::GroupState);
if self.state.group_depth() > 0 {
if self.after_group_tokens >= self.limits.tokens {
return self.fail("native aftergroup token capacity exceeded");
}
self.state.save_for_after(token);
self.after_group_tokens += 1;
}
Ok(())
}
pub(super) fn begin_group(
&mut self,
kind: GroupKind,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let origin = self.input_position;
self.state.begin_group(kind, origin);
self.trace_group(
kind,
true,
self.state.group_depth(),
self.state.group_type(),
origin,
files,
)
}
pub(super) fn finish_group(
&mut self,
kind: GroupKind,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let origin = self.state.group_origin();
let level = self.state.group_depth();
let group_type = self.state.group_type();
let restored = match self.state.pop_group(kind) {
Ok(restored) => restored,
Err(error) => {
let Some((open, origin)) = self.state.open_groups().next_back() else {
return Err(self.error(error, span));
};
let location = origin
.and_then(|(source, line)| {
self.sources
.get(source)
.map(|source| format!(" opened at {}:{line}", source.name))
})
.unwrap_or_default();
return Err(self.error(
format!(
"{error}: closing {} group with {} group{location} on top",
group_name(kind),
group_name(open)
),
span,
));
}
};
for (key, saved) in restored.entries {
let retaining = saved.is_none();
if let Some(value) = saved {
self.state.restore_saved(key.clone(), value);
}
if self.read_parameter(Parameter::Tracingrestores).width() > 0 {
self.trace_restore(&key, retaining, files)?;
}
}
self.trace_group(kind, false, level, group_type, origin, files)?;
self.warn_group_close(kind, level, origin, files)?;
for token in restored.after.into_iter().rev() {
self.unread(token.into())?;
}
Ok(())
}
fn trace_group(
&mut self,
kind: GroupKind,
entering: bool,
level: usize,
group_type: i32,
origin: Option<(usize, usize)>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.state.profile() != Profile::EtexBootstrap
|| self.read_parameter(Parameter::Tracinggroups).width() <= 0
{
return Ok(());
}
let name = group_name(kind);
let action = if entering { "entering" } else { "leaving" };
let mut message = format!("{{{action} {name} group (level {level})");
if let Some((source, line)) = origin {
self.reads.insert(Dependency::InputPosition(source));
if line != 0 {
let location = if entering {
"at line"
} else {
"entered at line"
};
message.push_str(&format!(" {location} {line}"));
}
}
message.push('}');
self.reads.insert(Dependency::NewLineChar);
let mut text: String = message
.chars()
.map(|c| {
if c as i32 == self.state.newlinechar {
'\n'
} else {
c
}
})
.collect();
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_inline_diagnostic(destination, &text)
.map_err(|e| self.error(e, self.current))?;
self.events.push(Event::GroupTrace {
entering,
group_type,
level,
origin,
destination,
text,
});
Ok(())
}
}
impl Executor {
pub(super) fn push_mode_hook(&mut self, parameter: TokenParameter) -> Result<(), Error> {
self.reads.insert(Dependency::TokenParameter(parameter));
let Some(tokens) = self.state.token_parameter(parameter).cloned() else {
return Ok(());
};
if tokens.is_empty() {
return Ok(());
}
if tokens.len() > self.limits.tokens {
return self.fail("native hook token capacity exceeded");
}
if self.inputs.len() >= self.limits.input_depth {
return self.fail("native input stack limit exceeded");
}
self.inputs.push(InputFrame::Hook {
parameter,
tokens,
cursor: 0,
});
Ok(())
}
}
pub(super) fn group_name(kind: GroupKind) -> &'static str {
match kind {
GroupKind::Simple => "simple",
GroupKind::SemiSimple => "semi simple",
GroupKind::Hbox => "hbox",
GroupKind::AdjustedHbox => "adjusted hbox",
GroupKind::Vbox => "vbox",
GroupKind::Vtop => "vtop",
GroupKind::MathShift => "math shift",
GroupKind::MathGroup => "math",
GroupKind::MathChoice => "math choice",
GroupKind::MathLeft => "math left",
GroupKind::Discretionary => "disc",
GroupKind::Insertion => "insert",
GroupKind::Output => "output",
GroupKind::Align => "align",
GroupKind::NoAlign => "no align",
GroupKind::Vcenter => "vcenter",
}
}
@@ -0,0 +1,260 @@
use super::super::statistics::{
Collector,
Ownership::{Active, Retained},
};
use super::*;
impl Executor {
fn stack_usage(&self) -> StackUsage {
StackUsage {
input_frames: self.inputs.len(),
groups: self.state.group_depth(),
box_frames: self.box_frames.len(),
math_frames: self.math.len(),
conditionals: self.conditionals.len(),
scanner_depth: self.scanner_depth,
expansion_depth: self.expansion_depth,
}
}
pub(super) fn observe_resource_stacks(&mut self) {
self.stack_peaks.include(&self.stack_usage());
}
fn resource_usage(
&self,
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
) -> ResourceUsage {
let mut c = Collector::default();
self.state.collect_statistics(&mut c);
c.usage.steps = self.steps;
c.usage.source_files = self.sources.len();
c.usage.source_payload_bytes = self.sources.iter().map(|s| s.data.len()).sum();
c.usage.box_nodes_created = self.box_nodes_created;
c.usage.diagnostic_bytes_generated = self.diagnostic_bytes;
c.usage.step_limit = self.limits.steps;
c.usage.token_limit = self.limits.tokens;
c.usage.input_depth_limit = self.limits.input_depth;
c.usage.stacks = self.stack_usage();
c.usage.stack_peaks = self.stack_peaks.clone();
c.usage.stack_peaks.include(&c.usage.stacks);
c.usage.host = host;
if let Some(p) = &self.paragraph {
c.paragraph_builder(p);
}
c.vertical(&self.vertical.nodes, Active);
if let Some(d) = &self.display {
d.collect_statistics(&mut c);
}
for b in &self.box_frames {
b.collect_statistics(&mut c);
}
for a in &self.alignments {
a.collect_statistics(&mut c);
}
for m in &self.math {
c.math_builder(m);
}
if let Some(f) = &self.output_frame {
f.collect_statistics(&mut c);
}
if let Some(p) = &self.native_page {
c.vertical(&p.nodes, Active);
c.vertical(&p.contributions, Active);
}
for b in &self.pending_shipouts {
c.native_box(b, Active);
}
if let Some(b) = shipping {
c.native_box(b, Active);
}
if self.after_assignment.is_some() {
c.usage.token_list_cells += 1;
}
for input in &self.inputs {
match input {
InputFrame::Source { mouth, .. } => {
c.usage.mouth_payload_bytes += mouth.payload_bytes()
}
InputFrame::Tokens { tokens, .. } => c.usage.token_list_cells += tokens.len(),
InputFrame::Macro {
definition,
arguments,
..
} => {
c.macro_body(definition);
for a in arguments {
c.shared_tokens(a);
}
}
InputFrame::Argument { tokens, .. } | InputFrame::Hook { tokens, .. } => {
c.shared_tokens(tokens)
}
InputFrame::Boundary => {}
}
}
for e in &self.events {
if matches!(e, Event::Statistics(_)) {
continue;
}
c.usage.retained_events += 1;
match e {
Event::Shipout(s) => {
c.usage.retained_shipouts += 1;
c.native_box(&s.box_node, Retained);
}
Event::VerticalMaterial(v) => c.vertical(v, Retained),
Event::BuiltParagraph(p) => {
c.text(&p.nodes, Retained);
for b in &p.line_boxes {
c.native_box(b, Retained);
}
for v in &p.line_adjustments {
c.vertical(v, Retained);
}
for b in &p.diagnostic_lines {
c.diagnostics(&b.nodes, Retained);
}
for paragraph in &p.lines {
for line in &paragraph.lines {
for item in line {
c.usage.retained_material.horizontal_nodes += 1;
if let crate::HorizontalItem::Box(b) = item {
c.horizontal_box(b, Retained);
}
}
}
}
}
Event::BuiltMath(m) => {
c.math(&m.noads, Retained);
c.text(&m.horizontal, Retained);
}
Event::BuiltDisplay(d) => c.native_box(&d.box_, Retained),
Event::DeferredOutput(o) => c.output(o),
_ => {}
}
}
c.usage
}
pub(super) fn statistics_before_shipout(
&mut self,
b: &NativeBox,
files: &mut impl SourceProvider,
) -> Result<Option<ResourceUsage>, Error> {
if self.read_parameter(Parameter::Tracingstats).width() <= 1 {
return Ok(None);
}
self.reads.insert(Dependency::ResourceStatistics);
let host = files
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
Ok(Some(self.resource_usage(Some(b), host)))
}
pub(super) fn statistics_after_shipout(
&mut self,
before: Option<ResourceUsage>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
let Some(before) = before else {
return Ok(());
};
let host = files
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
let after = self.resource_usage(None, host);
let text = format!(
"Route-D resources at shipout: active records {} -> {}; retained records {} -> {}; token cells {} -> {}; retained pages {}.\n",
before.active_material.records(),
after.active_material.records(),
before.retained_material.records(),
after.retained_material.records(),
before.macro_token_cells + before.token_list_cells,
after.macro_token_cells + after.token_list_cells,
after.retained_shipouts
);
self.emit_statistics(
StatisticsPhase::Shipout { before, after },
WriteDestination::TerminalAndLog,
text,
files,
)
}
pub(super) fn statistics_end(
&mut self,
success: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Tracingstats).width() <= 0 {
return Ok(());
}
self.reads.insert(Dependency::ResourceStatistics);
let host = files
.resource_usage()
.map_err(|e| self.error(e, self.current))?;
let usage = self.resource_usage(None, host);
let mut text = format!(
"Route-D resource usage at core execution end ({}):\n {} steps out of {}\n {} source files, {} source payload bytes, {} active mouth payload bytes\n {} command entries, {} control-name bytes\n {} macro bindings, {} unique macro bodies, {} macro token cells\n {} token-list cells, {} saved entries\n {} active material records, {} retained material records, {} retained pages\n {} font instances, {} font parameter cells, {} TFM resources / {} source bytes\n {} hyphenation exceptions\n stack peaks: {} input, {} group, {} box, {} math, {} conditional, {} scanner, {} expansion\n",
if success { "success" } else { "failure" },
usage.steps,
usage.step_limit,
usage.source_files,
usage.source_payload_bytes,
usage.mouth_payload_bytes,
usage.state.command_entries,
usage.state.control_name_bytes,
usage.state.macro_bindings,
usage.unique_macro_bodies,
usage.macro_token_cells,
usage.token_list_cells,
usage.state.save_entries,
usage.active_material.records(),
usage.retained_material.records(),
usage.retained_shipouts,
usage.state.font_instances,
usage.state.font_parameter_cells,
usage.state.tfm_resources,
usage.state.tfm_resource_bytes,
usage.state.hyphenation_exceptions,
usage.stack_peaks.input_frames,
usage.stack_peaks.groups,
usage.stack_peaks.box_frames,
usage.stack_peaks.math_frames,
usage.stack_peaks.conditionals,
usage.stack_peaks.scanner_depth,
usage.stack_peaks.expansion_depth
);
if let Some(h) = &usage.host {
text.push_str(&format!(" host resources: {} reads / {} bytes; {} lookups / {} misses / {} errors; {} stream reads / {} bytes\n",h.resource_reads,h.resource_bytes_read,h.lookups,h.negative_lookups,h.failed_lookups,h.stream_read_calls,h.stream_bytes_read));
} else {
text.push_str(" host resource telemetry unavailable\n");
}
self.emit_statistics(
StatisticsPhase::End { success, usage },
WriteDestination::Log,
text,
files,
)
}
fn emit_statistics(
&mut self,
phase: StatisticsPhase,
destination: WriteDestination,
text: String,
files: &mut impl SourceProvider,
) -> 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
.observe_diagnostic(destination, &text)
.map_err(|e| self.error(e, self.current))?;
self.events
.push(Event::Statistics(Box::new(StatisticsReport {
phase,
destination,
text,
span: self.current,
})));
Ok(())
}
}