Share TeX hyphenation patterns and reuse verified state fingerprints

This commit is contained in:
gloamxun committed 2026-11-19 19:00:55 +08:00
1 parent 3ffa452fd1
commit 48c980c871
5 files changed
+150 -24

No files matched your search

+14 -5
View File
@@ -292,7 +292,7 @@ impl EntryCheckpoint {
files: &mut impl SourceProvider,
cancellation: Cancellation,
) -> Option<Result<Execution, ExecutionFailure>> {
self.resume_observed(source, files, cancellation, None, |_, _, _| {})
self.resume_observed(source, files, cancellation, None, None, |_, _, _| {})
}
pub(super) fn resume_capturing_entries_after_host_replay<F: SourceProvider, S>(
@@ -301,6 +301,7 @@ impl EntryCheckpoint {
files: &mut F,
cancellation: Cancellation,
line_break_cache: std::sync::Arc<super::LineBreakCache>,
previous: Option<&Execution>,
select: impl FnMut(usize, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Option<Result<Execution, ExecutionFailure>> {
@@ -309,6 +310,7 @@ impl EntryCheckpoint {
files,
cancellation,
Some(line_break_cache),
previous,
Executor::entry_observer(self.incoming_state, select, capture),
)
}
@@ -319,6 +321,7 @@ impl EntryCheckpoint {
files: &mut F,
cancellation: Cancellation,
line_break_cache: Option<std::sync::Arc<super::LineBreakCache>>,
previous: Option<&Execution>,
capture_boundary: impl FnMut(&mut Executor, usize, &mut F),
) -> Option<Result<Execution, ExecutionFailure>> {
if !self.accepts_entry(&source) {
@@ -335,7 +338,7 @@ impl EntryCheckpoint {
.check_cancellation()
.and_then(|_| executor.run_active_input(self.initial_depth, files, capture_boundary));
let result = executor.finish_observed_input(result, files);
Some(executor.finish_execution(result, self.incoming_state))
Some(executor.finish_execution(result, self.incoming_state, previous))
}
}
@@ -3037,7 +3040,7 @@ impl Executor {
) -> Result<Execution, ExecutionFailure> {
let incoming_state = self.state.fingerprint();
let result = self.run_observed(file, files, |_, _, _| {});
self.finish_execution(result, incoming_state)
self.finish_execution(result, incoming_state, None)
}
/// Capture the first eligible entry command boundary at or beyond the
/// requested physical byte. The callback captures the matching host state.
@@ -3086,7 +3089,7 @@ impl Executor {
files,
Self::entry_observer(incoming_state, select, capture),
);
self.finish_execution(result, incoming_state)
self.finish_execution(result, incoming_state, None)
}
fn entry_observer<F: SourceProvider, S>(
@@ -3146,6 +3149,7 @@ impl Executor {
mut self,
result: Result<(), Error>,
incoming_state: u64,
previous: Option<&Execution>,
) -> Result<Execution, ExecutionFailure> {
self.collect_meaning_reads();
if let Err(error) = result {
@@ -3183,6 +3187,11 @@ impl Executor {
evidence,
});
}
// An identical completed state has the same fingerprint. Compare
// the entire state, including token source spans and assignments.
let outgoing_state = previous
.filter(|last| last.state == self.state)
.map_or_else(|| self.state.fingerprint(), |last| last.outgoing_state);
Ok(Execution {
format_dumped: self.format_dumped,
job_name: self.job_name,
@@ -3191,7 +3200,7 @@ impl Executor {
events: self.events.into_vec(),
native_page: self.native_page,
split_discards: self.split_discards,
outgoing_state: self.state.fingerprint(),
outgoing_state,
state: self.state,
io: self.io,
input_position: self.input_position,
@@ -1,6 +1,10 @@
//! Native language tables and pattern trie. No implicit English dictionary.
use super::*;
use std::collections::BTreeMap;
use std::{
collections::BTreeMap,
hash::{Hash, Hasher},
sync::{Arc, OnceLock},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct HyphenationLanguage {
pub language: u8,
@@ -39,20 +43,48 @@ struct TrieNode {
edges: BTreeMap<u32, usize>,
weights: Vec<u8>,
}
// Job state and checkpoints share the pattern trie. Pattern assignments
// can still mutate it while building a format.
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
struct TrieNodes {
values: Vec<TrieNode>,
#[serde(skip)]
counts: OnceLock<(usize, usize)>,
}
impl PartialEq for TrieNodes {
fn eq(&self, other: &Self) -> bool {
self.values == other.values
}
}
impl Eq for TrieNodes {}
impl Hash for TrieNodes {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.values.hash(hasher);
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) struct HyphenationData {
nodes: Vec<TrieNode>,
nodes: Arc<TrieNodes>,
roots: BTreeMap<u8, usize>,
pub exceptions: BTreeMap<u8, BTreeMap<String, Vec<usize>>>,
pub sealed: bool,
}
impl HyphenationData {
pub(super) fn resource_counts(&self) -> (usize, usize, usize) {
(
self.nodes.len(),
self.nodes.iter().map(|n| n.edges.len()).sum(),
self.nodes.iter().map(|n| n.weights.len()).sum(),
)
let (edges, weights) = *self.nodes.counts.get_or_init(|| {
self.nodes
.values
.iter()
.fold((0, 0), |(edges, weights), node| {
(edges + node.edges.len(), weights + node.weights.len())
})
});
(self.nodes.values.len(), edges, weights)
}
pub fn insert(
&mut self,
@@ -61,34 +93,37 @@ impl HyphenationData {
weights: &[u8],
limit: usize,
) -> Result<(), String> {
let trie = Arc::make_mut(&mut self.nodes);
trie.counts.take();
let nodes = &mut trie.values;
let mut at = if let Some(&root) = self.roots.get(&language) {
root
} else {
let root = self.node(limit)?;
let root = Self::node(nodes, limit)?;
self.roots.insert(language, root);
root
};
for c in letters {
at = if let Some(&next) = self.nodes[at].edges.get(c) {
at = if let Some(&next) = nodes[at].edges.get(c) {
next
} else {
let next = self.node(limit)?;
self.nodes[at].edges.insert(*c, next);
let next = Self::node(nodes, limit)?;
nodes[at].edges.insert(*c, next);
next
};
}
if self.nodes[at].weights.iter().any(|v| *v != 0) {
if nodes[at].weights.iter().any(|v| *v != 0) {
return Err("duplicate hyphenation pattern".into());
}
self.nodes[at].weights = weights.to_vec();
nodes[at].weights = weights.to_vec();
Ok(())
}
fn node(&mut self, limit: usize) -> Result<usize, String> {
if self.nodes.len() >= limit {
fn node(nodes: &mut Vec<TrieNode>, limit: usize) -> Result<usize, String> {
if nodes.len() >= limit {
return Err("native hyphenation pattern memory limit exceeded".into());
}
let next = self.nodes.len();
self.nodes.push(TrieNode::default());
let next = nodes.len();
nodes.push(TrieNode::default());
Ok(next)
}
pub fn points(&self, language: u8, word: &str) -> Vec<usize> {
@@ -98,6 +133,7 @@ impl HyphenationData {
let Some(&root) = self.roots.get(&language) else {
return Vec::new();
};
let nodes = &self.nodes.values;
let letters: Vec<_> = std::iter::once(0)
.chain(word.chars().map(|c| c as u32))
.chain([0])
@@ -106,11 +142,11 @@ impl HyphenationData {
for start in 0..letters.len() {
let mut at = root;
for c in &letters[start..] {
let Some(&next) = self.nodes[at].edges.get(c) else {
let Some(&next) = nodes[at].edges.get(c) else {
break;
};
at = next;
for (i, &v) in self.nodes[at].weights.iter().enumerate() {
for (i, &v) in nodes[at].weights.iter().enumerate() {
scores[start + i] = scores[start + i].max(v);
}
}
@@ -120,3 +156,37 @@ impl HyphenationData {
.collect()
}
}
#[test]
fn cloned_patterns_remain_isolated_on_assignment() {
let mut format = HyphenationData::default();
let letters = ['t' as u32, 'e' as u32];
format.insert(0, &letters, &[0, 1, 0], 12).unwrap();
assert_eq!(format.resource_counts(), (3, 2, 3));
let shared = format.clone();
assert!(Arc::ptr_eq(&format.nodes, &shared.nodes));
format.insert(0, &['a' as u32], &[0, 0], 12).unwrap();
assert_eq!(format.resource_counts(), (4, 3, 5));
assert_eq!(shared.resource_counts(), (3, 2, 3));
assert_eq!(shared.points(0, "tea"), [1]);
assert_eq!(format.points(0, "tea"), [1]);
let encoded = serde_json::to_value(&shared).unwrap();
assert_eq!(
encoded["nodes"],
serde_json::to_value(&shared.nodes.values).unwrap()
);
let restored: HyphenationData = serde_json::from_value(encoded).unwrap();
assert_eq!(restored, shared);
assert_eq!(restored.resource_counts(), (3, 2, 3));
let hash = |nodes: &TrieNodes| {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
nodes.hash(&mut hasher);
hasher.finish()
};
let mut legacy = std::collections::hash_map::DefaultHasher::new();
shared.nodes.values.hash(&mut legacy);
assert_eq!(hash(&shared.nodes), legacy.finish());
}
@@ -207,11 +207,13 @@ impl RevisionJob {
select: impl FnMut(usize, usize) -> Option<S>,
capture: impl FnMut(S, EntryCheckpoint, &mut F),
) -> Option<Result<Arc<RevisionExecution>, RevisionFailure>> {
let previous = self.session.latest();
let executed = checkpoint.resume_capturing_entries_after_host_replay(
source,
files,
self.cancellation.clone(),
line_break_cache,
previous.as_deref().map(|revision| &revision.execution),
select,
capture,
)?;