Reduce allocation and traversal in settled suffix checks

This commit is contained in:
gloamxun committed 2026-12-02 01:23:14 +08:00
1 parent 1ff049737f
commit c4003c8dad
6 files changed
+351 -66

No files matched your search

@@ -50,8 +50,9 @@ impl Executor {
&self,
shipping: Option<&NativeBox>,
host: Option<HostResourceUsage>,
c: Collector,
mut c: Collector,
) -> ResourceUsage {
self.state.collect_statistics(&mut c);
let mut c = self.collect_live_usage(shipping, host, c);
Self::collect_event_usage(self.events.iter(), &mut c);
c.usage
@@ -63,7 +64,6 @@ impl Executor {
host: Option<HostResourceUsage>,
mut c: Collector,
) -> Collector {
self.state.collect_statistics(&mut c);
c.usage.steps = self.steps;
c.usage.source_files = self.sources.len();
c.usage.source_payload_bytes = self.sources.iter().map(|s| s.data.len()).sum();
@@ -276,8 +276,11 @@ impl Executor {
}
let (history, old_history) =
Self::collect_event_usage_pair(&self.events, &old.events, collector());
let mut live = self.collect_live_usage(None, None, collector().tracking_aliases());
let old_live = old.collect_live_usage(None, None, collector().tracking_aliases());
let mut live = collector().tracking_aliases();
let mut old_live = collector().tracking_aliases();
self.state.collect_compared_statistics(&old.state, &mut live, &mut old_live)?;
let mut live = self.collect_live_usage(None, None, live);
let old_live = old.collect_live_usage(None, None, old_live);
// The splice translates the cumulative counters separately.
live.usage.steps = old_live.usage.steps;
live.usage.box_nodes_created = old_live.usage.box_nodes_created;
@@ -220,6 +220,12 @@ impl SourceRelocation {
}
}
/// A shard whose ranges end strictly before the edit can retain every
/// span, including zero-width points at those earlier positions.
pub(super) fn preserves_prefix_through(&self, end: usize) -> bool {
end < self.unchanged_prefix
}
pub(super) fn relocate_span(&self, span: Span) -> Option<Span> {
if span.source != self.source {
return Some(span);
+147 -31
View File
@@ -800,7 +800,47 @@ enum PdftexRevision {
}
const COMMAND_SHARDS: usize = 32;
type CommandShard = HashMap<Arc<CommandName>, Meaning, RandomState>;
type CommandEntries = HashMap<Arc<CommandName>, Meaning, RandomState>;
#[derive(Clone, Debug)]
struct CommandShard {
entries: CommandEntries,
// Bounds may retain ranges of replaced or removed entries. Their only
// use is to prove that every surviving token is before an edit.
source_bounds: OnceLock<BTreeMap<usize, Option<usize>>>,
}
impl CommandShard {
fn new(entries: CommandEntries) -> Self {
Self { entries, source_bounds: OnceLock::new() }
}
fn insert(&mut self, name: Arc<CommandName>, meaning: Meaning) -> Option<Meaning> {
if let Some(bounds) = self.source_bounds.get_mut() {
source_relocation::include_meaning_bounds(bounds, &meaning);
}
self.entries.insert(name, meaning)
}
fn insert_if_absent(&mut self, name: Arc<CommandName>, meaning: Meaning) -> bool {
let hashbrown::hash_map::Entry::Vacant(entry) = self.entries.entry(name) else {
return false;
};
if let Some(bounds) = self.source_bounds.get_mut() {
source_relocation::include_meaning_bounds(bounds, &meaning);
}
entry.insert(meaning);
true
}
}
impl PartialEq for CommandShard {
fn eq(&self, other: &Self) -> bool {
self.entries == other.entries
}
}
impl Eq for CommandShard {}
type OrderedCommandNames = Arc<OnceLock<Vec<(Arc<CommandName>, u64)>>>;
pub(super) fn command_hasher() -> &'static RandomState {
@@ -822,7 +862,9 @@ impl Default for CommandBindings {
fn default() -> Self {
let hasher = command_hasher();
Self {
shards: std::array::from_fn(|_| Arc::new(CommandShard::with_hasher(hasher.clone()))),
shards: std::array::from_fn(|_| {
Arc::new(CommandShard::new(CommandEntries::with_hasher(hasher.clone())))
}),
revisions: [0; COMMAND_SHARDS],
ordered_names: Arc::default(),
}
@@ -849,6 +891,7 @@ impl CommandBindings {
fn get_hashed(&self, name: &CommandName, hash: u64) -> Option<&Meaning> {
self.shards[Self::shard_index(hash)]
.entries
.raw_entry()
.from_key_hashed_nocheck(hash, name)
.map(|(_, meaning)| meaning)
@@ -867,16 +910,13 @@ impl CommandBindings {
}
fn insert_if_absent(&mut self, name: CommandName, meaning: Meaning) {
if let hashbrown::hash_map::Entry::Vacant(entry) =
self.shard_mut(&name).entry(name.into())
{
entry.insert(meaning);
if self.shard_mut(&name).insert_if_absent(name.into(), meaning) {
self.invalidate_order();
}
}
fn remove(&mut self, name: &CommandName) {
if self.shard_mut(name).remove(name).is_some() {
if self.shard_mut(name).entries.remove(name).is_some() {
self.invalidate_order();
}
}
@@ -890,11 +930,11 @@ impl CommandBindings {
}
fn len(&self) -> usize {
self.shards.iter().map(|shard| shard.len()).sum()
self.shards.iter().map(|shard| shard.entries.len()).sum()
}
fn iter(&self) -> impl Iterator<Item = (&Arc<CommandName>, &Meaning)> {
self.shards.iter().flat_map(|shard| shard.iter())
self.shards.iter().flat_map(|shard| shard.entries.iter())
}
fn ordered(&self) -> impl ExactSizeIterator<Item = (&Arc<CommandName>, &Meaning)> {
@@ -921,7 +961,11 @@ impl CommandBindings {
impl Hash for CommandBindings {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.ordered().collect::<Vec<_>>().hash(hasher);
let entries = self.ordered();
entries.len().hash(hasher);
for entry in entries {
entry.hash(hasher);
}
}
}
@@ -1049,7 +1093,45 @@ impl Default for FingerprintHasher {
}
}
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]);
@@ -1610,6 +1692,60 @@ impl Default for State {
impl State {
pub(super) fn collect_statistics(&self, c: &mut super::statistics::Collector) {
if !c.material_only() {
c.usage.state.command_entries = self.commands.len();
for (name, meaning) in self.commands.iter() {
Self::collect_command_statistics(c, name, meaning);
}
}
self.collect_state_storage(c);
}
pub(super) fn collect_compared_statistics(
&self,
old: &Self,
current_usage: &mut super::statistics::Collector,
old_usage: &mut super::statistics::Collector,
) -> Option<()> {
if !current_usage.material_only() {
let entries = old.commands.len();
current_usage.usage.state.command_entries = entries;
old_usage.usage.state.command_entries = entries;
// The alias proof needs corresponding visits, so both sides
// walk the donor's binding order. Hashing and serialization
// still use the independent, sorted command order.
for (current, prior) in self.commands.shards.iter().zip(&old.commands.shards) {
if current.entries.len() != prior.entries.len() {
return None;
}
let shared = Arc::ptr_eq(current, prior);
for (name, old_meaning) in &prior.entries {
let meaning = if shared { old_meaning } else { current.entries.get(name)? };
Self::collect_command_statistics(current_usage, name, meaning);
Self::collect_command_statistics(old_usage, name, old_meaning);
}
}
}
self.collect_state_storage(current_usage);
old.collect_state_storage(old_usage);
Some(())
}
fn collect_command_statistics(
c: &mut super::statistics::Collector,
name: &CommandName,
meaning: &Meaning,
) {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
}
fn collect_state_storage(&self, c: &mut super::statistics::Collector) {
use super::statistics::Ownership::Active;
for b in self.boxes.values() {
c.native_box(b, Active);
@@ -1622,26 +1758,6 @@ impl State {
}
return;
}
c.usage.state.command_entries = self.commands.len();
let track_aliases = c.tracks_aliases();
let mut visit_command = |name: &CommandName, meaning: &Meaning| {
if let CommandName::Control(name) = name {
c.usage.state.control_name_bytes += name.len();
}
if let Meaning::Macro(macro_definition) = meaning {
c.usage.state.macro_bindings += 1;
c.macro_body(macro_definition);
}
};
if track_aliases {
for (name, meaning) in self.commands.ordered() {
visit_command(name, meaning);
}
} else {
for (name, meaning) in self.commands.iter() {
visit_command(name, meaning);
}
}
c.usage.state.token_registers = self.toks.len() + self.xe_inter_char_tokens.len();
c.usage.state.parameter_entries =
self.parameters.len() + self.token_parameters.len() + self.job_parameters.len();
@@ -2485,7 +2601,7 @@ impl State {
Arc::unwrap_or_clone(state.commands)
.shards
.into_iter()
.flat_map(Arc::unwrap_or_clone)
.flat_map(|shard| Arc::unwrap_or_clone(shard).entries)
.filter_map(|(name, meaning)| match Arc::unwrap_or_clone(name) {
CommandName::Control(name) => Some((name, meaning)),
_ => None,
@@ -1,5 +1,7 @@
use super::*;
use crate::execution::source_relocation_events::EventRelocation;
use crate::execution::{
Span, source_relocation::SourceRelocation, source_relocation_events::EventRelocation,
};
use crate::pdf_device::forms::FormContents;
impl State {
@@ -13,7 +15,10 @@ impl State {
// Copy only shards with a relocated macro. Ordinary format macros
// and macros from the byte-identical prefix keep their allocations.
for (index, shard) in commands.shards.iter().enumerate() {
for (name, meaning) in shard.iter() {
if shard.preserves_source_spans(relocation.map()) {
continue;
}
for (name, meaning) in &shard.entries {
if let Meaning::Macro(body) = meaning {
let relocated = relocation.relocate_macro(body)?;
if !Arc::ptr_eq(body, &relocated) {
@@ -97,9 +102,84 @@ impl State {
}
}
impl CommandShard {
fn preserves_source_spans(&self, relocation: &SourceRelocation) -> bool {
let bounds = self.source_bounds.get_or_init(|| {
let mut bounds = BTreeMap::<usize, Option<usize>>::new();
for meaning in self.entries.values() {
include_meaning_bounds(&mut bounds, meaning);
}
bounds
});
bounds.get(&relocation.source()).is_none_or(|end| {
end.is_some_and(|end| relocation.preserves_prefix_through(end))
})
}
}
pub(super) fn include_meaning_bounds(
bounds: &mut BTreeMap<usize, Option<usize>>,
meaning: &Meaning,
) {
let Meaning::Macro(body) = meaning else {
return;
};
let mut include = |span: Span| {
let end = bounds.entry(span.source).or_insert(Some(0));
*end = end.filter(|_| span.start <= span.end).map(|end| end.max(span.end));
};
for part in &body.replacement {
if let Replacement::Token(token) = part {
include(token.span);
if let Some(invocation) = token.invocation {
include(invocation);
}
}
}
}
fn relocate_tokens(tokens: &mut [Token], relocation: &mut EventRelocation<'_>) -> Option<()> {
for token in tokens {
relocation.relocate_token(token)?;
}
Some(())
}
#[test]
fn command_bounds_track_redefinitions_and_invocation_origins() {
use crate::execution::CatCode;
let map = SourceRelocation::new(0, b"First\nx\nKeep\n", b"First\nlonger\nKeep\n").unwrap();
let name = CommandName::Control("boundtest".into());
let meaning = |invocation| {
let mut token = Token::new(
TokenKind::Character('x', CatCode::Letter),
Span { source: 0, start: 0, end: 1 },
);
token.invocation = invocation;
Meaning::Macro(Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: vec![Replacement::Token(token)],
long: false,
outer: false,
protected: false,
}))
};
let mut state = State::default();
state.define(name.clone(), meaning(None), true);
state.relocate_source(&mut EventRelocation::new(&map)).unwrap();
let before = state.clone();
let token_span = Span { source: 0, start: 8, end: 9 };
state.define(name.clone(), meaning(Some(token_span)), true);
state.relocate_source(&mut EventRelocation::new(&map)).unwrap();
let mapped = map.relocate_span(token_span).unwrap();
assert_ne!(mapped, token_span);
assert_eq!(state.meaning(&name), meaning(Some(mapped)));
assert_eq!(before.meaning(&name), meaning(None));
state.define(name, meaning(Some(Span { source: 0, start: 2, end: 1 })), true);
assert!(state.relocate_source(&mut EventRelocation::new(&map)).is_none());
}
@@ -1,7 +1,7 @@
//! Measured native storage and execution resources, not invented TeX arena words.
use super::*;
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
collections::{BTreeSet, HashMap, HashSet, hash_map::Entry},
sync::Arc,
};
@@ -456,7 +456,7 @@ pub(super) enum Ownership {
Active,
Retained,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum Allocation {
Macro(usize),
Tokens(usize, usize),
@@ -465,22 +465,27 @@ enum Allocation {
#[derive(Clone, Default)]
struct AliasVisits {
ordinals: BTreeMap<Allocation, usize>,
ordinals: HashMap<Allocation, usize>,
visits: Vec<(Allocation, usize)>,
}
impl AliasVisits {
fn record(&mut self, allocation: Allocation) {
fn record(&mut self, allocation: Allocation) -> bool {
let next = self.ordinals.len();
let ordinal = *self.ordinals.entry(allocation).or_insert(next);
let (ordinal, first) = match self.ordinals.entry(allocation) {
Entry::Occupied(entry) => (*entry.get(), false),
Entry::Vacant(entry) => (*entry.insert(next), true),
};
self.visits.push((allocation, ordinal));
first
}
}
#[derive(Clone, Default)]
pub(super) struct Collector {
pub usage: ResourceUsage,
// Alias visits keep traversal order separately from this membership index.
// A tracked visit uses its ordinal index for deduplication. The
// membership sets cover normal collection and any visits before tracking.
macros: HashSet<usize>,
token_lists: BTreeSet<(usize, usize)>,
shared_lists: Option<BTreeSet<usize>>,
@@ -495,21 +500,14 @@ impl Collector {
}
pub(super) fn tracking_aliases(mut self) -> Self {
self.aliases = Some(AliasVisits::default());
self.aliases.get_or_insert_with(AliasVisits::default);
self
}
pub(super) fn tracks_aliases(&self) -> bool {
self.aliases.is_some()
}
fn tracks_allocation(&mut self, allocation: Allocation) {
if let Some(aliases) = &mut self.aliases {
aliases.record(allocation);
}
}
fn contains(&self, allocation: Allocation) -> bool {
if self.aliases.as_ref().is_some_and(|aliases| aliases.ordinals.contains_key(&allocation)) {
return true;
}
match allocation {
Allocation::Macro(address) => self.macros.contains(&address),
Allocation::Tokens(address, len) => self.token_lists.contains(&(address, len)),
@@ -575,8 +573,13 @@ impl Collector {
pub fn macro_body(&mut self, m: &Arc<Macro>) {
let address = Arc::as_ptr(m) as usize;
self.tracks_allocation(Allocation::Macro(address));
if self.macros.insert(address) {
let first = if let Some(aliases) = &mut self.aliases {
aliases.record(Allocation::Macro(address))
&& (self.macros.is_empty() || !self.macros.contains(&address))
} else {
self.macros.insert(address)
};
if first {
self.usage.unique_macro_bodies += 1;
self.usage.macro_token_cells += m.prefix.len()
+ m.parameters.iter().map(Vec::len).sum::<usize>()
@@ -585,11 +588,15 @@ impl Collector {
}
pub fn shared_tokens(&mut self, t: &Arc<[Token]>) {
let address = t.as_ptr() as usize;
if !t.is_empty() {
self.tracks_allocation(Allocation::Tokens(address, t.len()));
}
if self.token_lists.insert((address, t.len())) {
self.usage.token_list_cells += t.len();
let len = t.len();
let first = if let Some(aliases) = &mut self.aliases && len != 0 {
aliases.record(Allocation::Tokens(address, len))
&& !self.token_lists.contains(&(address, len))
} else {
self.token_lists.insert((address, len))
};
if first {
self.usage.token_list_cells += len;
}
}
fn material(&mut self, o: Ownership) -> &mut MaterialUsage {
@@ -725,13 +732,15 @@ impl Collector {
self.usage.active_material.ligature_work_items += b.ligature_work_items();
}
fn visit_shared<T: ?Sized>(&mut self, list: &Arc<T>) -> bool {
let Some(seen) = &mut self.shared_lists else {
return true;
};
let address = Arc::as_ptr(list).cast::<()>() as usize;
if self.shared_lists.is_some() {
self.tracks_allocation(Allocation::Material(address));
if let Some(aliases) = &mut self.aliases {
aliases.record(Allocation::Material(address)) && !seen.contains(&address)
} else {
seen.insert(address)
}
self.shared_lists
.as_mut()
.is_none_or(|seen| seen.insert(address))
}
pub fn shared_diagnostics(
@@ -911,6 +920,44 @@ mod tests {
).is_none());
}
#[test]
fn tracked_macro_counts_share_the_ordinal_index_without_losing_visits() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());
let body = Arc::new(Macro {
prefix: Vec::new(),
parameters: Vec::new(),
parameter_chars: Vec::new(),
replacement: vec![Replacement::Token(token.clone())],
long: false,
outer: false,
protected: false,
});
let independent = Arc::new((*body).clone());
let tokens: Arc<[Token]> = Arc::from([token]);
let mut history = Collector::default();
let mut live = Collector::default().tracking_aliases();
for collector in [&mut history, &mut live] {
collector.macro_body(&body);
collector.shared_tokens(&tokens);
collector.macro_body(&body);
collector.macro_body(&independent);
}
assert_eq!(live.usage, history.usage);
assert_eq!(live.usage.unique_macro_bodies, 2);
assert!(live.macros.is_empty());
assert!(live.token_lists.is_empty());
let visits = &live.aliases.as_ref().unwrap().visits;
assert_eq!(visits.iter().map(|(_, ordinal)| *ordinal).collect::<Vec<_>>(), [0, 1, 0, 2]);
assert!(visits.iter().all(|(allocation, _)| {
history.contains(*allocation) && live.contains(*allocation)
}));
let mut previously_counted = history.clone().tracking_aliases();
previously_counted.macro_body(&body);
assert_eq!(previously_counted.usage, history.usage);
}
#[test]
fn history_equivalence_keeps_aliases_that_cross_the_boundary() {
let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());