//! Anchors that tie a memory to the code it talks about. //! //! An anchor is `path` + qualified symbol name + kind + the hash of the symbol's text (see //! [`crate::parse::body_hash`]). Only these identifiers and the hash leave the machine: never //! the source. Anchors are computed and checked by parsing the cited files directly from disk, //! so they work even before the repository index exists and always see the working tree. use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; use serde::Deserialize; use serde::Serialize; use crate::index::MAX_FILE_BYTES; use crate::lang::Lang; use crate::parse::Parsed; use crate::parse::parse; /// At most this many anchors per memory. pub const MAX_ANCHORS: usize = 6; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Anchor { pub path: String, pub symbol: String, pub kind: String, pub line: u32, pub hash: String, } /// Result of checking one anchor against the working tree. #[derive(Clone, Debug, PartialEq, Eq)] pub enum AnchorCheck { /// Same text; the symbol may have moved inside the file. Fresh { line: u32 }, /// The symbol is still there but its text changed. Changed { line: u32 }, /// No symbol with that name in the file (renamed, moved or deleted), or no file. Missing, } impl AnchorCheck { pub fn is_fresh(&self) -> bool { matches!(self, AnchorCheck::Fresh { .. }) } } /// A citation as stored by the memory server. #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize)] pub struct Citation { pub path: String, #[serde(default)] pub lines: Option, #[serde(default)] pub quote: Option, } /// Parses files of one checkout on demand and keeps them for the batch. pub struct Verifier { root: PathBuf, files: HashMap>, } impl Verifier { pub fn new(root: &Path) -> Self { Self { root: root.to_path_buf(), files: HashMap::new(), } } fn file(&mut self, path: &str) -> Option<&(Lang, Parsed, String)> { let root = self.root.clone(); self.files .entry(path.to_string()) .or_insert_with(|| { if path.contains("..") || Path::new(path).is_absolute() { return None; } let lang = Lang::from_path(path)?; let absolute = root.join(path); let meta = std::fs::metadata(&absolute).ok()?; if !meta.is_file() || meta.len() > MAX_FILE_BYTES { return None; } let source = std::fs::read_to_string(&absolute).ok()?; let parsed = parse(lang, &source); Some((lang, parsed, source)) }) .as_ref() } /// Checks one anchor against the current file. pub fn check(&mut self, anchor: &Anchor) -> AnchorCheck { let Some((lang, parsed, _)) = self.file(&anchor.path) else { return AnchorCheck::Missing; }; let lang = *lang; let candidates: Vec<_> = parsed .symbols .iter() .filter(|symbol| symbol.qualified_name(lang) == anchor.symbol && symbol.kind == anchor.kind) .collect(); if let Some(same) = candidates.iter().find(|symbol| symbol.hash == anchor.hash) { return AnchorCheck::Fresh { line: same.line }; } match candidates .iter() .min_by_key(|symbol| symbol.line.abs_diff(anchor.line)) { Some(nearest) => AnchorCheck::Changed { line: nearest.line }, None => AnchorCheck::Missing, } } /// Anchors for one citation: the innermost definitions that contain the cited lines (or the /// line where the quote is found). pub fn anchors_for_citation(&mut self, citation: &Citation) -> Vec { let path = citation.path.trim().trim_start_matches("./").to_string(); let range = citation.lines.as_deref().and_then(parse_lines); let Some((lang, parsed, source)) = self.file(&path) else { return Vec::new(); }; let range = range.or_else(|| { let quote = citation.quote.as_deref()?.trim(); find_quote_line(source, quote).map(|line| (line, line)) }); let Some((from, to)) = range else { return Vec::new(); }; let lang = *lang; // Innermost symbols overlapping the range, skipping containers that hold another match. let overlapping: Vec = parsed .symbols .iter() .enumerate() .filter(|(_, symbol)| symbol.line <= to && symbol.end_line >= from) .map(|(index, _)| index) .collect(); let innermost: Vec = overlapping .iter() .copied() .filter(|index| { !overlapping.iter().any(|other| { *other != *index && parsed.symbols[*other].parent == Some(*index) }) }) .collect(); innermost .into_iter() .take(3) .map(|index| { let symbol = &parsed.symbols[index]; Anchor { path: path.clone(), symbol: symbol.qualified_name(lang), kind: symbol.kind.to_string(), line: symbol.line, hash: symbol.hash.clone(), } }) .collect() } /// Anchors for identifiers named in the memory text (`` `name` `` or `name()`), looked up in /// the given files only. pub fn anchors_for_names(&mut self, paths: &[String], names: &[String]) -> Vec { let mut out = Vec::new(); for path in paths { let Some((lang, parsed, _)) = self.file(path) else { continue; }; let lang = *lang; for name in names { let matches: Vec<_> = parsed .symbols .iter() .filter(|symbol| { !matches!(symbol.kind, "key" | "section") && (symbol.name == *name || symbol.qualified_name(lang) == *name) }) .collect(); // Ambiguous names in the same file are skipped: the anchor must be unambiguous. if let [symbol] = matches.as_slice() { out.push(Anchor { path: path.clone(), symbol: symbol.qualified_name(lang), kind: symbol.kind.to_string(), line: symbol.line, hash: symbol.hash.clone(), }); } } } out } } /// All anchors of a memory: its citations, then identifiers of its text found in cited files. pub fn anchors_for_memory(root: &Path, citations: &[Citation], text: &str) -> Vec { let mut verifier = Verifier::new(root); let mut anchors: Vec = Vec::new(); for citation in citations { anchors.extend(verifier.anchors_for_citation(citation)); } let paths: Vec = citations .iter() .map(|citation| citation.path.trim().trim_start_matches("./").to_string()) .collect(); anchors.extend(verifier.anchors_for_names(&paths, &identifiers_in_text(text))); let mut seen = std::collections::HashSet::new(); anchors.retain(|anchor| seen.insert((anchor.path.clone(), anchor.symbol.clone(), anchor.kind.clone()))); anchors.truncate(MAX_ANCHORS); anchors } /// `12` or `12-30` (1-based, inclusive). pub fn parse_lines(raw: &str) -> Option<(u32, u32)> { let raw = raw.trim(); let (from, to) = match raw.split_once('-') { Some((from, to)) => (from.trim().parse().ok()?, to.trim().parse().ok()?), None => { let line = raw.parse().ok()?; (line, line) } }; (from >= 1 && to >= from).then_some((from, to)) } /// 1-based line where `quote` starts, comparing with whitespace collapsed. fn find_quote_line(source: &str, quote: &str) -> Option { let wanted: String = quote.split_whitespace().collect::>().join(" "); if wanted.len() < 4 { return None; } let first_word = wanted.split(' ').next()?; for (index, line) in source.lines().enumerate() { if !line.contains(first_word) { continue; } let window: String = source .lines() .skip(index) .take(8) .collect::>() .join(" ") .split_whitespace() .collect::>() .join(" "); if window.contains(&wanted) { return u32::try_from(index + 1).ok(); } } None } /// Identifiers in backticks or followed by `()`: `` `parse_porcelain_z` ``, `Index::new()`. pub fn identifiers_in_text(text: &str) -> Vec { let is_ident = |candidate: &str| { let candidate = candidate.trim_end_matches("()"); candidate.len() >= 3 && candidate.len() <= 120 && candidate.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') && candidate .chars() .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == ':' || c == '.') && !candidate.contains("..") }; let mut out = Vec::new(); for (index, part) in text.split('`').enumerate() { if index % 2 == 1 && is_ident(part.trim()) { out.push(part.trim().trim_end_matches("()").to_string()); } } for word in text.split(|c: char| c.is_whitespace() || c == ',' || c == ';' || c == '`') { if let Some(stripped) = word.strip_suffix("()") && is_ident(stripped) { out.push(stripped.to_string()); } } // `Type::name` also matches by its last segment inside the file. let mut expanded = Vec::new(); for name in out { if let Some((_, last)) = name.rsplit_once("::") { expanded.push(last.to_string()); } expanded.push(name); } expanded.sort(); expanded.dedup(); expanded } #[cfg(test)] mod tests { use super::*; use pretty_assertions::assert_eq; fn write(dir: &Path, path: &str, content: &str) { let full = dir.join(path); std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir"); std::fs::write(full, content).expect("write"); } #[test] fn anchors_follow_changes_of_the_cited_symbol() { let dir = tempfile::tempdir().expect("tempdir"); let root = dir.path(); write( root, "src/lib.rs", "pub struct Index;\nimpl Index {\n pub fn open() -> u32 {\n 1\n }\n}\nfn helper() {}\n", ); let anchors = anchors_for_memory( root, &[Citation { path: "src/lib.rs".to_string(), lines: Some("4".to_string()), quote: None, }], "`helper` is called by `Index::open`.", ); let names: Vec<(&str, &str)> = anchors.iter().map(|a| (a.symbol.as_str(), a.kind.as_str())).collect(); assert_eq!(names, vec![("Index::open", "method"), ("helper", "function")]); // Whitespace only: still fresh. Moved down by one line: fresh with the new line. write( root, "src/lib.rs", "\npub struct Index;\nimpl Index {\n pub fn open() -> u32 { 1 }\n}\nfn helper() {}\n", ); let mut verifier = Verifier::new(root); assert_eq!(verifier.check(&anchors[0]), AnchorCheck::Fresh { line: 4 }); // Body changed: stale. Function removed: missing. write(root, "src/lib.rs", "pub struct Index;\nimpl Index {\n pub fn open() -> u32 { 2 }\n}\n"); let mut verifier = Verifier::new(root); assert_eq!(verifier.check(&anchors[0]), AnchorCheck::Changed { line: 3 }); assert_eq!(verifier.check(&anchors[1]), AnchorCheck::Missing); } #[test] fn quote_and_identifiers() { let dir = tempfile::tempdir().expect("tempdir"); write(dir.path(), "a.py", "def first():\n return 1\n\ndef second():\n value = compute(\n 2)\n return value\n"); let mut verifier = Verifier::new(dir.path()); let anchors = verifier.anchors_for_citation(&Citation { path: "a.py".to_string(), lines: None, quote: Some("value = compute( 2)".to_string()), }); assert_eq!(anchors.len(), 1); assert_eq!(anchors[0].symbol, "second"); assert_eq!( identifiers_in_text("Use `Index::new` and call reload() then `a b`."), vec!["Index::new".to_string(), "new".to_string(), "reload".to_string()] ); assert_eq!(parse_lines("10-12"), Some((10, 12))); assert_eq!(parse_lines("x"), None); assert!(verifier.anchors_for_citation(&Citation { path: "../etc/passwd".to_string(), lines: Some("1".to_string()), quote: None }).is_empty()); } }