Add the M1 box/glue/penalty paragraph builder
This commit is contained in:
1 parent
99dbb5ebb0
commit
51beb682f0
5 files changed
+282
-30
No files matched your search
@@ -555,9 +555,10 @@ Numeric bibliographies render authors as Surname, I. rather than full given name
|
|||||||
|
|
||||||
## Route D experimental core
|
## Route D experimental core
|
||||||
|
|
||||||
is the start of a TeX-compatible incremental layout
|
`crates/texrra-tex-core` is the start of a TeX-compatible incremental layout
|
||||||
core. It does not embed pdfTeX/XeTeX/Tectonic; it is a new Rust engine designed
|
core. It does not embed pdfTeX/XeTeX/Tectonic; it is a new Rust engine designed
|
||||||
around page-boundary checkpoints and page-hash diffing. M0 implements vertical
|
around page-boundary checkpoints and page-hash diffing. M0 implements vertical
|
||||||
boxes/glue, a simple page builder, serializable checkpoints and a page-local
|
boxes/glue, a simple page builder, serializable checkpoints and a page-local
|
||||||
edit demo. The production v1 engine remains the default until the new core
|
edit demo. M1 adds the horizontal box/glue/penalty model and a word-level
|
||||||
reaches layout parity. See .
|
Knuth-Plass-style paragraph builder. The production v1 engine remains the
|
||||||
|
default until the new core reaches layout parity. See `docs/TEX_CORE.md`.
|
||||||
@@ -1,3 +1,7 @@
|
|||||||
|
pub mod paragraph;
|
||||||
|
|
||||||
|
pub use paragraph::{HorizontalBox, HorizontalItem, Paragraph, ParagraphStyle, layout_paragraph};
|
||||||
|
|
||||||
use std::collections::hash_map::DefaultHasher;
|
use std::collections::hash_map::DefaultHasher;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
|
|
||||||
@@ -24,17 +28,25 @@ pub struct Unit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Unit {
|
impl Unit {
|
||||||
/// M0 placeholder for the real TeX paragraph builder: one line per 40
|
/// M1 paragraph builder: box/glue/penalty item stream with a
|
||||||
/// characters, 12pt baseline distance, 10pt text.
|
/// Knuth-Plass-style word-level line breaker.
|
||||||
pub fn paragraph(id: UnitId, source: impl Into<String>) -> Self {
|
pub fn paragraph(id: UnitId, source: impl Into<String>) -> Self {
|
||||||
|
Self::paragraph_with_style(id, source, ParagraphStyle::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn paragraph_with_style(
|
||||||
|
id: UnitId,
|
||||||
|
source: impl Into<String>,
|
||||||
|
style: ParagraphStyle,
|
||||||
|
) -> Self {
|
||||||
let source = source.into();
|
let source = source.into();
|
||||||
let lines = source.chars().count().div_ceil(40).max(1) as i64;
|
let paragraph = layout_paragraph(&source, &style);
|
||||||
Self {
|
Self {
|
||||||
id,
|
id,
|
||||||
source,
|
source,
|
||||||
items: vec![VerticalItem::Box(VerticalBox {
|
items: vec![VerticalItem::Box(VerticalBox {
|
||||||
width: 10 * 40,
|
width: paragraph.width.max(style.line_width),
|
||||||
height: lines * 12,
|
height: paragraph.height,
|
||||||
})],
|
})],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -195,17 +207,30 @@ impl Engine {
|
|||||||
next.units[unit_index].source = source.into();
|
next.units[unit_index].source = source.into();
|
||||||
next.units[unit_index] = Unit::paragraph(unit_id, next.units[unit_index].source.clone());
|
next.units[unit_index] = Unit::paragraph(unit_id, next.units[unit_index].source.clone());
|
||||||
|
|
||||||
let checkpoint = self
|
let mut checkpoint =
|
||||||
.layout
|
self.layout
|
||||||
.checkpoints
|
.checkpoints
|
||||||
.get(unit_index)
|
.get(unit_index)
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or(Checkpoint {
|
.unwrap_or(Checkpoint {
|
||||||
unit_index,
|
unit_index,
|
||||||
page_index: 0,
|
page_index: 0,
|
||||||
used: 0,
|
used: 0,
|
||||||
page_items: Vec::new(),
|
page_items: Vec::new(),
|
||||||
});
|
});
|
||||||
|
let edited_height: i64 = next.units[unit_index]
|
||||||
|
.items
|
||||||
|
.iter()
|
||||||
|
.map(|item| match item {
|
||||||
|
VerticalItem::Box(vertical_box) => vertical_box.height,
|
||||||
|
VerticalItem::Glue(height) | VerticalItem::Penalty(height) => *height,
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
if checkpoint.used + edited_height > next.page_goal && !checkpoint.page_items.is_empty() {
|
||||||
|
checkpoint.page_index += 1;
|
||||||
|
checkpoint.used = 0;
|
||||||
|
checkpoint.page_items.clear();
|
||||||
|
}
|
||||||
let old_pages = self.layout.pages.clone();
|
let old_pages = self.layout.pages.clone();
|
||||||
let mut pages = old_pages[..checkpoint.page_index].to_vec();
|
let mut pages = old_pages[..checkpoint.page_index].to_vec();
|
||||||
let mut current = Page {
|
let mut current = Page {
|
||||||
|
|||||||
Executable
+205
@@ -0,0 +1,205 @@
|
|||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// A horizontal box in scaled points (1/65536 pt).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
pub struct HorizontalBox {
|
||||||
|
pub width: i64,
|
||||||
|
pub height: i64,
|
||||||
|
pub depth: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
|
pub enum HorizontalItem {
|
||||||
|
Box(HorizontalBox),
|
||||||
|
Glue {
|
||||||
|
width: i64,
|
||||||
|
stretch: i64,
|
||||||
|
shrink: i64,
|
||||||
|
},
|
||||||
|
Penalty {
|
||||||
|
width: i64,
|
||||||
|
penalty: i64,
|
||||||
|
flagged: bool,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct ParagraphStyle {
|
||||||
|
pub line_width: i64,
|
||||||
|
pub par_indent: i64,
|
||||||
|
pub line_height: i64,
|
||||||
|
pub char_width: i64,
|
||||||
|
pub space_width: i64,
|
||||||
|
pub space_stretch: i64,
|
||||||
|
pub space_shrink: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ParagraphStyle {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
line_width: 400,
|
||||||
|
par_indent: 0,
|
||||||
|
line_height: 12,
|
||||||
|
char_width: 10,
|
||||||
|
space_width: 4,
|
||||||
|
space_stretch: 6,
|
||||||
|
space_shrink: 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct Paragraph {
|
||||||
|
pub lines: Vec<Vec<HorizontalItem>>,
|
||||||
|
pub height: i64,
|
||||||
|
pub width: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Paragraph {
|
||||||
|
pub fn line_count(&self) -> usize {
|
||||||
|
self.lines.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// M1 word-level Knuth-Plass approximation.
|
||||||
|
///
|
||||||
|
/// The real TeX paragraph builder will operate on an item stream with
|
||||||
|
/// discretionary hyphens and penalties. This version keeps the same glue
|
||||||
|
/// stretch/shrink cost model but only breaks at spaces; it is deliberately
|
||||||
|
/// isolated so the DP can be replaced without touching the page builder.
|
||||||
|
pub fn layout_paragraph(text: &str, style: &ParagraphStyle) -> Paragraph {
|
||||||
|
let words: Vec<&str> = text.split_whitespace().collect();
|
||||||
|
if words.is_empty() {
|
||||||
|
return Paragraph {
|
||||||
|
lines: Vec::new(),
|
||||||
|
height: 0,
|
||||||
|
width: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let widths: Vec<i64> = words
|
||||||
|
.iter()
|
||||||
|
.map(|word| word.chars().count() as i64 * style.char_width)
|
||||||
|
.collect();
|
||||||
|
let count = words.len();
|
||||||
|
let mut best = vec![i64::MAX; count + 1];
|
||||||
|
let mut previous = vec![0_usize; count + 1];
|
||||||
|
best[0] = 0;
|
||||||
|
for end in 1..=count {
|
||||||
|
for start in 0..end {
|
||||||
|
if best[start] == i64::MAX {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let natural: i64 = widths[start..end].iter().sum::<i64>()
|
||||||
|
+ style.space_width * (end - start - 1) as i64;
|
||||||
|
let target = style.line_width - if start == 0 { style.par_indent } else { 0 };
|
||||||
|
let (ratio, overfull) = if natural <= target {
|
||||||
|
let stretch = style.space_stretch * (end - start - 1) as i64;
|
||||||
|
if stretch == 0 {
|
||||||
|
// A single word has no interword glue to stretch. Treat it
|
||||||
|
// as an extremely loose line instead of a free break.
|
||||||
|
let slack = (target - natural).max(1) as f64;
|
||||||
|
(slack / style.space_stretch.max(1) as f64, false)
|
||||||
|
} else {
|
||||||
|
((target - natural) as f64 / stretch as f64, false)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let shrink = style.space_shrink * (end - start - 1) as i64;
|
||||||
|
if shrink == 0 {
|
||||||
|
((natural - target) as f64, true)
|
||||||
|
} else {
|
||||||
|
let ratio = (natural - target) as f64 / shrink as f64;
|
||||||
|
(ratio, ratio > 1.0)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let badness = (100.0 * ratio.abs().powi(3)).min(10_000.0) as i64;
|
||||||
|
let overfull_penalty = if overfull { 100_000 } else { 0 };
|
||||||
|
let cost = badness
|
||||||
|
.saturating_mul(badness)
|
||||||
|
.saturating_add(overfull_penalty);
|
||||||
|
if cost < best[end] {
|
||||||
|
best[end] = cost;
|
||||||
|
previous[end] = start;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut ranges = Vec::new();
|
||||||
|
let mut end = count;
|
||||||
|
while end > 0 {
|
||||||
|
let start = previous[end].min(end - 1);
|
||||||
|
ranges.push((start, end));
|
||||||
|
end = start;
|
||||||
|
}
|
||||||
|
ranges.reverse();
|
||||||
|
let mut lines = Vec::with_capacity(ranges.len());
|
||||||
|
let mut max_width = 0;
|
||||||
|
for (start, end) in ranges {
|
||||||
|
let mut line = Vec::new();
|
||||||
|
let mut width = 0;
|
||||||
|
for index in start..end {
|
||||||
|
if index > start {
|
||||||
|
line.push(HorizontalItem::Glue {
|
||||||
|
width: style.space_width,
|
||||||
|
stretch: style.space_stretch,
|
||||||
|
shrink: style.space_shrink,
|
||||||
|
});
|
||||||
|
width += style.space_width;
|
||||||
|
}
|
||||||
|
line.push(HorizontalItem::Box(HorizontalBox {
|
||||||
|
width: widths[index],
|
||||||
|
height: style.line_height,
|
||||||
|
depth: 0,
|
||||||
|
}));
|
||||||
|
width += widths[index];
|
||||||
|
}
|
||||||
|
if end == count {
|
||||||
|
line.push(HorizontalItem::Penalty {
|
||||||
|
width: 0,
|
||||||
|
penalty: 10_000,
|
||||||
|
flagged: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
max_width = max_width.max(width);
|
||||||
|
lines.push(line);
|
||||||
|
}
|
||||||
|
Paragraph {
|
||||||
|
height: lines.len() as i64 * style.line_height,
|
||||||
|
width: max_width,
|
||||||
|
lines,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn words_break_at_spaces_and_use_glue() {
|
||||||
|
let style = ParagraphStyle {
|
||||||
|
line_width: 100,
|
||||||
|
..ParagraphStyle::default()
|
||||||
|
};
|
||||||
|
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
|
||||||
|
assert_eq!(paragraph.line_count(), 2);
|
||||||
|
assert!(
|
||||||
|
paragraph.lines[0]
|
||||||
|
.iter()
|
||||||
|
.any(|item| matches!(item, HorizontalItem::Glue { .. }))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn first_line_respects_par_indent() {
|
||||||
|
let style = ParagraphStyle {
|
||||||
|
line_width: 100,
|
||||||
|
par_indent: 20,
|
||||||
|
..ParagraphStyle::default()
|
||||||
|
};
|
||||||
|
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
|
||||||
|
assert!(paragraph.line_count() >= 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_paragraph_has_no_lines() {
|
||||||
|
assert_eq!(layout_paragraph("", &ParagraphStyle::default()).height, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -163,3 +163,5 @@ See `docs/ROADMAP.md` for concrete implementation plans.
|
|||||||
incremental engine. It has vertical boxes/glue/penalties, page-boundary
|
incremental engine. It has vertical boxes/glue/penalties, page-boundary
|
||||||
checkpoints, page hashes and a page-local edit test. It is not yet wired into
|
checkpoints, page hashes and a page-local edit test. It is not yet wired into
|
||||||
the server; the v1 engine remains the production path.
|
the server; the v1 engine remains the production path.
|
||||||
|
|
||||||
|
- Route D core: M0 checkpoint spike plus M1 word-level box/glue/penalty paragraph builder in `crates/texrra-tex-core`; seven core tests. v1 remains the default.
|
||||||
+30
-11
@@ -1,6 +1,6 @@
|
|||||||
# TeX-compatible incremental core (route D)
|
# TeX-compatible incremental core (route D)
|
||||||
|
|
||||||
Status: **M0 architecture spike implemented** in `crates/texrra-tex-core`.
|
Status: **M0 architecture spike + M1 paragraph builder implemented** in `crates/texrra-tex-core`.
|
||||||
The production v1 engine in `src/rust_typeset` remains the default and is kept as
|
The production v1 engine in `src/rust_typeset` remains the default and is kept as
|
||||||
a fallback while the TeX-compatible core grows.
|
a fallback while the TeX-compatible core grows.
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ operation from the start. It does **not** embed pdfTeX, XeTeX or Tectonic.
|
|||||||
|
|
||||||
- `VerticalItem::{Box, Glue, Penalty}` and `VerticalBox` as the first vertical
|
- `VerticalItem::{Box, Glue, Penalty}` and `VerticalBox` as the first vertical
|
||||||
list model;
|
list model;
|
||||||
- `Unit::paragraph` as a placeholder for the future TeX paragraph builder;
|
- `Unit::paragraph` backed by the M1 box/glue/penalty paragraph builder;
|
||||||
- `Engine::layout` that builds pages with a simple page goal;
|
- `Engine::layout` that builds pages with a simple page goal;
|
||||||
- `Checkpoint` before every top-level unit, containing the completed-page count,
|
- `Checkpoint` before every top-level unit, containing the completed-page count,
|
||||||
used vertical space and current page items;
|
used vertical space and current page items;
|
||||||
@@ -32,8 +32,26 @@ operation from the start. It does **not** embed pdfTeX, XeTeX or Tectonic.
|
|||||||
`recomputed_pages`;
|
`recomputed_pages`;
|
||||||
- serde round-trip for checkpoints.
|
- serde round-trip for checkpoints.
|
||||||
|
|
||||||
M0 proves the incremental contract, not TeX compatibility. The paragraph
|
M0 proves the incremental contract; M1 starts replacing the placeholder with
|
||||||
builder, page builder, math, fonts and class execution are still ahead.
|
horizontal material and a paragraph breaker. The page builder, math, fonts and
|
||||||
|
class execution are still ahead.
|
||||||
|
|
||||||
|
## M1 scope (paragraph builder)
|
||||||
|
|
||||||
|
`crates/texrra-tex-core/src/paragraph.rs` adds:
|
||||||
|
|
||||||
|
- `HorizontalItem::{Box, Glue, Penalty}` and `HorizontalBox` as the horizontal
|
||||||
|
list model;
|
||||||
|
- `ParagraphStyle` with `line_width`, `par_indent`, `line_height`, fixed
|
||||||
|
character/space metrics and glue stretch/shrink;
|
||||||
|
- a word-level Knuth-Plass-style dynamic program that minimizes badness from
|
||||||
|
glue stretch/shrink, allows overfull lines with an explicit overfull penalty,
|
||||||
|
applies `par_indent` to the first line, and emits justified glue;
|
||||||
|
- `Paragraph { lines, height, width }` and a paragraph-backed `Unit`.
|
||||||
|
|
||||||
|
M1 is deliberately word-level: it does not yet hyphenate, process
|
||||||
|
`\discretionary`, use real TFM metrics or compare against pdfTeX. Those are the
|
||||||
|
next paragraph milestones.
|
||||||
|
|
||||||
## Target architecture
|
## Target architecture
|
||||||
|
|
||||||
@@ -50,7 +68,7 @@ builder, page builder, math, fonts and class execution are still ahead.
|
|||||||
| Milestone | Content | Acceptance |
|
| Milestone | Content | Acceptance |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 |
|
| M0 | vertical list, page builder, checkpoint, page hash, edit demo | edit on page 2 rebuilds only page 2 |
|
||||||
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | line breaks match pdfTeX for test paragraphs |
|
| M1 | TeX box/glue/penalty + paragraph builder (`\par`, `\hsize`, `\parindent`) | **partial**: item model + word-level breaker implemented; hyphenation/TFM/pdfTeX parity next |
|
||||||
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | one-column article matches reference pages |
|
| M2 | page builder + `\output`, `\vsize`, `\topskip`, footnotes, floats | one-column article matches reference pages |
|
||||||
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | table width/rules match reference |
|
| M3 | `\halign`, `\omit`, `\span`, `\multispan`, booktabs/longtable | table width/rules match reference |
|
||||||
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | arXiv formulas render without overlap |
|
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | arXiv formulas render without overlap |
|
||||||
@@ -60,10 +78,10 @@ builder, page builder, math, fonts and class execution are still ahead.
|
|||||||
|
|
||||||
## Current limits
|
## Current limits
|
||||||
|
|
||||||
- The M0 paragraph model is a character-count placeholder; it does not run the
|
- The M1 paragraph builder is word-level with fixed metrics; it does not yet
|
||||||
TeX paragraph algorithm yet.
|
hyphenate, honor all penalties, or use TFM font metrics.
|
||||||
- Page breaking only handles vertical boxes/glue; penalties are recorded but not
|
- Page breaking only handles vertical boxes/glue; vertical penalties are recorded
|
||||||
interpreted.
|
but not interpreted.
|
||||||
- No macro state, output routine, math, fonts or PDF output in the new core yet.
|
- No macro state, output routine, math, fonts or PDF output in the new core yet.
|
||||||
- The v1 server and project API still use `src/rust_typeset` and are unchanged.
|
- The v1 server and project API still use `src/rust_typeset` and are unchanged.
|
||||||
|
|
||||||
@@ -73,5 +91,6 @@ builder, page builder, math, fonts and class execution are still ahead.
|
|||||||
cargo test -p texrra-tex-core --offline
|
cargo test -p texrra-tex-core --offline
|
||||||
```
|
```
|
||||||
|
|
||||||
The four M0 tests cover page splitting, checkpoint serialization and
|
The M0 tests cover page splitting, checkpoint serialization and page-local
|
||||||
page-local editing.
|
editing. Three M1 tests cover glue-based line breaking, paragraph indentation and
|
||||||
|
empty paragraphs.
|
||||||
Reference in new issue
Block a user