#![allow(dead_code)]
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
fn enabled() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("CPPLS_WALK_CENSUS").is_some())
}
static ENTRIES: AtomicU64 = AtomicU64::new(0);
static SPLICED: AtomicU64 = AtomicU64::new(0);
static FRESH: AtomicU64 = AtomicU64::new(0);
fn distinct() -> &'static Mutex<HashSet<u64>> {
static SEEN: OnceLock<Mutex<HashSet<u64>>> = OnceLock::new();
SEEN.get_or_init(|| Mutex::new(HashSet::new()))
}
fn projections() -> &'static Mutex<HashMap<std::path::PathBuf, (u64, Arc<Vec<(Box<str>, u64)>>)>> {
static PROJECTIONS: OnceLock<
Mutex<HashMap<std::path::PathBuf, (u64, Arc<Vec<(Box<str>, u64)>>)>>,
> = OnceLock::new();
PROJECTIONS.get_or_init(|| Mutex::new(HashMap::new()))
}
pub(crate) fn entered(path: &std::path::Path, source: &str, defined: impl Fn(&str) -> bool) {
if !enabled() {
return;
}
let mut key = hash(path.to_string_lossy().as_bytes());
for (name, hash) in projection_of(path, source).iter() {
key = key.rotate_left(5) ^ hash ^ if defined(name) { 0x9e37 } else { 0 };
}
ENTRIES.fetch_add(1, Ordering::Relaxed);
let distinct_now = {
let mut seen = distinct()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
seen.insert(key);
seen.len() as u64
};
let entries = ENTRIES.load(Ordering::Relaxed);
eprintln!(
"census: entries {entries} distinct {distinct_now} ratio {:.2} | spliced {} fresh {}",
entries as f64 / distinct_now.max(1) as f64,
SPLICED.load(Ordering::Relaxed),
FRESH.load(Ordering::Relaxed),
);
}
pub(crate) fn a_splice() {
if enabled() {
SPLICED.fetch_add(1, Ordering::Relaxed);
}
}
pub(crate) fn a_fresh_walk() {
if enabled() {
FRESH.fetch_add(1, Ordering::Relaxed);
}
}
pub(crate) fn projection_digest(
path: &std::path::Path,
source: &str,
defined: impl Fn(&str) -> bool,
) -> u64 {
let mut digest: u64 = 0xcbf2_9ce4_8422_2325;
for (name, hash) in projection_of(path, source).iter() {
let value = hash
^ if defined(name) {
0x9e37_79b9_7f4a_7c15
} else {
0
};
digest = digest.rotate_left(5) ^ value;
}
digest
}
pub(crate) fn projection_of(path: &std::path::Path, source: &str) -> Arc<Vec<(Box<str>, u64)>> {
if path.as_os_str().is_empty() {
return Arc::new(scan(source));
}
let fingerprint = fingerprint_of(source);
let hit = projections()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(path)
.filter(|(known, _)| *known == fingerprint)
.map(|(_, names)| names.clone());
if let Some(hit) = hit {
return hit;
}
let names = Arc::new(scan(source));
projections()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(path.to_path_buf(), (fingerprint, names.clone()));
names
}
pub(crate) fn forget_projections() {
projections()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clear();
}
fn fingerprint_of(source: &str) -> u64 {
let mut hash = source.len() as u64;
for byte in source.as_bytes().chunks(64).take(4).flatten() {
hash = hash.rotate_left(5) ^ u64::from(*byte);
}
hash
}
fn scan(source: &str) -> Vec<(Box<str>, u64)> {
let mut names: Vec<(Box<str>, u64)> = Vec::new();
let mut seen: HashSet<Box<str>> = HashSet::new();
for line in source.lines() {
let trimmed = line.trim_start();
let Some(after_hash) = trimmed.strip_prefix('#') else {
continue;
};
let after_hash = after_hash.trim_start();
let directive: String = after_hash
.chars()
.take_while(|character| character.is_ascii_alphabetic())
.collect();
if !matches!(directive.as_str(), "if" | "ifdef" | "ifndef" | "elif") {
continue;
}
let mut word = String::new();
let flush =
|word: &mut String, names: &mut Vec<(Box<str>, u64)>, seen: &mut HashSet<Box<str>>| {
if word.is_empty() {
return;
}
if seen.insert(Box::from(&**word)) {
names.push((Box::from(&**word), hash(word.as_bytes())));
}
word.clear();
};
for character in after_hash[directive.len()..].chars() {
if character.is_alphanumeric() || character == '_' {
word.push(character);
} else {
flush(&mut word, &mut names, &mut seen);
}
}
flush(&mut word, &mut names, &mut seen);
}
names
}
pub(crate) fn hash(bytes: &[u8]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in bytes {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}