Reuse exact hash input for shared macro meanings

This commit is contained in:
gloamxun committed 2026-12-02 01:35:49 +08:00
1 parent c4003c8dad
commit ed105bdd39
3 files changed
+324 -90

No files matched your search

+99 -90
View File
@@ -1,9 +1,14 @@
mod fingerprint;
pub(super) mod source_relocation;
use fingerprint::{FingerprintHasher, MacroFingerprintInputs};
use hashbrown::HashMap;
use std::collections::BTreeMap;
use std::hash::{BuildHasher, DefaultHasher, Hash, Hasher, RandomState};
use std::sync::{Arc, OnceLock};
use std::hash::{BuildHasher, Hash, Hasher, RandomState};
#[cfg(test)]
use std::hash::DefaultHasher;
use std::sync::{Arc, Mutex, OnceLock};
use super::{
CatCode, FontId, Glue, JobParameter, JobTime, NativeBox, Parameter, ParameterValue, Register,
@@ -856,6 +861,7 @@ struct CommandBindings {
revisions: [u64; COMMAND_SHARDS],
// Cache names only so redefinitions can share the same order.
ordered_names: OrderedCommandNames,
fingerprint_inputs: Arc<Mutex<MacroFingerprintInputs>>,
}
impl Default for CommandBindings {
@@ -867,6 +873,7 @@ impl Default for CommandBindings {
}),
revisions: [0; COMMAND_SHARDS],
ordered_names: Arc::default(),
fingerprint_inputs: Arc::default(),
}
}
}
@@ -959,6 +966,22 @@ impl CommandBindings {
}
}
impl CommandBindings {
fn hash_fingerprint(&self, hasher: &mut FingerprintHasher) {
let Ok(mut inputs) = self.fingerprint_inputs.try_lock() else {
self.hash(hasher);
return;
};
inputs.prune_if_full();
let entries = self.ordered();
entries.len().hash(hasher);
for (name, meaning) in entries {
name.hash(hasher);
inputs.hash_meaning(meaning, hasher);
}
}
}
impl Hash for CommandBindings {
fn hash<H: Hasher>(&self, hasher: &mut H) {
let entries = self.ordered();
@@ -988,11 +1011,29 @@ impl<'de> serde::Deserialize<'de> for CommandBindings {
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State {
// Checkpoints share the table. A write copies just its command shard.
// Formats and fingerprints use key order.
commands: Arc<CommandBindings>,
// Derive the ordinary hash and emit the specialized fingerprint in the
// same field order. Only the command meanings can reuse recorded hash input.
macro_rules! define_state {
($( $(#[$metadata:meta])* $access:vis $field:ident: $ty:ty, )*) => {
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct State {
// Checkpoints share the table. A write copies just its command shard.
commands: Arc<CommandBindings>,
$( $(#[$metadata])* $access $field: $ty, )*
}
impl State {
pub fn fingerprint(&self) -> u64 {
let mut hash = FingerprintHasher::default();
self.commands.hash_fingerprint(&mut hash);
$(self.$field.hash(&mut hash);)*
hash.finish()
}
}
};
}
define_state! {
catcodes: BTreeMap<char, CatCode>,
counts: BTreeMap<u16, i32>,
toks: BTreeMap<u16, Vec<Token>>,
@@ -1075,84 +1116,6 @@ pub struct State {
pub(super) hyphenation: super::hyphenation::HyphenationData,
}
// Batch the many small token and integer writes in a state fingerprint.
// The ordered bytes still go through the native state fingerprint's hasher.
struct FingerprintHasher {
hasher: DefaultHasher,
buffer: [u8; 4096],
used: usize,
}
impl Default for FingerprintHasher {
fn default() -> Self {
Self {
hasher: DefaultHasher::new(),
buffer: [0; 4096],
used: 0,
}
}
}
impl FingerprintHasher {
#[inline]
fn write_fixed<const N: usize>(&mut self, bytes: [u8; N]) {
if N > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
let end = self.used + N;
self.buffer[self.used..end].copy_from_slice(&bytes);
self.used = end;
}
}
impl Hasher for FingerprintHasher {
#[inline]
fn write_u8(&mut self, value: u8) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u16(&mut self, value: u16) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u32(&mut self, value: u32) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_u64(&mut self, value: u64) {
self.write_fixed(value.to_ne_bytes());
}
#[inline]
fn write_usize(&mut self, value: usize) {
self.write_fixed(value.to_ne_bytes());
}
fn write(&mut self, bytes: &[u8]) {
if bytes.len() > self.buffer.len() - self.used {
self.hasher.write(&self.buffer[..self.used]);
self.used = 0;
}
if bytes.len() > self.buffer.len() {
self.hasher.write(bytes);
} else {
let end = self.used + bytes.len();
self.buffer[self.used..end].copy_from_slice(bytes);
self.used = end;
}
}
fn finish(&self) -> u64 {
let mut hasher = self.hasher.clone();
hasher.write(&self.buffer[..self.used]);
hasher.finish()
}
}
#[test]
fn buffered_fingerprint_matches_the_ordered_state_hash() {
let mut state = State::initex().with_etex();
@@ -1178,6 +1141,57 @@ fn buffered_fingerprint_matches_the_ordered_state_hash() {
check(&state);
}
#[test]
fn cached_macro_fingerprint_preserves_aliases_mutations_and_uncached_hashes() {
use super::Span;
let check = |state: &State| {
let mut direct = DefaultHasher::new();
state.hash(&mut direct);
let fingerprint = state.fingerprint();
assert_eq!(fingerprint, direct.finish());
fingerprint
};
let first = CommandName::Control("测试命令".into());
let alias = CommandName::Control("命令别名".into());
let mut token = Token::new(
TokenKind::Command(CommandName::Control("αβγ".into())),
Span { source: 2, start: 40, end: 44 },
);
token.invocation = Some(Span { source: 3, start: 99, end: 101 });
let mut body = Arc::new(Macro {
prefix: vec![TokenKind::Character('木', CatCode::Letter)],
parameters: vec![vec![TokenKind::Character('λ', CatCode::Other)]],
parameter_chars: vec!['#'],
replacement: vec![Replacement::Token(token.clone()); 80],
long: true,
outer: false,
protected: true,
});
let mut state = State::default();
state.define(first.clone(), Meaning::Macro(body.clone()), true);
state.define(alias, Meaning::Macro(body.clone()), true);
let original = check(&state);
assert_eq!(Arc::weak_count(&body), 1);
assert_eq!(check(&state), original);
let donor = state.clone();
token.invocation = Some(Span { source: 3, start: 111, end: 113 });
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token.clone());
state.define(first.clone(), Meaning::Macro(body.clone()), true);
assert_ne!(check(&state), original);
assert_eq!(check(&donor), original);
assert_eq!(Arc::weak_count(&body), 1);
token.kind = TokenKind::Command(CommandName::Control("λ".repeat(40_000)));
Arc::make_mut(&mut body).replacement[0] = Replacement::Token(token);
state.define(first, Meaning::Macro(body), true);
let uncached = check(&state);
let _held = state.commands.fingerprint_inputs.lock().unwrap();
assert_eq!(state.fingerprint(), uncached);
}
#[test]
fn command_snapshots_share_unmodified_shards_and_keep_ordered_identity() {
let mut state = State::initex().with_etex();
@@ -2828,11 +2842,6 @@ impl State {
}
}
pub fn fingerprint(&self) -> u64 {
let mut hash = FingerprintHasher::default();
self.hash(&mut hash);
hash.finish()
}
pub(super) fn begin_group(&mut self, kind: GroupKind, origin: Option<(usize, usize)>) {
self.groups.push(Group {
kind,