use std::collections::{BTreeMap, HashMap, VecDeque};
use codeint_model::StableHasher;
use serde::{Deserialize, Serialize};
#[cfg(test)]
mod tests;
const MAX_EXACT_MATCH_GROUP: usize = 64;
const MAX_LINE_DISTANCE: u32 = 1_000_000;
const MATCH_WEIGHT: i64 = 1 << 44;
const CONTEXT_SHIFT: u32 = 34;
const LINE_SHIFT: u32 = 7;
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FindingAnchor {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub paths: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub before: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub after: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub line: Option<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub clone_lines: Vec<CloneLineAnchor>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CloneLineAnchor {
path: u64,
occurrence: u32,
content: u64,
}
impl CloneLineAnchor {
pub fn new(path: &str, occurrence: u32, content: u64) -> Self {
Self {
path: anchor_path_digest(path),
occurrence,
content,
}
}
pub(crate) fn with_rename(self, renames: &HashMap<u64, u64>) -> Self {
Self {
path: renames.get(&self.path).copied().unwrap_or(self.path),
..self
}
}
}
pub(crate) fn clone_line_renames(renames: &BTreeMap<String, String>) -> HashMap<u64, u64> {
renames
.iter()
.map(|(old, new)| (anchor_path_digest(old), anchor_path_digest(new)))
.collect()
}
impl FindingAnchor {
pub fn id_only(id: impl Into<String>) -> FindingAnchor {
FindingAnchor {
id: id.into(),
content: None,
body: None,
paths: Vec::new(),
before: None,
after: None,
line: None,
clone_lines: Vec::new(),
}
}
pub fn from_hashes(
id: String,
content: u64,
before: Option<u64>,
after: Option<u64>,
line: Option<u32>,
) -> FindingAnchor {
FindingAnchor {
id,
content: Some(format!("{content:016x}")),
body: None,
paths: Vec::new(),
before: before.map(|value| format!("{value:016x}")),
after: after.map(|value| format!("{value:016x}")),
line,
clone_lines: Vec::new(),
}
}
pub fn with_body_and_paths(mut self, body: Option<u64>, paths: Vec<String>) -> FindingAnchor {
self.body = body
.filter(|&value| value != 0)
.map(|value| format!("{value:016x}"));
let mut hashed: Vec<String> = paths
.into_iter()
.map(|path| hash_anchor_path(&path))
.collect();
hashed.sort();
hashed.dedup();
self.paths = hashed;
self
}
}
fn hash_anchor_path(path: &str) -> String {
format!("{:016x}", anchor_path_digest(path))
}
fn anchor_path_digest(path: &str) -> u64 {
StableHasher::new()
.write_bytes(b"codeint.anchor.path.v1")
.write_u64(path.len() as u64)
.write_bytes(path.as_bytes())
.finish()
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AnchorMatch {
pub matched_pairs: Vec<(usize, usize)>,
}
impl AnchorMatch {
pub fn matched_references(&self, len: usize) -> Vec<bool> {
let mut matched = vec![false; len];
for &(reference_index, _) in &self.matched_pairs {
matched[reference_index] = true;
}
matched
}
pub fn matched_candidates(&self, len: usize) -> Vec<bool> {
let mut matched = vec![false; len];
for &(_, candidate_index) in &self.matched_pairs {
matched[candidate_index] = true;
}
matched
}
}
pub fn remap_anchor_paths(
anchor: &FindingAnchor,
renames: &BTreeMap<String, String>,
) -> FindingAnchor {
if renames.is_empty() {
return anchor.clone();
}
let mut remapped = anchor.clone();
remapped.id = remap_paths_in_id(&anchor.id, renames);
remapped
}
pub fn match_anchors_with_renames(
references: &[FindingAnchor],
candidates: &[FindingAnchor],
renames: &BTreeMap<String, String>,
) -> AnchorMatch {
if renames.is_empty() {
return match_anchors(references, candidates);
}
let remapped_references: Vec<FindingAnchor> = references
.iter()
.map(|reference| remap_anchor_paths(reference, renames))
.collect();
let direct = match_anchors(&remapped_references, candidates);
let max_matches = references.len().min(candidates.len());
if direct.matched_pairs.len() == max_matches {
return direct;
}
let mut used_references = direct.matched_references(references.len());
let mut used_candidates = direct.matched_candidates(candidates.len());
let mut matched_pairs = direct.matched_pairs;
match_remapped_ids(
references,
&remapped_references,
candidates,
&mut used_references,
&mut used_candidates,
&mut matched_pairs,
);
if matched_pairs.len() < max_matches {
match_renamed_body_groups(
references,
candidates,
renames,
&used_references,
&used_candidates,
&mut matched_pairs,
);
}
matched_pairs.sort_unstable();
AnchorMatch { matched_pairs }
}
fn match_candidates_by_id<'a>(
candidates: &'a [FindingAnchor],
used_references: &mut [bool],
used_candidates: &mut [bool],
matched_pairs: &mut Vec<(usize, usize)>,
reference_ids: impl Iterator<Item = (usize, &'a str)>,
) {
let mut candidates_by_id: HashMap<&str, VecDeque<usize>> = HashMap::new();
for (index, candidate) in candidates.iter().enumerate() {
if !used_candidates[index] {
candidates_by_id
.entry(candidate.id.as_str())
.or_default()
.push_back(index);
}
}
for (ref_index, target_id) in reference_ids {
if let Some(queue) = candidates_by_id.get_mut(target_id)
&& let Some(cand_index) = queue.pop_front()
{
used_references[ref_index] = true;
used_candidates[cand_index] = true;
matched_pairs.push((ref_index, cand_index));
}
}
}
fn match_remapped_ids(
references: &[FindingAnchor],
remapped_references: &[FindingAnchor],
candidates: &[FindingAnchor],
used_references: &mut [bool],
used_candidates: &mut [bool],
matched_pairs: &mut Vec<(usize, usize)>,
) {
let targets: Vec<(usize, &str)> = references
.iter()
.zip(remapped_references.iter())
.enumerate()
.filter(|&(index, (original, remapped))| {
!used_references[index] && original.id != remapped.id
})
.map(|(index, (_, remapped))| (index, remapped.id.as_str()))
.collect();
match_candidates_by_id(
candidates,
used_references,
used_candidates,
matched_pairs,
targets.into_iter(),
);
}
fn canonical_paths(paths: &[String], renames: Option<&HashMap<String, String>>) -> Vec<String> {
let mut normalized: Vec<String> = paths
.iter()
.map(|path| match renames.and_then(|map| map.get(path)) {
Some(renamed) => renamed.clone(),
None => path.clone(),
})
.collect();
normalized.sort();
normalized.dedup();
normalized
}
fn build_rename_lookup(renames: &BTreeMap<String, String>) -> HashMap<String, String> {
let mut lookup = HashMap::with_capacity(renames.len() * 2);
for (old_path, new_path) in renames {
lookup.insert(old_path.clone(), new_path.clone());
lookup.insert(hash_anchor_path(old_path), hash_anchor_path(new_path));
}
lookup
}
fn group_anchors_by_body_and_paths<'a>(
anchors: &'a [FindingAnchor],
used: &[bool],
rename_lookup: Option<&HashMap<String, String>>,
) -> BTreeMap<(&'a str, Vec<String>), Vec<usize>> {
let mut groups: BTreeMap<(&'a str, Vec<String>), Vec<usize>> = BTreeMap::new();
for (index, anchor) in anchors.iter().enumerate() {
if used[index] || anchor.paths.is_empty() {
continue;
}
let Some(body) = anchor.body.as_deref() else {
continue;
};
if let Some(lookup) = rename_lookup
&& !anchor.paths.iter().any(|path| lookup.contains_key(path))
{
continue;
}
let key = (body, canonical_paths(&anchor.paths, rename_lookup));
groups.entry(key).or_default().push(index);
}
groups
}
fn match_renamed_body_groups(
references: &[FindingAnchor],
candidates: &[FindingAnchor],
renames: &BTreeMap<String, String>,
used_references: &[bool],
used_candidates: &[bool],
matched_pairs: &mut Vec<(usize, usize)>,
) {
let rename_lookup = build_rename_lookup(renames);
let reference_groups =
group_anchors_by_body_and_paths(references, used_references, Some(&rename_lookup));
if reference_groups.is_empty() {
return;
}
let candidate_groups = group_anchors_by_body_and_paths(candidates, used_candidates, None);
for (key, ref_indices) in reference_groups {
let Some(cand_indices) = candidate_groups.get(&key) else {
continue;
};
match_content_group(
references,
candidates,
&ref_indices,
cand_indices,
matched_pairs,
);
}
}
pub fn match_anchors_with_aliases(
references: &[FindingAnchor],
candidates: &[FindingAnchor],
candidate_aliases: &[Option<FindingAnchor>],
renames: &BTreeMap<String, String>,
) -> AnchorMatch {
let direct = match_anchors_with_renames(references, candidates, renames);
if candidate_aliases.is_empty()
|| direct.matched_pairs.len() == references.len().min(candidates.len())
{
return direct;
}
let ref_used = direct.matched_references(references.len());
let cand_used = direct.matched_candidates(candidates.len());
let unmatched_ref_indices: Vec<usize> = ref_used
.iter()
.enumerate()
.filter_map(|(index, &used)| (!used).then_some(index))
.collect();
let unmatched_alias_entries: Vec<(usize, FindingAnchor)> = candidate_aliases
.iter()
.enumerate()
.filter_map(|(index, alias)| {
if index < candidates.len() && !cand_used[index] {
alias.clone().map(|anchor| (index, anchor))
} else {
None
}
})
.collect();
if unmatched_ref_indices.is_empty() || unmatched_alias_entries.is_empty() {
return direct;
}
let unmatched_refs: Vec<FindingAnchor> = unmatched_ref_indices
.iter()
.map(|&index| references[index].clone())
.collect();
let unmatched_aliases: Vec<FindingAnchor> = unmatched_alias_entries
.iter()
.map(|(_, anchor)| anchor.clone())
.collect();
let alias_match = match_anchors(&unmatched_refs, &unmatched_aliases);
if alias_match.matched_pairs.is_empty() {
return direct;
}
let mut matched_pairs = direct.matched_pairs;
for (local_ref, local_alias) in alias_match.matched_pairs {
matched_pairs.push((
unmatched_ref_indices[local_ref],
unmatched_alias_entries[local_alias].0,
));
}
matched_pairs.sort_unstable();
AnchorMatch { matched_pairs }
}
fn remap_paths_in_id(id: &str, renames: &BTreeMap<String, String>) -> String {
if let Some(exact) = renames.get(id) {
return exact.clone();
}
let mut ordered: Vec<(&str, &str)> = renames
.iter()
.filter(|(old_path, _)| !old_path.is_empty() && id.contains(old_path.as_str()))
.map(|(old_path, new_path)| (old_path.as_str(), new_path.as_str()))
.collect();
if ordered.is_empty() {
return id.to_owned();
}
ordered.sort_by(|left, right| {
right
.0
.len()
.cmp(&left.0.len())
.then_with(|| left.0.cmp(right.0))
});
let mut result = id.to_owned();
for (old_path, new_path) in ordered {
result = replace_path_bounded(&result, old_path, new_path);
}
result
}
fn replace_path_bounded(text: &str, old_path: &str, new_path: &str) -> String {
let mut output = String::with_capacity(text.len());
let mut rest = text;
let mut offset = 0usize;
while let Some(pos) = rest.find(old_path) {
let abs_start = offset + pos;
let abs_end = abs_start + old_path.len();
let left_ok = abs_start == 0
|| text[..abs_start]
.chars()
.next_back()
.is_some_and(is_path_delimiter);
let right_ok = abs_end == text.len()
|| text[abs_end..]
.chars()
.next()
.is_some_and(is_path_delimiter);
output.push_str(&rest[..pos]);
if left_ok && right_ok {
output.push_str(new_path);
} else {
output.push_str(old_path);
}
let advance = pos + old_path.len();
rest = &rest[advance..];
offset += advance;
}
output.push_str(rest);
output
}
fn is_path_delimiter(ch: char) -> bool {
matches!(
ch,
':' | ',' | ' ' | '\t' | '|' | '[' | ']' | '(' | ')' | '#' | '@' | ';'
)
}
pub fn match_anchors(references: &[FindingAnchor], candidates: &[FindingAnchor]) -> AnchorMatch {
if references.is_empty() || candidates.is_empty() {
return AnchorMatch::default();
}
let mut matched_pairs = Vec::new();
let mut used_references = vec![false; references.len()];
let mut used_candidates = vec![false; candidates.len()];
match_id_only_references(
references,
candidates,
&mut used_references,
&mut used_candidates,
&mut matched_pairs,
);
let reference_groups = group_unused_by_content(references, &used_references);
let candidate_groups = group_unused_by_content(candidates, &used_candidates);
for (content, ref_indices) in reference_groups {
let Some(cand_indices) = candidate_groups.get(content) else {
continue;
};
match_content_group(
references,
candidates,
&ref_indices,
cand_indices,
&mut matched_pairs,
);
}
matched_pairs.sort_unstable();
AnchorMatch { matched_pairs }
}
fn group_unused_by_content<'a>(
anchors: &'a [FindingAnchor],
used: &[bool],
) -> BTreeMap<&'a str, Vec<usize>> {
let mut groups: BTreeMap<&'a str, Vec<usize>> = BTreeMap::new();
for (index, anchor) in anchors.iter().enumerate() {
if !used[index]
&& let Some(content) = anchor.content.as_deref()
{
groups.entry(content).or_default().push(index);
}
}
groups
}
fn match_id_only_references(
references: &[FindingAnchor],
candidates: &[FindingAnchor],
used_references: &mut [bool],
used_candidates: &mut [bool],
matched_pairs: &mut Vec<(usize, usize)>,
) {
let targets = references
.iter()
.enumerate()
.filter(|(_, reference)| reference.content.is_none())
.map(|(index, reference)| (index, reference.id.as_str()));
match_candidates_by_id(
candidates,
used_references,
used_candidates,
matched_pairs,
targets,
);
}
fn match_content_group(
references: &[FindingAnchor],
candidates: &[FindingAnchor],
ref_indices: &[usize],
cand_indices: &[usize],
matched_pairs: &mut Vec<(usize, usize)>,
) {
if ref_indices.len() == 1 && cand_indices.len() == 1 {
matched_pairs.push((ref_indices[0], cand_indices[0]));
return;
}
if ref_indices.len().max(cand_indices.len()) <= MAX_EXACT_MATCH_GROUP {
match_group_exact(
references,
candidates,
ref_indices,
cand_indices,
matched_pairs,
);
} else {
match_group_bucketed(
references,
candidates,
ref_indices,
cand_indices,
matched_pairs,
);
}
}
fn match_group_exact(
references: &[FindingAnchor],
candidates: &[FindingAnchor],
ref_indices: &[usize],
cand_indices: &[usize],
matched_pairs: &mut Vec<(usize, usize)>,
) {
let size = ref_indices.len().max(cand_indices.len());
let mut weights = vec![vec![0i64; size]; size];
for (row, &ref_index) in ref_indices.iter().enumerate() {
for (col, &cand_index) in cand_indices.iter().enumerate() {
weights[row][col] = pair_weight(&references[ref_index], &candidates[cand_index]);
}
}
let assignment = hungarian_max_weight(&weights);
for (row, &col) in assignment.iter().enumerate() {
if row < ref_indices.len() && col < cand_indices.len() {
matched_pairs.push((ref_indices[row], cand_indices[col]));
}
}
}
fn pair_weight(reference: &FindingAnchor, candidate: &FindingAnchor) -> i64 {
let context_score = context_match_score(reference, candidate);
let line_bonus = line_proximity_bonus(reference.line, candidate.line);
let same_id = i64::from(reference.id == candidate.id);
MATCH_WEIGHT + (context_score << CONTEXT_SHIFT) + (line_bonus << LINE_SHIFT) + same_id
}
fn context_match_score(reference: &FindingAnchor, candidate: &FindingAnchor) -> i64 {
let has_line_bounds = reference.line.is_some() && candidate.line.is_some();
side_match_score(
reference.before.as_deref(),
candidate.before.as_deref(),
has_line_bounds,
) + side_match_score(
reference.after.as_deref(),
candidate.after.as_deref(),
has_line_bounds,
)
}
fn side_match_score(
reference_side: Option<&str>,
candidate_side: Option<&str>,
has_line_bounds: bool,
) -> i64 {
match (reference_side, candidate_side) {
(Some(left), Some(right)) if left == right => 3,
(None, None) if has_line_bounds => 2,
_ => 0,
}
}
fn line_proximity_bonus(reference_line: Option<u32>, candidate_line: Option<u32>) -> i64 {
let distance = match (reference_line, candidate_line) {
(Some(left), Some(right)) => left.abs_diff(right).min(MAX_LINE_DISTANCE),
_ => MAX_LINE_DISTANCE,
};
i64::from(MAX_LINE_DISTANCE - distance)
}
struct HungarianSolver<'a> {
weights: &'a [Vec<i64>],
max_weight: i64,
u: Vec<i64>,
v: Vec<i64>,
p: Vec<usize>,
way: Vec<usize>,
}
impl<'a> HungarianSolver<'a> {
fn new(weights: &'a [Vec<i64>]) -> HungarianSolver<'a> {
let n = weights.len();
let max_weight = weights
.iter()
.flat_map(|row| row.iter().copied())
.max()
.unwrap_or(0);
HungarianSolver {
weights,
max_weight,
u: vec![0; n + 1],
v: vec![0; n + 1],
p: vec![0; n + 1],
way: vec![0; n + 1],
}
}
fn solve(mut self) -> Vec<usize> {
let n = self.weights.len();
for row in 1..=n {
self.augment_row(row);
}
let mut assignment = vec![0usize; n];
for col in 1..=n {
if self.p[col] > 0 {
assignment[self.p[col] - 1] = col - 1;
}
}
assignment
}
fn augment_row(&mut self, row: usize) {
let n = self.weights.len();
self.p[0] = row;
let mut col0 = 0usize;
let mut min_v = vec![i64::MAX; n + 1];
let mut used = vec![false; n + 1];
loop {
used[col0] = true;
let (delta, next_col) = self.relax_columns(col0, &used, &mut min_v);
self.shift_potentials(&used, &mut min_v, delta);
col0 = next_col;
if self.p[col0] == 0 {
break;
}
}
self.unwind_path(col0);
}
fn relax_columns(&mut self, col0: usize, used: &[bool], min_v: &mut [i64]) -> (i64, usize) {
let row0 = self.p[col0];
let mut delta = i64::MAX;
let mut best_col = 0usize;
for col in 1..=self.weights.len() {
if used[col] {
continue;
}
let cost = self.max_weight - self.weights[row0 - 1][col - 1];
let current = cost - self.u[row0] - self.v[col];
if current < min_v[col] {
min_v[col] = current;
self.way[col] = col0;
}
if min_v[col] < delta {
delta = min_v[col];
best_col = col;
}
}
(delta, best_col)
}
fn shift_potentials(&mut self, used: &[bool], min_v: &mut [i64], delta: i64) {
for col in 0..=self.weights.len() {
if used[col] {
self.u[self.p[col]] += delta;
self.v[col] -= delta;
} else {
min_v[col] -= delta;
}
}
}
fn unwind_path(&mut self, mut col0: usize) {
while col0 != 0 {
let col1 = self.way[col0];
self.p[col0] = self.p[col1];
col0 = col1;
}
}
}
fn hungarian_max_weight(weights: &[Vec<i64>]) -> Vec<usize> {
HungarianSolver::new(weights).solve()
}
struct BucketedMatcher<'a> {
references: &'a [FindingAnchor],
candidates: &'a [FindingAnchor],
ref_indices: &'a [usize],
cand_indices: &'a [usize],
ref_used: Vec<bool>,
cand_used: Vec<bool>,
}
impl<'a> BucketedMatcher<'a> {
fn pair_by_key<K: Eq + std::hash::Hash>(
&mut self,
matched_pairs: &mut Vec<(usize, usize)>,
key_of: impl Fn(&'a FindingAnchor) -> Option<K>,
) {
let mut buckets: HashMap<K, VecDeque<usize>> = HashMap::new();
for (cand_pos, &cand_index) in self.cand_indices.iter().enumerate() {
if !self.cand_used[cand_pos]
&& let Some(key) = key_of(&self.candidates[cand_index])
{
buckets.entry(key).or_default().push_back(cand_pos);
}
}
for (ref_pos, &ref_index) in self.ref_indices.iter().enumerate() {
if self.ref_used[ref_pos] {
continue;
}
if let Some(key) = key_of(&self.references[ref_index])
&& let Some(queue) = buckets.get_mut(&key)
&& let Some(cand_pos) = queue.pop_front()
{
self.ref_used[ref_pos] = true;
self.cand_used[cand_pos] = true;
matched_pairs.push((ref_index, self.cand_indices[cand_pos]));
}
}
}
}
fn match_group_bucketed(
references: &[FindingAnchor],
candidates: &[FindingAnchor],
ref_indices: &[usize],
cand_indices: &[usize],
matched_pairs: &mut Vec<(usize, usize)>,
) {
let mut matcher = BucketedMatcher {
references,
candidates,
ref_indices,
cand_indices,
ref_used: vec![false; ref_indices.len()],
cand_used: vec![false; cand_indices.len()],
};
matcher.pair_by_key(matched_pairs, |anchor| {
Some((anchor.before.as_deref(), anchor.after.as_deref()))
});
matcher.pair_by_key(matched_pairs, |anchor| anchor.before.as_deref());
matcher.pair_by_key(matched_pairs, |anchor| anchor.after.as_deref());
let remaining_refs = ref_indices
.iter()
.enumerate()
.filter(|&(pos, _)| !matcher.ref_used[pos])
.map(|(_, &index)| index);
let remaining_cands = cand_indices
.iter()
.enumerate()
.filter(|&(pos, _)| !matcher.cand_used[pos])
.map(|(_, &index)| index);
matched_pairs.extend(remaining_refs.zip(remaining_cands));
}