diff --git a/crates/texrra-tex-core/src/execution/state.rs b/crates/texrra-tex-core/src/execution/state.rs index eb4ea2a..7f87d97 100644 --- a/crates/texrra-tex-core/src/execution/state.rs +++ b/crates/texrra-tex-core/src/execution/state.rs @@ -2233,6 +2233,7 @@ impl State { // The same permutation on both sides leaves the alias proof // intact. Record common allocations first so a later reference // to any of them still has the original ordinal on both sides. + current_usage.share_common_macro_visits(); let mut old_usage = current_usage.clone(); for (body, old_body) in changed_macros { current_usage.macro_body(body); diff --git a/crates/texrra-tex-core/src/execution/statistics.rs b/crates/texrra-tex-core/src/execution/statistics.rs index 1bc8583..446791b 100644 --- a/crates/texrra-tex-core/src/execution/statistics.rs +++ b/crates/texrra-tex-core/src/execution/statistics.rs @@ -490,15 +490,33 @@ enum Allocation { Material(usize), } +struct SharedMacroVisits { + ordinals: HashMap, + visits: Vec<(Allocation, usize)>, +} + #[derive(Clone, Default)] struct AliasVisits { + shared_macros: Option>, ordinals: HashMap, visits: Vec<(Allocation, usize)>, } impl AliasVisits { + fn shared_ordinal(&self, allocation: Allocation) -> Option { + if !matches!(allocation, Allocation::Macro(_)) { + return None; + } + self.shared_macros.as_ref()?.ordinals.get(&allocation).copied() + } + fn record(&mut self, allocation: Allocation) -> bool { - let next = self.ordinals.len(); + if let Some(ordinal) = self.shared_ordinal(allocation) { + self.visits.push((allocation, ordinal)); + return false; + } + let prefix = self.shared_macros.as_ref().map_or(0, |macros| macros.ordinals.len()); + let next = prefix + self.ordinals.len(); let (ordinal, first) = match self.ordinals.entry(allocation) { Entry::Occupied(entry) => (*entry.get(), false), Entry::Vacant(entry) => (*entry.insert(next), true), @@ -506,6 +524,27 @@ impl AliasVisits { self.visits.push((allocation, ordinal)); first } + + fn share_common_macros(&mut self) { + if self.shared_macros.is_some() + || self.ordinals.is_empty() + || self.ordinals.keys().any(|allocation| !matches!(allocation, Allocation::Macro(_))) + { + return; + } + self.shared_macros = Some(Arc::new(SharedMacroVisits { + ordinals: std::mem::take(&mut self.ordinals), + visits: std::mem::take(&mut self.visits), + })); + } + + fn shared_visits(&self) -> &[(Allocation, usize)] { + self.shared_macros.as_ref().map_or(&[], |macros| macros.visits.as_slice()) + } + + fn all_visits(&self) -> impl Iterator { + self.shared_visits().iter().chain(&self.visits) + } } #[derive(Clone, Default)] @@ -531,8 +570,16 @@ impl Collector { self } + pub(super) fn share_common_macro_visits(&mut self) { + if let Some(aliases) = &mut self.aliases { + aliases.share_common_macros(); + } + } + fn contains(&self, allocation: Allocation) -> bool { - if self.aliases.as_ref().is_some_and(|aliases| aliases.ordinals.contains_key(&allocation)) { + if self.aliases.as_ref().is_some_and(|aliases| { + aliases.ordinals.contains_key(&allocation) || aliases.shared_ordinal(allocation).is_some() + }) { return true; } match allocation { @@ -583,15 +630,27 @@ impl Collector { history: &Self, old_history: &Self, ) -> bool { - let a = &self.aliases.as_ref().expect("live alias traversal").visits; - let b = &other.aliases.as_ref().expect("live alias traversal").visits; - self.usage == other.usage - && a.len() == b.len() - && a.iter().zip(b).all(|(&(new, ni), &(old, oi))| { - ni == oi - && std::mem::discriminant(&new) == std::mem::discriminant(&old) - && history.contains(new) == old_history.contains(old) - }) + let a = self.aliases.as_ref().expect("live alias traversal"); + let b = other.aliases.as_ref().expect("live alias traversal"); + if self.usage != other.usage { + return false; + } + let matches = |(&(new, ni), &(old, oi)): (&(Allocation, usize), &(Allocation, usize))| { + ni == oi + && std::mem::discriminant(&new) == std::mem::discriminant(&old) + && history.contains(new) == old_history.contains(old) + }; + let shares_prefix = a.shared_macros.as_ref().zip(b.shared_macros.as_ref()) + .is_some_and(|(a, b)| Arc::ptr_eq(a, b)); + if shares_prefix && history.macros.is_empty() && old_history.macros.is_empty() + && history.aliases.is_none() && old_history.aliases.is_none() + { + // Both sides have the same macro allocations at the same + // ordinals, and none of them can cross this retained boundary. + return a.visits.len() == b.visits.len() && a.visits.iter().zip(&b.visits).all(matches); + } + a.shared_visits().len() + a.visits.len() == b.shared_visits().len() + b.visits.len() + && a.all_visits().zip(b.all_visits()).all(matches) } pub(super) fn material_only(&self) -> bool { @@ -1024,6 +1083,47 @@ mod tests { assert_eq!(previously_counted.usage, history.usage); } + #[test] + fn shared_macro_prefix_preserves_later_aliases_and_retained_membership() { + let body = Arc::new(Macro { + prefix: vec![TokenKind::Character('A', CatCode::Letter)], + parameters: Vec::new(), + parameter_chars: Vec::new(), + replacement: Vec::new(), + long: false, + outer: false, + protected: false, + }); + let independent = Arc::new((*body).clone()); + let mut common = Collector::default().tracking_aliases(); + common.macro_body(&body); + common.share_common_macro_visits(); + + let mut live = common.clone(); + live.macro_body(&body); + live.macro_body(&independent); + let mut old_live = common.clone(); + old_live.macro_body(&body); + old_live.macro_body(&independent); + let mut swapped = common; + swapped.macro_body(&independent); + swapped.macro_body(&body); + let empty = Collector::default(); + assert_eq!(live.usage, swapped.usage); + assert_eq!(live.usage.unique_macro_bodies, 2); + assert!(live.has_equivalent_history(&old_live, &empty, &empty)); + assert!(!live.has_equivalent_history(&swapped, &empty, &empty)); + + // Keep equal retained totals but change the actual boundary alias. + let mut history = Collector::default(); + history.macro_body(&body); + let mut old_history = Collector::default(); + old_history.macro_body(&independent); + assert_eq!(history.usage, old_history.usage); + assert!(live.has_equivalent_history(&old_live, &history, &history)); + assert!(!live.has_equivalent_history(&old_live, &history, &old_history)); + } + #[test] fn history_equivalence_keeps_aliases_that_cross_the_boundary() { let token = Token::new(TokenKind::Character('A', CatCode::Letter), Span::default());