use crate::glue::Glue;
use crate::node::{BoxNode, Node, Scaled, IGNORE_DEPTH};
pub mod align;
pub mod build;
pub mod font;
pub mod hyph;
pub mod math;
pub mod output;
pub mod par;
pub mod run;
pub use font::Font;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
Vertical,
InternalVertical,
Horizontal,
RestrictedHorizontal,
Math,
DisplayMath,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
V,
H,
M,
}
impl Mode {
pub fn kind(self) -> Kind {
match self {
Mode::Vertical | Mode::InternalVertical => Kind::V,
Mode::Horizontal | Mode::RestrictedHorizontal => Kind::H,
Mode::Math | Mode::DisplayMath => Kind::M,
}
}
pub fn outer(self) -> bool {
matches!(self, Mode::Vertical | Mode::Horizontal | Mode::DisplayMath)
}
}
#[derive(Clone, Debug)]
pub struct ListState {
pub mode: Mode,
pub list: Vec<Node>,
pub prev_depth: Scaled,
pub space_factor: i64,
pub prev_graf: i64,
pub mode_line: i64,
pub opened: Opened,
pub mlist: Vec<crate::math::noad::Noad>,
pub incompleat: Option<crate::math::noad::Fraction>,
pub eq_no: Option<(BoxNode, bool)>,
}
impl ListState {
pub fn new(mode: Mode, opened: Opened) -> ListState {
ListState {
mode,
list: Vec::new(),
prev_depth: IGNORE_DEPTH,
space_factor: 1000,
prev_graf: 0,
mode_line: 0,
opened,
mlist: Vec::new(),
incompleat: None,
eq_no: None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Opened {
Page,
Box {
kind: BoxKind,
spec: crate::pack::Spec,
context: BoxContext,
max_depth: Scaled,
},
Insert(u16),
Output,
MathShift {
display: Option<math::Display>,
eqno: Option<bool>,
},
MathGroup(math::Target),
MathLeft,
MathChoice(u8),
Align,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BoxKind {
H,
V,
Top,
VCenter,
}
#[derive(Clone, Debug, PartialEq)]
pub enum BoxContext {
Shift(Scaled),
SetBox { n: u16, global: bool },
ShipOut,
Leaders(crate::node::LeaderKind),
}
pub trait Eqtb {
fn slot(&self, slot: i64) -> i64;
}
pub fn dimen_par(e: &dyn Eqtb, name: &str) -> Scaled {
crate::params::register_slot(name).map_or(0, |s| e.slot(s))
}
pub fn glue_par(e: &dyn Eqtb, name: &str) -> Glue {
crate::params::register_slot(name).map_or(Glue::default(), |s| glue_at(e, s))
}
pub fn glue_at(e: &dyn Eqtb, s: i64) -> Glue {
let orders = e.slot(s + 3);
Glue {
natural: e.slot(s),
stretch: e.slot(s + 1),
stretch_order: orders / 4,
shrink: e.slot(s + 2),
shrink_order: orders % 4,
}
}
#[derive(Clone, Debug, Default)]
struct Register {
value: Option<BoxNode>,
level: usize,
}
#[derive(Clone, Debug)]
enum Saved {
Box {
n: u16,
old: Register,
},
ParShape {
old: Vec<(Scaled, Scaled)>,
level: usize,
},
}
pub struct Stomach {
pub nest: Vec<ListState>,
registers: Vec<Register>,
saves: Vec<Vec<Saved>>,
pub fonts: Vec<Font>,
pub int_pars: Vec<i64>,
pub sf_codes: rustc_hash::FxHashMap<char, i64>,
pub lc_codes: rustc_hash::FxHashMap<char, i64>,
pub last_badness: i64,
pub leader_box: Option<Node>,
pub output: output::Output,
pub pages: output::Pages,
pub hyphenation_source: String,
pub hyphenator: Option<std::rc::Rc<crate::linebreak::Hyphenator>>,
dirty: Vec<u16>,
pub said: Vec<Said>,
build_page_wanted: bool,
pub build_page_reason: &'static str,
pub line: i64,
pub baselines: crate::pack::Baselines,
pub split_top_skip: Glue,
pub split_max_depth: Scaled,
pub pack_begin_line: i64,
pub counts: [i64; 10],
pub h_offset: Scaled,
pub v_offset: Scaled,
pub par_shape: Vec<(Scaled, Scaled)>,
par_shape_level: usize,
pub math_target: Option<math::Target>,
pub just_box: Option<BoxNode>,
pub slot_writes: Vec<(i64, i64)>,
pub aligns: Vec<align::Align>,
pub align_display: Option<(Vec<Node>, Scaled)>,
pub mark_ids: rustc_hash::FxHashMap<String, u32>,
pub math_exten: rustc_hash::FxHashMap<usize, Vec<[u8; 4]>>,
}
impl Default for Stomach {
fn default() -> Self {
Self::new()
}
}
impl Stomach {
pub fn new() -> Stomach {
Stomach {
nest: vec![ListState::new(Mode::Vertical, Opened::Page)],
registers: vec![Register::default(); 256],
saves: Vec::new(),
fonts: vec![Font::null()],
int_pars: initex_int_pars(),
sf_codes: rustc_hash::FxHashMap::default(),
lc_codes: rustc_hash::FxHashMap::default(),
last_badness: 0,
leader_box: None,
output: output::Output::default(),
pages: output::Pages::default(),
hyphenation_source: String::new(),
hyphenator: None,
dirty: Vec::new(),
said: Vec::new(),
build_page_wanted: false,
build_page_reason: "",
line: 0,
baselines: crate::pack::Baselines::default(),
split_top_skip: Glue::default(),
split_max_depth: 0,
counts: [0; 10],
pack_begin_line: 0,
h_offset: 0,
v_offset: 0,
par_shape: Vec::new(),
par_shape_level: 1,
math_target: None,
just_box: None,
slot_writes: Vec::new(),
math_exten: rustc_hash::FxHashMap::default(),
mark_ids: rustc_hash::FxHashMap::default(),
aligns: Vec::new(),
align_display: None,
}
}
pub fn cur(&self) -> &ListState {
self.nest.last().expect("the outer list is never popped")
}
pub fn cur_mut(&mut self) -> &mut ListState {
self.nest
.last_mut()
.expect("the outer list is never popped")
}
pub fn mode(&self) -> Mode {
self.cur().mode
}
pub fn tail_append(&mut self, node: Node) {
let cur = self.cur_mut();
match cur.mode.kind() {
Kind::M => cur.mlist.push(crate::math::noad::Noad::Node(node)),
_ => cur.list.push(node),
}
}
pub fn int_par(&self, name: &str) -> i64 {
crate::intpar::index(name)
.and_then(|i| self.int_pars.get(i).copied())
.unwrap_or(0)
}
pub fn sf_code(&self, c: char) -> i64 {
match self.sf_codes.get(&c) {
Some(v) => *v,
None if c.is_ascii_uppercase() => 999,
None => 1000,
}
}
pub fn box_register(&self, n: u16) -> Option<&BoxNode> {
self.registers
.get(n as usize)
.and_then(|r| r.value.as_ref())
}
pub fn take_box(&mut self, n: u16) -> Option<BoxNode> {
let taken = self.registers.get_mut(n as usize)?.value.take();
self.dirty.push(n);
taken
}
pub fn box_register_mut(&mut self, n: u16) -> Option<&mut BoxNode> {
self.dirty.push(n);
self.registers.get_mut(n as usize)?.value.as_mut()
}
pub fn set_box(&mut self, n: u16, value: Option<BoxNode>, global: bool) {
if n as usize >= self.registers.len() {
self.registers.resize(n as usize + 1, Register::default());
}
self.dirty.push(n);
let level = self.saves.len() + 1;
let r = &mut self.registers[n as usize];
if global {
*r = Register { value, level: 1 };
return;
}
if r.level != level {
if let Some(frame) = self.saves.last_mut() {
frame.push(Saved::Box { n, old: r.clone() });
}
}
*r = Register { value, level };
}
pub fn group_begin(&mut self) {
self.saves.push(Vec::new());
}
pub fn group_end(&mut self) {
let Some(frame) = self.saves.pop() else {
return;
};
for s in frame.into_iter().rev() {
match s {
Saved::Box { n, old } => {
let r = &mut self.registers[n as usize];
if r.level != 1 {
*r = old;
}
self.dirty.push(n);
}
Saved::ParShape { old, level } => {
if self.par_shape_level != 1 {
self.par_shape = old;
self.par_shape_level = level;
}
}
}
}
}
pub fn set_par_shape(&mut self, shape: Vec<(Scaled, Scaled)>, global: bool) {
let level = self.saves.len() + 1;
if global {
self.par_shape = shape;
self.par_shape_level = 1;
return;
}
if self.par_shape_level != level {
if let Some(frame) = self.saves.last_mut() {
frame.push(Saved::ParShape {
old: std::mem::take(&mut self.par_shape),
level: self.par_shape_level,
});
}
}
self.par_shape = shape;
self.par_shape_level = level;
}
fn take_dirty(&mut self) -> Vec<u16> {
let mut d = std::mem::take(&mut self.dirty);
d.sort_unstable();
d.dedup();
d
}
pub fn font(&self, f: usize) -> &Font {
self.fonts.get(f).unwrap_or(&self.fonts[0])
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Said {
Error(String),
Diagnostic(String),
Report(String),
ReportOpen(String),
Terminal(String),
Glued(String),
}
impl Stomach {
pub fn say(&mut self, what: Said) {
self.said.push(what);
}
pub fn diagnostic(&mut self, text: &str) {
self.say(Said::Diagnostic(text.to_string()));
}
pub fn output_active(&self) -> bool {
self.nest.iter().any(|l| l.opened == Opened::Output)
}
pub fn esc_text(&self) -> String {
let e = self.int_par("escapechar");
match (0..256).contains(&e) {
true => char::from_u32(e as u32)
.map(String::from)
.unwrap_or_default(),
false => String::new(),
}
}
pub fn want_build_page(&mut self, reason: &'static str) {
self.build_page_wanted = true;
self.build_page_reason = reason;
}
pub fn take_build_page(&mut self) -> bool {
std::mem::take(&mut self.build_page_wanted)
}
pub fn refresh(&mut self, e: &dyn Eqtb) {
self.baselines = crate::pack::Baselines {
baseline_skip: glue_par(e, "baselineskip"),
line_skip: glue_par(e, "lineskip"),
line_skip_limit: dimen_par(e, "lineskiplimit"),
};
self.split_top_skip = glue_par(e, "splittopskip");
self.split_max_depth = dimen_par(e, "splitmaxdepth");
self.h_offset = dimen_par(e, "hoffset");
self.v_offset = dimen_par(e, "voffset");
for (i, c) in self.counts.iter_mut().enumerate() {
*c = e.slot(i as i64);
}
}
}
pub fn initex_int_pars() -> Vec<i64> {
let mut v = vec![0; crate::intpar::NAMES.len()];
for (name, value) in [
("mag", 1000),
("tolerance", 10000),
("hangafter", 1),
("maxdeadcycles", 25),
("escapechar", 92),
("endlinechar", 13),
] {
if let Some(i) = crate::intpar::index(name) {
v[i] = value;
}
}
v
}
pub struct Mirror;
pub const KIND_VOID: i64 = 0;
pub const KIND_HBOX: i64 = 1;
pub const KIND_VBOX: i64 = 2;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BoxDimen {
Wd,
Ht,
Dp,
}
pub fn box_dimen_slot(n: u16, which: BoxDimen) -> i64 {
let k = match which {
BoxDimen::Wd => 0,
BoxDimen::Ht => 1,
BoxDimen::Dp => 2,
};
crate::compiler::BOXDIM_BASE + 3 * i64::from(n) + k
}
pub fn box_kind_slot(n: u16) -> i64 {
crate::compiler::BOXKIND_BASE + i64::from(n)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Internal {
LastPenalty,
LastKern,
LastSkip,
Badness,
PrevDepth,
SpaceFactor,
PrevGraf,
PageGoal,
PageTotal,
PageStretch(u8),
PageShrink,
PageDepth,
DeadCycles,
InsertPenalties,
OutputPenalty,
Mark(u8),
}
impl Internal {
pub fn slot(self) -> i64 {
let k = match self {
Internal::LastPenalty => 0,
Internal::LastKern => 1,
Internal::LastSkip => 2,
Internal::Badness => 6,
Internal::PrevDepth => 7,
Internal::SpaceFactor => 8,
Internal::PrevGraf => 9,
Internal::PageGoal => 10,
Internal::PageTotal => 11,
Internal::PageStretch(o) => 12 + i64::from(o.min(3)),
Internal::PageShrink => 16,
Internal::PageDepth => 17,
Internal::DeadCycles => 18,
Internal::InsertPenalties => 19,
Internal::OutputPenalty => 20,
Internal::Mark(k) => 21 + i64::from(k.min(4)),
};
crate::compiler::INTERNAL_BASE + k
}
pub fn of_name(name: &str) -> Option<Internal> {
Some(match name {
"lastpenalty" => Internal::LastPenalty,
"lastkern" => Internal::LastKern,
"lastskip" => Internal::LastSkip,
"badness" => Internal::Badness,
"prevdepth" => Internal::PrevDepth,
"spacefactor" => Internal::SpaceFactor,
"prevgraf" => Internal::PrevGraf,
"pagegoal" => Internal::PageGoal,
"pagetotal" => Internal::PageTotal,
"pagestretch" => Internal::PageStretch(0),
"pagefilstretch" => Internal::PageStretch(1),
"pagefillstretch" => Internal::PageStretch(2),
"pagefilllstretch" => Internal::PageStretch(3),
"pageshrink" => Internal::PageShrink,
"pagedepth" => Internal::PageDepth,
"deadcycles" => Internal::DeadCycles,
"insertpenalties" => Internal::InsertPenalties,
"outputpenalty" => Internal::OutputPenalty,
_ => return None,
})
}
pub fn is_dimen(self) -> bool {
matches!(
self,
Internal::LastKern
| Internal::PrevDepth
| Internal::PageGoal
| Internal::PageTotal
| Internal::PageStretch(_)
| Internal::PageShrink
| Internal::PageDepth
)
}
}
pub const INTERNAL_SLOTS: i64 = 26;
pub trait SlotSink {
fn set(&mut self, slot: i64, value: i64);
}
impl Mirror {
pub fn flush(s: &mut Stomach, out: &mut dyn SlotSink) {
for n in s.take_dirty() {
let (kind, w, h, d) = match s.box_register(n) {
None => (KIND_VOID, 0, 0, 0),
Some(b) => (
if b.vertical { KIND_VBOX } else { KIND_HBOX },
b.width,
b.height,
b.depth,
),
};
if n < 256 {
out.set(box_kind_slot(n), kind);
out.set(box_dimen_slot(n, BoxDimen::Wd), w);
out.set(box_dimen_slot(n, BoxDimen::Ht), h);
out.set(box_dimen_slot(n, BoxDimen::Dp), d);
}
}
let (pen, kern, skip) = s.last_item();
out.set(Internal::LastPenalty.slot(), pen);
out.set(Internal::LastKern.slot(), kern);
let base = Internal::LastSkip.slot();
out.set(base, skip.natural);
out.set(base + 1, skip.stretch);
out.set(base + 2, skip.shrink);
out.set(base + 3, skip.stretch_order * 4 + skip.shrink_order);
out.set(Internal::Badness.slot(), s.last_badness);
let cur = s.cur();
out.set(Internal::PrevDepth.slot(), cur.prev_depth);
out.set(Internal::SpaceFactor.slot(), cur.space_factor);
out.set(Internal::PrevGraf.slot(), s.prev_graf());
s.output.mirror(out);
for (slot, value) in std::mem::take(&mut s.slot_writes) {
out.set(slot, value);
}
}
}
impl Stomach {
fn last_item(&self) -> (i64, Scaled, Glue) {
let cur = self.cur();
if self.nest.len() == 1 && cur.list.is_empty() {
return self.output.last_item();
}
match cur.list.last() {
Some(Node::Penalty(p)) => (*p, 0, Glue::default()),
Some(Node::Kern { width, .. }) => (0, *width, Glue::default()),
Some(Node::Glue(g)) => (0, 0, g.spec),
_ => (0, 0, Glue::default()),
}
}
pub fn prev_graf(&self) -> i64 {
self.nest
.iter()
.rev()
.find(|l| l.mode.kind() == Kind::V)
.map_or(0, |l| l.prev_graf)
}
pub fn set_prev_graf(&mut self, value: i64) {
if let Some(l) = self
.nest
.iter_mut()
.rev()
.find(|l| l.mode.kind() == Kind::V)
{
l.prev_graf = value;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hbox(width: Scaled) -> BoxNode {
BoxNode {
width,
..BoxNode::null()
}
}
#[test]
fn box_registers_obey_the_save_stack() {
let mut s = Stomach::new();
s.set_box(0, Some(hbox(1)), false);
s.group_begin();
s.set_box(0, Some(hbox(2)), false);
s.set_box(1, Some(hbox(3)), false);
s.set_box(1, Some(hbox(4)), true);
s.group_end();
assert_eq!(s.box_register(0).map(|b| b.width), Some(1));
assert_eq!(s.box_register(1).map(|b| b.width), Some(4));
}
#[test]
fn taking_a_box_is_not_undone_by_a_group() {
let mut s = Stomach::new();
s.set_box(5, Some(hbox(7)), false);
s.group_begin();
assert!(s.take_box(5).is_some());
s.group_end();
assert!(s.box_register(5).is_none());
}
struct Slots(rustc_hash::FxHashMap<i64, i64>);
impl SlotSink for Slots {
fn set(&mut self, slot: i64, value: i64) {
self.0.insert(slot, value);
}
}
#[test]
fn the_mirror_writes_what_ifvoid_and_wd_read() {
let mut s = Stomach::new();
let mut slots = Slots(Default::default());
s.set_box(3, Some(hbox(65536)), false);
Mirror::flush(&mut s, &mut slots);
assert_eq!(slots.0[&box_kind_slot(3)], KIND_HBOX);
assert_eq!(slots.0[&box_dimen_slot(3, BoxDimen::Wd)], 65536);
s.take_box(3);
Mirror::flush(&mut s, &mut slots);
assert_eq!(slots.0[&box_kind_slot(3)], KIND_VOID);
assert_eq!(slots.0[&box_dimen_slot(3, BoxDimen::Wd)], 0);
}
}