use crate::calls::{get_function_name, is_function_kind};
use crate::query::{find_descendants, walk_preorder, Walk};
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use tree_sitter::Node;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum FingerprintTier {
Function,
Block,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Fingerprint {
pub name: Option<String>,
pub tier: FingerprintTier,
pub kind: &'static str,
pub hash: u64,
pub node_count: usize,
pub start_byte: usize,
pub end_byte: usize,
pub start_line: usize,
pub end_line: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorpusFingerprint<S> {
pub source: S,
pub fingerprint: Fingerprint,
}
pub fn duplicate_groups<S: Ord + Clone>(
fingerprints: &[CorpusFingerprint<S>],
) -> Vec<Vec<&CorpusFingerprint<S>>> {
let mut by_hash: HashMap<(u64, FingerprintTier), Vec<&CorpusFingerprint<S>>> = HashMap::new();
for fp in fingerprints {
by_hash
.entry((fp.fingerprint.hash, fp.fingerprint.tier))
.or_default()
.push(fp);
}
let mut groups: Vec<Vec<&CorpusFingerprint<S>>> = by_hash
.into_iter()
.filter(|(_, members)| members.len() > 1)
.map(|(_, mut members)| {
members.sort_by(|a, b| {
(a.source.clone(), a.fingerprint.start_byte)
.cmp(&(b.source.clone(), b.fingerprint.start_byte))
});
members
})
.collect();
groups.sort_by_key(|members| (members[0].fingerprint.hash, members[0].fingerprint.tier));
groups
}
pub fn structural_hash(node: Node, source: &[u8]) -> u64 {
hash_and_count(node, source).0
}
pub fn function_fingerprints(root: Node, source: &str, min_nodes: usize) -> Vec<Fingerprint> {
find_descendants(root, |n| is_function_kind(n.kind()))
.into_iter()
.filter_map(|node| {
let (hash, node_count) = hash_and_count(node, source.as_bytes());
if node_count < min_nodes {
return None;
}
Some(Fingerprint {
name: get_function_name(node, source),
tier: FingerprintTier::Function,
kind: node.kind(),
hash,
node_count,
start_byte: node.start_byte(),
end_byte: node.end_byte(),
start_line: node.start_position().row + 1,
end_line: node.end_position().row + 1,
})
})
.collect()
}
pub fn block_fingerprints(root: Node, source: &str, min_nodes: usize) -> Vec<Fingerprint> {
find_descendants(root, |n| is_block_kind(n.kind()))
.into_iter()
.filter_map(|node| {
let (hash, node_count) = hash_and_count(node, source.as_bytes());
if node_count < min_nodes {
return None;
}
Some(Fingerprint {
name: None,
tier: FingerprintTier::Block,
kind: node.kind(),
hash,
node_count,
start_byte: node.start_byte(),
end_byte: node.end_byte(),
start_line: node.start_position().row + 1,
end_line: node.end_position().row + 1,
})
})
.collect()
}
pub fn is_block_kind(kind: &str) -> bool {
matches!(
kind,
"if_statement"
| "while_statement"
| "for_statement"
| "for_range_loop" | "do_statement"
| "switch_statement"
| "case_statement"
| "if_expression"
| "while_expression"
| "for_expression"
| "loop_expression"
| "match_expression"
| "match_arm"
| "match_statement"
| "case_clause" | "for_in_statement"
| "switch_case"
| "switch_default"
| "expression_switch_statement"
| "type_switch_statement"
| "select_statement"
| "expression_case"
| "type_case"
| "communication_case"
| "enhanced_for_statement"
| "switch_expression" | "switch_block_statement_group"
| "switch_rule" | "foreach_statement" | "switch_expression_arm"
| "switch_section"
| "do_while_statement"
| "when_expression"
| "when_entry"
| "repeat_while_statement"
| "switch_entry"
| "match_conditional_expression"
| "do_loop"
| "select_case_statement"
| "forall_statement"
| "do_while_expression"
| "type_case_clause"
| "repeat_statement"
| "loop_statement"
| "case_statement_alternative"
)
}
fn hash_and_count(root: Node, source: &[u8]) -> (u64, usize) {
let mut hasher = DefaultHasher::new();
let mut count = 0usize;
walk_preorder(root, |node| {
count += 1;
node.kind().hash(&mut hasher);
node.child_count().hash(&mut hasher);
Walk::Continue
});
if let Some(type_text) = declared_type_text(root, source) {
type_text.hash(&mut hasher);
}
(hasher.finish(), count)
}
fn declared_type_text<'a>(node: Node, source: &'a [u8]) -> Option<&'a str> {
["return_type", "result", "type"].iter().find_map(|field| {
let type_node = node.child_by_field_name(field)?;
std::str::from_utf8(&source[type_node.start_byte()..type_node.end_byte()]).ok()
})
}
#[cfg(test)]
mod tests {
use super::*;
fn parse(source: &str, language: tree_sitter::Language) -> tree_sitter::Tree {
let mut parser = tree_sitter::Parser::new();
parser.set_language(&language).unwrap();
parser.parse(source, None).unwrap()
}
#[test]
#[cfg(feature = "lang-c")]
fn identical_functions_hash_identically() {
let a = "int f(int x) { return x + 1; }";
let b = "int g(int y) { return y + 1; }";
let tree_a = parse(a, tree_sitter_c::LANGUAGE.into());
let tree_b = parse(b, tree_sitter_c::LANGUAGE.into());
let fp_a = function_fingerprints(tree_a.root_node(), a, 0);
let fp_b = function_fingerprints(tree_b.root_node(), b, 0);
assert_eq!(fp_a.len(), 1);
assert_eq!(fp_b.len(), 1);
assert_eq!(fp_a[0].hash, fp_b[0].hash);
assert_eq!(fp_a[0].name, Some("f".to_string()));
assert_eq!(fp_b[0].name, Some("g".to_string()));
}
#[test]
#[cfg(feature = "lang-c")]
fn structurally_different_functions_hash_differently() {
let a = "int f(int x) { return x + 1; }";
let b = "int f(int x) { if (x) { return x; } return 0; }";
let tree_a = parse(a, tree_sitter_c::LANGUAGE.into());
let tree_b = parse(b, tree_sitter_c::LANGUAGE.into());
let fp_a = function_fingerprints(tree_a.root_node(), a, 0);
let fp_b = function_fingerprints(tree_b.root_node(), b, 0);
assert_ne!(fp_a[0].hash, fp_b[0].hash);
}
#[test]
#[cfg(feature = "lang-c")]
fn min_nodes_filters_out_trivial_subtrees() {
let source = "int f(void) { return 1; }";
let tree = parse(source, tree_sitter_c::LANGUAGE.into());
let all = function_fingerprints(tree.root_node(), source, 0);
assert_eq!(all.len(), 1);
let filtered = function_fingerprints(tree.root_node(), source, 1_000);
assert!(filtered.is_empty());
}
#[test]
#[cfg(feature = "lang-c")]
fn hash_is_stable_across_separate_calls() {
let source = "int f(int x) { return x + 1; }";
let tree1 = parse(source, tree_sitter_c::LANGUAGE.into());
let tree2 = parse(source, tree_sitter_c::LANGUAGE.into());
let h1 = function_fingerprints(tree1.root_node(), source, 0)[0].hash;
let h2 = function_fingerprints(tree2.root_node(), source, 0)[0].hash;
assert_eq!(h1, h2);
}
#[test]
#[cfg(feature = "lang-rust")]
fn nested_functions_are_fingerprinted_independently_of_their_enclosing_fn() {
let source = "fn f() { fn g() { 1 + 1; } g(); }";
let tree = parse(source, tree_sitter_rust::LANGUAGE.into());
let fps = function_fingerprints(tree.root_node(), source, 0);
assert_eq!(fps.len(), 2);
}
#[test]
#[cfg(feature = "lang-c")]
fn structural_hash_matches_function_fingerprints_hash() {
let source = "int f(int x) { return x + 1; }";
let tree = parse(source, tree_sitter_c::LANGUAGE.into());
let fn_node = find_descendants(tree.root_node(), |n| is_function_kind(n.kind()))
.into_iter()
.next()
.unwrap();
let direct = structural_hash(fn_node, source.as_bytes());
let via_fingerprints = function_fingerprints(tree.root_node(), source, 0)[0].hash;
assert_eq!(direct, via_fingerprints);
}
#[test]
#[cfg(feature = "lang-rust")]
fn same_skeleton_different_return_type_hashes_differently() {
let names = "fn collect_names(&self, node: &Node) -> Vec<String> { \
let mut names = Vec::new(); self.collect_names_recursive(node, &mut names); names }";
let violations = "fn check(&self, node: &Node) -> Vec<RuleViolation> { \
let mut violations = Vec::new(); self.check_x(node, &mut violations); violations }";
let tree_a = parse(names, tree_sitter_rust::LANGUAGE.into());
let tree_b = parse(violations, tree_sitter_rust::LANGUAGE.into());
let fp_a = function_fingerprints(tree_a.root_node(), names, 0);
let fp_b = function_fingerprints(tree_b.root_node(), violations, 0);
assert_ne!(fp_a[0].hash, fp_b[0].hash);
}
#[test]
#[cfg(feature = "lang-rust")]
fn same_skeleton_same_return_type_still_hashes_identically() {
let a = "fn collect_names(&self, node: &Node) -> Vec<String> { \
let mut out = Vec::new(); self.walk(node, &mut out); out }";
let b = "fn gather_ids(&self, root: &Node) -> Vec<String> { \
let mut acc = Vec::new(); self.walk(root, &mut acc); acc }";
let tree_a = parse(a, tree_sitter_rust::LANGUAGE.into());
let tree_b = parse(b, tree_sitter_rust::LANGUAGE.into());
let fp_a = function_fingerprints(tree_a.root_node(), a, 0);
let fp_b = function_fingerprints(tree_b.root_node(), b, 0);
assert_eq!(fp_a[0].hash, fp_b[0].hash);
}
#[test]
#[cfg(feature = "lang-c")]
fn function_with_no_type_annotation_still_hashes() {
let source = "int f(int x) { if (x) { return x; } return 0; }";
let tree = parse(source, tree_sitter_c::LANGUAGE.into());
let if_node = find_descendants(tree.root_node(), |n| n.kind() == "if_statement")
.into_iter()
.next()
.unwrap();
let _ = structural_hash(if_node, source.as_bytes());
}
#[test]
#[cfg(feature = "lang-c")]
fn duplicate_groups_finds_clones_across_files() {
let a_src = "int f(int x) { return x + 1; }";
let b_src = "int g(int y) { return y + 1; }";
let c_src = "int h(int z) { if (z) { return z; } return 0; }";
let a_tree = parse(a_src, tree_sitter_c::LANGUAGE.into());
let b_tree = parse(b_src, tree_sitter_c::LANGUAGE.into());
let c_tree = parse(c_src, tree_sitter_c::LANGUAGE.into());
let mut all = Vec::new();
for (source_id, tree, src) in [
("a.c", &a_tree, a_src),
("b.c", &b_tree, b_src),
("c.c", &c_tree, c_src),
] {
for fingerprint in function_fingerprints(tree.root_node(), src, 0) {
all.push(CorpusFingerprint {
source: source_id,
fingerprint,
});
}
}
let groups = duplicate_groups(&all);
assert_eq!(groups.len(), 1);
assert_eq!(groups[0].len(), 2);
let sources: Vec<&str> = groups[0].iter().map(|m| m.source).collect();
assert_eq!(sources, vec!["a.c", "b.c"]);
}
#[test]
#[cfg(feature = "lang-c")]
fn duplicate_groups_excludes_unique_fingerprints() {
let source = "int f(int x) { return x + 1; }";
let tree = parse(source, tree_sitter_c::LANGUAGE.into());
let all: Vec<CorpusFingerprint<&str>> = function_fingerprints(tree.root_node(), source, 0)
.into_iter()
.map(|fingerprint| CorpusFingerprint {
source: "a.c",
fingerprint,
})
.collect();
assert!(duplicate_groups(&all).is_empty());
}
#[test]
#[cfg(feature = "lang-c")]
fn block_tier_finds_match_between_non_duplicate_functions() {
let a_src = "int f(int *arr, int n) { \
int total = 0; \
for (int i = 0; i < n; i++) { total = total + arr[i]; } \
return total; }";
let b_src = "void g(int *arr, int n) { \
printf(\"start\"); \
for (int i = 0; i < n; i++) { total = total + arr[i]; } \
printf(\"end\"); }";
let tree_a = parse(a_src, tree_sitter_c::LANGUAGE.into());
let tree_b = parse(b_src, tree_sitter_c::LANGUAGE.into());
let fn_a = function_fingerprints(tree_a.root_node(), a_src, 0);
let fn_b = function_fingerprints(tree_b.root_node(), b_src, 0);
assert_ne!(
fn_a[0].hash, fn_b[0].hash,
"f and g must not be function-tier duplicates of each other"
);
let block_a = block_fingerprints(tree_a.root_node(), a_src, 0);
let block_b = block_fingerprints(tree_b.root_node(), b_src, 0);
let for_a = block_a
.iter()
.find(|fp| fp.kind == "for_statement")
.expect("f's for-loop should be a Block-tier fingerprint");
let for_b = block_b
.iter()
.find(|fp| fp.kind == "for_statement")
.expect("g's for-loop should be a Block-tier fingerprint");
assert_eq!(
for_a.hash, for_b.hash,
"the two functions' identical for-loop bodies should match at Block tier"
);
assert_eq!(for_a.tier, FingerprintTier::Block);
assert!(for_a.name.is_none(), "blocks are never named");
}
#[test]
#[cfg(feature = "lang-c")]
fn block_fingerprints_min_nodes_filters_out_trivial_subtrees() {
let source = "int f(int x) { if (x) { x = 1; } return x; }";
let tree = parse(source, tree_sitter_c::LANGUAGE.into());
let all = block_fingerprints(tree.root_node(), source, 0);
assert!(!all.is_empty());
let filtered = block_fingerprints(tree.root_node(), source, 1_000);
assert!(filtered.is_empty());
}
fn fp_with(tier: FingerprintTier, hash: u64, start_byte: usize) -> Fingerprint {
Fingerprint {
name: None,
tier,
kind: "for_statement",
hash,
node_count: 5,
start_byte,
end_byte: start_byte + 1,
start_line: 1,
end_line: 1,
}
}
#[test]
fn duplicate_groups_keeps_function_and_block_tiers_separate() {
const COLLIDING_HASH: u64 = 42;
let all = vec![
CorpusFingerprint {
source: "a.c",
fingerprint: fp_with(FingerprintTier::Function, COLLIDING_HASH, 0),
},
CorpusFingerprint {
source: "b.c",
fingerprint: fp_with(FingerprintTier::Function, COLLIDING_HASH, 10),
},
CorpusFingerprint {
source: "c.c",
fingerprint: fp_with(FingerprintTier::Block, COLLIDING_HASH, 0),
},
CorpusFingerprint {
source: "d.c",
fingerprint: fp_with(FingerprintTier::Block, COLLIDING_HASH, 10),
},
];
let groups = duplicate_groups(&all);
assert_eq!(
groups.len(),
2,
"cross-tier hash collision must not merge into one group"
);
for group in &groups {
assert_eq!(group.len(), 2);
let tier = group[0].fingerprint.tier;
assert!(
group.iter().all(|m| m.fingerprint.tier == tier),
"a group must not mix tiers"
);
}
let tiers: std::collections::HashSet<FingerprintTier> =
groups.iter().map(|g| g[0].fingerprint.tier).collect();
assert_eq!(
tiers.len(),
2,
"expected one Function group and one Block group"
);
}
}