use std::collections::HashMap;
use std::sync::Arc;
use crate::macros::MacroDef;
use crate::summary::{TuEvent, TuFrame};
#[derive(Debug, Clone)]
pub(crate) enum StateChange {
Defined {
name: Box<str>,
definition: Arc<MacroDef>,
file: std::path::PathBuf,
at: usize,
},
Undefined {
name: Box<str>,
file: std::path::PathBuf,
at: usize,
},
}
#[derive(Debug, Clone)]
pub(crate) struct EntryPosition {
pub(crate) from_offset: isize,
pub(crate) file: std::path::PathBuf,
pub(crate) at: usize,
}
#[derive(Debug, Clone)]
pub(crate) struct ConditionalBody {
pub(crate) name: Box<str>,
pub(crate) function_like: bool,
pub(crate) parameters: Option<Box<str>>,
pub(crate) body: Box<str>,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Contribution {
pub(crate) file: std::path::PathBuf,
pub(crate) visit_once: bool,
pub(crate) events: Vec<TuEvent>,
pub(crate) changes: Vec<StateChange>,
pub(crate) edges: Vec<(usize, u64)>,
pub(crate) bodies: Vec<ConditionalBody>,
pub(crate) dead: Vec<usize>,
pub(crate) conditional_facts: usize,
pub(crate) facts_in_force: usize,
}
impl StateChange {
pub(crate) fn file(&self) -> &std::path::Path {
match self {
StateChange::Defined { file, .. } => file,
StateChange::Undefined { file, .. } => file,
}
}
pub(crate) fn at(&self) -> usize {
match self {
StateChange::Defined { at, .. } => *at,
StateChange::Undefined { at, .. } => *at,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct CachedFrame {
pub(crate) file: std::path::PathBuf,
pub(crate) parent: Option<u32>,
pub(crate) from_in_parent: usize,
pub(crate) visit_once: bool,
pub(crate) entry_seq: u32,
pub(crate) tout: u32,
}
const MAX_CONTRIBUTIONS: usize = 512;
pub(crate) fn key(file: &std::path::Path, content: u64, projection: u64) -> u64 {
let mut hash = crate::index::walk_census::hash(file.to_string_lossy().as_bytes());
for part in [content, projection, crate::cache::READING_FINGERPRINT] {
hash = hash.rotate_left(7) ^ part;
}
hash
}
#[derive(Default)]
pub struct WalkCache {
table: std::sync::Mutex<Table>,
}
#[derive(Default)]
struct Table {
held: HashMap<u64, Arc<Contribution>>,
order: std::collections::VecDeque<u64>,
}
impl Table {
fn evict(&mut self) {
while self.held.len() > MAX_CONTRIBUTIONS {
let Some(oldest) = self.order.pop_front() else {
break;
};
self.held.remove(&oldest);
}
}
}
impl WalkCache {
pub fn new() -> WalkCache {
WalkCache::default()
}
fn locked(&self) -> std::sync::MutexGuard<'_, Table> {
self.table
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub(crate) fn lookup(&self, key: u64) -> Option<Arc<Contribution>> {
self.locked().held.get(&key).cloned()
}
pub(crate) fn store(&self, key: u64, contribution: Contribution) {
let mut table = self.locked();
table.held.insert(key, Arc::new(contribution));
table.order.push_back(key);
table.evict();
}
pub fn accounting(&self) -> (usize, usize) {
let table = self.locked();
let mut bytes = 0usize;
for contribution in table.held.values() {
bytes += std::mem::size_of::<Contribution>() + contribution.file.as_os_str().len();
for event in &contribution.events {
bytes += std::mem::size_of::<crate::summary::TuEvent>()
+ event.name.len()
+ event.body_text.as_ref().map_or(0, |text| text.len())
+ event.parameters.as_ref().map_or(0, |text| text.len());
}
bytes += contribution.changes.len() * std::mem::size_of::<StateChange>();
bytes += contribution.edges.len() * std::mem::size_of::<(usize, u64)>();
bytes += contribution.bodies.len() * std::mem::size_of::<crate::ConditionalBody>();
bytes += contribution.dead.len() * std::mem::size_of::<usize>();
}
(table.held.len(), bytes)
}
pub(crate) fn clear(&self) {
let mut table = self.locked();
table.held.clear();
table.order.clear();
drop(table);
crate::index::walk_census::forget_projections();
}
pub(crate) fn saved(&self) -> Vec<(u64, Contribution)> {
self.locked()
.held
.iter()
.map(|(key, contribution)| (*key, (**contribution).clone()))
.collect()
}
pub(crate) fn restore(&self, entries: Vec<(u64, Contribution)>) {
let mut table = self.locked();
table.held.clear();
table.order.clear();
for (key, contribution) in entries {
table.held.insert(key, Arc::new(contribution));
table.order.push_back(key);
}
table.evict();
}
pub(crate) fn held(&self) -> usize {
self.locked().held.len()
}
}
pub(crate) fn rebased(
contribution: &Contribution,
frame: u32,
event_base: u32,
parent: Option<u32>,
from_in_parent: usize,
) -> (TuFrame, Vec<TuEvent>) {
let built = TuFrame {
file: contribution.file.clone(),
parent,
from_in_parent,
visit_once: contribution.visit_once,
entry_seq: event_base,
tout: u32::MAX,
};
let mut events = contribution.events.clone();
for event in &mut events {
event.frame = frame;
}
(built, events)
}
#[cfg(test)]
mod tests {
use super::*;
fn an_event() -> TuEvent {
TuEvent {
name: std::sync::Arc::from("X"),
function_like: None,
body: None,
body_text: None,
parameters: None,
body_range: None,
frame: 0,
at: 7,
unconditional: true,
}
}
#[test]
fn a_spliced_frame_takes_its_parent_from_the_site_and_its_events_take_the_frame() {
let contribution = Contribution {
file: std::path::PathBuf::from("/p/a.h"),
visit_once: true,
events: vec![an_event()],
..Contribution::default()
};
let (frame, events) = rebased(&contribution, 5, 41, Some(2), 33);
assert_eq!(frame.parent, Some(2));
assert_eq!(frame.from_in_parent, 33);
assert_eq!(frame.entry_seq, 41);
assert_eq!(frame.tout, u32::MAX);
assert_eq!(events[0].frame, 5);
assert_eq!(events[0].at, 7);
}
#[test]
fn the_key_moves_with_the_file_its_contents_and_the_projection() {
let base = key(std::path::Path::new("/p/a.cpp"), 1, 3);
assert_ne!(
base,
key(std::path::Path::new("/p/a.cpp"), 9, 3),
"contents"
);
assert_ne!(
base,
key(std::path::Path::new("/p/a.cpp"), 1, 9),
"projection"
);
assert_ne!(base, key(std::path::Path::new("/p/b.cpp"), 1, 3), "file");
assert_eq!(base, key(std::path::Path::new("/p/a.cpp"), 1, 3));
}
}