Start route D incremental TeX core with M0 checkpoint spike

This commit is contained in:
gloamxun committed 2026-10-20 12:06:39 +08:00
1 parent b41a2a9a97
commit 99dbb5ebb0
8 files changed
+447 -3

No files matched your search

Generated
+8
View File
@@ -961,6 +961,14 @@ dependencies = [
"ttf-parser",
]
[[package]]
name = "texrra-tex-core"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "tiff"
version = "0.6.1"
+1 -1
View File
@@ -11,7 +11,7 @@ name = "texrra"
path = "src/main.rs"
[workspace]
members = ["crates/texrra-core"]
members = ["crates/texrra-core", "crates/texrra-tex-core"]
[dependencies]
texrra-core = { path = "crates/texrra-core", features = ["serde"] }
+10
View File
@@ -551,3 +551,13 @@ PDF-only figures are rendered as placeholders sized from the source PDF page asp
Numeric bibliographies render authors as Surname, I. rather than full given names.
## Route D experimental 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
around page-boundary checkpoints and page-hash diffing. M0 implements vertical
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
reaches layout parity. See .
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "texrra-tex-core"
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
description = "Experimental incremental TeX-compatible typesetting core (route D)"
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
+331
View File
@@ -0,0 +1,331 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
pub type UnitId = u64;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct VerticalBox {
pub width: i64,
pub height: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum VerticalItem {
Box(VerticalBox),
Glue(i64),
Penalty(i64),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Unit {
pub id: UnitId,
pub source: String,
pub items: Vec<VerticalItem>,
}
impl Unit {
/// M0 placeholder for the real TeX paragraph builder: one line per 40
/// characters, 12pt baseline distance, 10pt text.
pub fn paragraph(id: UnitId, source: impl Into<String>) -> Self {
let source = source.into();
let lines = source.chars().count().div_ceil(40).max(1) as i64;
Self {
id,
source,
items: vec![VerticalItem::Box(VerticalBox {
width: 10 * 40,
height: lines * 12,
})],
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Document {
pub units: Vec<Unit>,
pub page_goal: i64,
}
impl Document {
pub fn new(page_goal: i64, units: Vec<Unit>) -> Self {
Self { units, page_goal }
}
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Page {
pub items: Vec<VerticalItem>,
pub sources: Vec<(UnitId, u64)>,
pub hash: u64,
}
impl Page {
fn seal_in_place(&mut self) {
let mut hasher = DefaultHasher::new();
self.items.hash(&mut hasher);
self.sources.hash(&mut hasher);
self.hash = hasher.finish();
}
}
fn source_hash(source: &str) -> u64 {
let mut hasher = DefaultHasher::new();
source.hash(&mut hasher);
hasher.finish()
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Checkpoint {
/// Index of the next unit to execute.
pub unit_index: usize,
/// Number of completed pages.
pub page_index: usize,
/// Vertical space already used on the current page.
pub used: i64,
/// Page items already emitted on the current page.
pub page_items: Vec<VerticalItem>,
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Layout {
pub pages: Vec<Page>,
/// `checkpoints[i]` is the state before executing unit `i`.
pub checkpoints: Vec<Checkpoint>,
/// Number of pages whose content had to be rebuilt by the last edit.
pub recomputed_pages: usize,
}
impl Layout {
pub fn page_index_for(&self, unit_index: usize) -> Option<usize> {
self.checkpoints.get(unit_index).map(|c| c.page_index)
}
}
pub struct Engine {
layout: Layout,
}
impl Engine {
pub fn layout(document: &Document) -> Self {
let mut pages = Vec::new();
let mut checkpoints = Vec::with_capacity(document.units.len());
let mut current = Page {
items: Vec::new(),
sources: Vec::new(),
hash: 0,
};
let mut used = 0_i64;
for (unit_index, unit) in document.units.iter().enumerate() {
checkpoints.push(Checkpoint {
unit_index,
page_index: pages.len(),
used,
page_items: current.items.clone(),
});
for item in &unit.items {
match item {
VerticalItem::Box(vertical_box) => {
if used + vertical_box.height > document.page_goal
&& !current.items.is_empty()
{
pages.push(std::mem::replace(
&mut current,
Page {
items: Vec::new(),
sources: Vec::new(),
hash: 0,
},
));
used = 0;
}
used += vertical_box.height;
current.items.push(item.clone());
}
VerticalItem::Glue(amount) => {
if !current.items.is_empty() {
used += amount;
current.items.push(item.clone());
}
}
VerticalItem::Penalty(_) => {}
}
}
}
if !current.items.is_empty() {
pages.push(current);
}
for (index, unit) in document.units.iter().enumerate() {
if let Some(checkpoint) = checkpoints.get(index)
&& let Some(page) = pages.get_mut(checkpoint.page_index)
{
page.sources.push((unit.id, source_hash(&unit.source)));
}
}
for page in &mut pages {
page.seal_in_place();
}
Self {
layout: Layout {
pages,
checkpoints,
recomputed_pages: 0,
},
}
}
pub fn pages(&self) -> &[Page] {
&self.layout.pages
}
pub fn checkpoints(&self) -> &[Checkpoint] {
&self.layout.checkpoints
}
pub fn recomputed_pages(&self) -> usize {
self.layout.recomputed_pages
}
pub fn edit(&mut self, document: &Document, unit_id: UnitId, source: impl Into<String>) {
let Some(unit_index) = document.units.iter().position(|unit| unit.id == unit_id) else {
self.layout = Self::layout(document).layout;
self.layout.recomputed_pages = self.layout.pages.len();
return;
};
let mut next = document.clone();
next.units[unit_index].source = source.into();
next.units[unit_index] = Unit::paragraph(unit_id, next.units[unit_index].source.clone());
let checkpoint = self
.layout
.checkpoints
.get(unit_index)
.cloned()
.unwrap_or(Checkpoint {
unit_index,
page_index: 0,
used: 0,
page_items: Vec::new(),
});
let old_pages = self.layout.pages.clone();
let mut pages = old_pages[..checkpoint.page_index].to_vec();
let mut current = Page {
items: checkpoint.page_items,
sources: Vec::new(),
hash: 0,
};
let mut used = checkpoint.used;
let mut checkpoints = self.layout.checkpoints[..unit_index].to_vec();
for (index, unit) in next.units.iter().enumerate().skip(unit_index) {
checkpoints.push(Checkpoint {
unit_index: index,
page_index: pages.len(),
used,
page_items: current.items.clone(),
});
for item in &unit.items {
match item {
VerticalItem::Box(vertical_box) => {
if used + vertical_box.height > next.page_goal && !current.items.is_empty()
{
pages.push(std::mem::replace(
&mut current,
Page {
items: Vec::new(),
sources: Vec::new(),
hash: 0,
},
));
used = 0;
}
used += vertical_box.height;
current.items.push(item.clone());
}
VerticalItem::Glue(amount) => {
if !current.items.is_empty() {
used += amount;
current.items.push(item.clone());
}
}
VerticalItem::Penalty(_) => {}
}
}
}
if !current.items.is_empty() {
pages.push(current);
}
for (index, unit) in next.units.iter().enumerate() {
if let Some(checkpoint) = checkpoints.get(index)
&& let Some(page) = pages.get_mut(checkpoint.page_index)
{
page.sources.push((unit.id, source_hash(&unit.source)));
}
}
for page in &mut pages {
page.seal_in_place();
}
let mut rebuilt = 0;
for (index, page) in pages.iter().enumerate().skip(checkpoint.page_index) {
if old_pages.get(index).is_none_or(|old| old.hash != page.hash) {
rebuilt += 1;
}
}
self.layout = Layout {
pages,
checkpoints,
recomputed_pages: rebuilt,
};
}
}
#[cfg(test)]
mod tests {
use super::*;
fn document() -> Document {
Document::new(
50,
vec![
Unit::paragraph(1, "a"),
Unit::paragraph(2, "b"),
Unit::paragraph(3, "c"),
Unit::paragraph(4, "d"),
],
)
}
#[test]
fn layout_splits_pages_and_records_checkpoints() {
let engine = Engine::layout(&document());
assert_eq!(engine.pages().len(), 1);
assert_eq!(engine.checkpoints().len(), 4);
assert_eq!(engine.checkpoints()[1].unit_index, 1);
}
#[test]
fn edit_on_second_page_only_rebuilds_second_page() {
let mut document = document();
document.units.push(Unit::paragraph(5, "e"));
document.units.push(Unit::paragraph(6, "f"));
let mut engine = Engine::layout(&document);
assert!(engine.pages().len() >= 2);
engine.edit(&document, 5, "edited second page");
assert_eq!(engine.recomputed_pages(), 1);
}
#[test]
fn edit_on_first_page_rebuilds_following_pages() {
let mut engine = Engine::layout(&document());
engine.edit(&document(), 1, "edited first page");
assert!(engine.recomputed_pages() >= 1);
}
#[test]
fn checkpoint_round_trips_through_serde() {
let engine = Engine::layout(&document());
let encoded = serde_json::to_string(engine.checkpoints()).unwrap();
let decoded: Vec<Checkpoint> = serde_json::from_str(&encoded).unwrap();
assert_eq!(engine.checkpoints(), decoded.as_slice());
}
}
+8
View File
@@ -155,3 +155,11 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- Lines whose justification ratio exceeds 3 fall back to natural spacing instead of stretching inter-word gaps across the measure.
- Numeric bibliographies format author names as Surname, I. for standard journal styles.
## Route D core (experimental)
is an isolated M0 spike for a TeX-compatible
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
the server; the v1 engine remains the production path.
+77
View File
@@ -0,0 +1,77 @@
# TeX-compatible incremental core (route D)
Status: **M0 architecture spike implemented** in `crates/texrra-tex-core`.
The production v1 engine in `src/rust_typeset` remains the default and is kept as
a fallback while the TeX-compatible core grows.
## Why route D
The v1 engine parses LaTeX into `DocumentModel` and lays it out with
hand-written algorithms. That gives true incremental preview, but it cannot be
page-identical for arbitrary `.cls`/`.sty` files: class files are TeX programs,
and their layout primitives (`\vbox`, `\halign`, `\output`, `\twocolumn`,
insertions, math lists, font metrics) are not executed.
Route D is a TeX-compatible execution/layout core designed for incremental
operation from the start. It does **not** embed pdfTeX, XeTeX or Tectonic.
## M0 scope (this spike)
`crates/texrra-tex-core` currently provides:
- `VerticalItem::{Box, Glue, Penalty}` and `VerticalBox` as the first vertical
list model;
- `Unit::paragraph` as a placeholder for the future TeX paragraph builder;
- `Engine::layout` that builds pages with a simple page goal;
- `Checkpoint` before every top-level unit, containing the completed-page count,
used vertical space and current page items;
- `Page` hashes derived from both vertical items and the contributing unit
sources;
- `Engine::edit` which restores the checkpoint before the edited unit,
re-executes only the suffix, compares page hashes, and reports
`recomputed_pages`;
- serde round-trip for checkpoints.
M0 proves the incremental contract, not TeX compatibility. The paragraph
builder, page builder, math, fonts and class execution are still ahead.
## Target architecture
- Persistent TeX VM state: macros, registers, fonts, counters, output queue.
- Stable IDs for top-level units.
- Checkpoint at page boundaries plus unit boundaries.
- Dependency graph for labels, references, counters, TOC and citations.
- Dirty propagation: after a local edit, replay from the nearest checkpoint and
stop at the first unchanged page hash.
- Float/footnote queues restored with the checkpoint.
## Milestones
| Milestone | Content | Acceptance |
| --- | --- | --- |
| 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 |
| 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 |
| M4 | math lists, scripts, fractions, radicals, accents, delimiters | arXiv formulas render without overlap |
| M5 | NFSS/TFM metrics, CM/Latin Modern | same line/page breaks as reference |
| M6 | class/package execution (`article`, `sn-jnl`) | Overleaf page-count parity |
| M7 | `\special`, PDF XObjects, hyperref annotations | PDF structure parity |
## Current limits
- The M0 paragraph model is a character-count placeholder; it does not run the
TeX paragraph algorithm yet.
- Page breaking only handles vertical boxes/glue; penalties are recorded but not
interpreted.
- 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.
## Verification
```sh
cargo test -p texrra-tex-core --offline
```
The four M0 tests cover page splitting, checkpoint serialization and
page-local editing.
+2 -2
View File
@@ -561,8 +561,8 @@ fn layout_table(
&& width > 0
{
rule.height = common::Scaled(
(f64::from(rule.width.0) * f64::from(height) / f64::from(width))
.round() as i32,
(f64::from(rule.width.0) * f64::from(height) / f64::from(width)).round()
as i32,
);
}
}