heddle-semantic 0.15.5

An AI-native version control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// SPDX-License-Identifier: Apache-2.0
//! Function-level semantic changes.

use std::collections::{BTreeMap, BTreeSet, HashSet};

use objects::object::{ChangeImportance, SemanticChange};

use super::analysis_similarity::{SimilarityMethod, compute_similarity_with_language};
use crate::parser::{FunctionDef, Language, ParsedFile};

const FUNCTION_RENAME_SIMILARITY_THRESHOLD: f64 = 0.58;
const FUNCTION_RENAME_CANDIDATE_THRESHOLD: f64 = 0.30;
const FUNCTION_RENAME_CONFIDENCE_MARGIN: f64 = 0.05;

/// One structurally plausible target for a function that disappeared under
/// its old name.
#[derive(Clone, Debug, PartialEq)]
pub struct FunctionRenameCandidate {
    pub new_name: String,
    pub confidence: f64,
    /// Whether bytes other than the consistently renamed function name changed.
    pub body_changed: bool,
}

/// Conservative result for resolving one function rename.
///
/// The general semantic diff may choose a stable best pairing so it can
/// describe a whole file. Durable anchors have a stricter contract: only a
/// high-confidence candidate with a clear lead may move the anchor.
#[derive(Clone, Debug, PartialEq)]
pub enum FunctionRenameResolution {
    Renamed(FunctionRenameCandidate),
    Ambiguous(Vec<FunctionRenameCandidate>),
    NotRenamed,
}

/// Multi-map: function name → all definitions on this side with that
/// name, in source order.
///
/// `BTreeMap<String, FunctionDef>` would silently collapse same-name
/// redeclarations (JS allows two `function foo()` at module scope;
/// Python allows repeated top-level `def foo()`). A prior fix (r1)
/// keyed entries by `(name, occurrence)` to stop the collapse, but
/// that paired old's `foo[0]` with new's `foo[0]` regardless of body
/// content — so a fresh same-name definition inserted before existing
/// ones produced a bogus FunctionModified with the wrong delta plus a
/// misclassified add/delete (Codex cid 3259311747, heddle#125 r2).
///
/// Keeping a `Vec` per name lets us pair instances across versions by
/// *content similarity* (see `pair_within_name`) rather than by
/// within-side position. merge_driver keeps the positional keying
/// (commit 2198b00) because its job is line-up merging within a
/// logical slot; analysis_functions needs fuzzy cross-version identity.
type FunctionMap = BTreeMap<String, Vec<FunctionDef>>;

/// `(name, within-side index)` — identifies a single function instance
/// on one side. Not a cross-version identity.
type InstanceRef = (String, usize);

fn build_function_map(parsed: Option<&ParsedFile>) -> FunctionMap {
    let Some(parsed) = parsed else {
        return BTreeMap::new();
    };
    let mut map = FunctionMap::new();
    for func in parsed.extract_functions() {
        map.entry(func.name.clone()).or_default().push(func);
    }
    map
}

/// Greedy best-similarity matcher within a single name bucket. Returns
/// (paired old/new indices, unpaired old indices, unpaired new indices).
fn pair_within_name(
    olds: &[FunctionDef],
    news: &[FunctionDef],
    similarity_method: SimilarityMethod,
    language: Language,
) -> (Vec<(usize, usize)>, Vec<usize>, Vec<usize>) {
    let mut candidates: Vec<(usize, usize, f64)> = Vec::with_capacity(olds.len() * news.len());
    for (i, o) in olds.iter().enumerate() {
        for (j, n) in news.iter().enumerate() {
            let similarity = if o.content == n.content {
                1.0
            } else {
                compute_similarity_with_language(
                    &o.content,
                    &n.content,
                    similarity_method,
                    language,
                )
            };
            candidates.push((i, j, similarity));
        }
    }
    // Highest similarity first; deterministic tiebreak: lowest old, then lowest new.
    candidates
        .sort_by(|(li, lj, ls), (ri, rj, rs)| rs.total_cmp(ls).then(li.cmp(ri)).then(lj.cmp(rj)));

    let mut old_used = vec![false; olds.len()];
    let mut new_used = vec![false; news.len()];
    let mut pairs = Vec::new();
    for (i, j, _) in candidates {
        if !old_used[i] && !new_used[j] {
            old_used[i] = true;
            new_used[j] = true;
            pairs.push((i, j));
        }
    }
    let unmatched_old = old_used
        .iter()
        .enumerate()
        .filter_map(|(i, used)| (!*used).then_some(i))
        .collect();
    let unmatched_new = new_used
        .iter()
        .enumerate()
        .filter_map(|(j, used)| (!*used).then_some(j))
        .collect();
    (pairs, unmatched_old, unmatched_new)
}

/// Detect function-level changes between two file versions.
pub fn detect_function_changes(
    old_path: &std::path::Path,
    new_path: &std::path::Path,
    old_content: &str,
    new_content: &str,
    similarity_method: SimilarityMethod,
) -> Vec<SemanticChange> {
    let old_parsed = ParsedFile::parse(old_content, Language::from_path(old_path));
    let new_parsed = ParsedFile::parse(new_content, Language::from_path(new_path));

    detect_function_changes_with_parsed(
        old_path,
        new_path,
        old_parsed.as_ref(),
        new_parsed.as_ref(),
        similarity_method,
    )
}

/// Resolve the new name of one function within a single file.
///
/// Candidates come from parsed function definitions that are new under their
/// qualified identity and share the original definition's container. This
/// deliberately excludes text search and existing, unchanged neighbours.
pub fn resolve_function_rename(
    path: &std::path::Path,
    old_content: &str,
    new_content: &str,
    old_name: &str,
    similarity_method: SimilarityMethod,
) -> FunctionRenameResolution {
    let language = Language::from_path(path);
    let Some(old_parsed) = ParsedFile::parse(old_content, language) else {
        return FunctionRenameResolution::NotRenamed;
    };
    let Some(new_parsed) = ParsedFile::parse(new_content, language) else {
        return FunctionRenameResolution::NotRenamed;
    };
    let old_functions = old_parsed.extract_functions();
    let new_functions = new_parsed.extract_functions();
    let qualified = old_name.contains("::");
    let old_matches = old_functions
        .iter()
        .filter(|function| {
            if qualified {
                function.qualified_name() == old_name
            } else {
                function.name == old_name
            }
        })
        .collect::<Vec<_>>();
    let [old_function] = old_matches.as_slice() else {
        return if old_matches.is_empty() {
            FunctionRenameResolution::NotRenamed
        } else {
            FunctionRenameResolution::Ambiguous(Vec::new())
        };
    };

    let old_identities = old_functions
        .iter()
        .map(FunctionDef::qualified_name)
        .collect::<BTreeSet<_>>();
    let old_normalized =
        normalized_function_for_matching(&old_function.content, &old_function.name);
    let mut candidates = new_functions
        .iter()
        .filter(|function| function.container == old_function.container)
        .filter(|function| function.name != old_function.name)
        .filter(|function| !old_identities.contains(&function.qualified_name()))
        .filter_map(|function| {
            let new_normalized =
                normalized_function_for_matching(&function.content, &function.name);
            let confidence = compute_similarity_with_language(
                &old_normalized,
                &new_normalized,
                similarity_method,
                language,
            );
            (confidence >= FUNCTION_RENAME_CANDIDATE_THRESHOLD).then(|| FunctionRenameCandidate {
                new_name: if qualified {
                    function.qualified_name()
                } else {
                    function.name.clone()
                },
                confidence,
                body_changed: renamed_function_content(&old_function.content, &old_function.name)
                    != renamed_function_content(&function.content, &function.name),
            })
        })
        .collect::<Vec<_>>();
    candidates.sort_by(|left, right| {
        right
            .confidence
            .total_cmp(&left.confidence)
            .then_with(|| left.new_name.cmp(&right.new_name))
    });

    let Some(best) = candidates.first() else {
        return FunctionRenameResolution::NotRenamed;
    };
    let clear_lead = candidates.get(1).is_none_or(|runner_up| {
        best.confidence - runner_up.confidence >= FUNCTION_RENAME_CONFIDENCE_MARGIN
    });
    if best.confidence >= FUNCTION_RENAME_SIMILARITY_THRESHOLD && clear_lead {
        FunctionRenameResolution::Renamed(best.clone())
    } else {
        FunctionRenameResolution::Ambiguous(candidates)
    }
}

pub(crate) fn detect_function_changes_with_parsed(
    old_path: &std::path::Path,
    new_path: &std::path::Path,
    old_parsed: Option<&ParsedFile>,
    new_parsed: Option<&ParsedFile>,
    similarity_method: SimilarityMethod,
) -> Vec<SemanticChange> {
    let mut changes = Vec::new();
    let mut file_modified = false;

    let old_funcs = build_function_map(old_parsed);
    let new_funcs = build_function_map(new_parsed);
    let language = Language::from_path(new_path);

    // Phase 1: pair instances within each name bucket by content similarity.
    let mut pairs: Vec<(String, usize, usize)> = Vec::new();
    let mut unmatched_old: Vec<InstanceRef> = Vec::new();
    let mut unmatched_new: Vec<InstanceRef> = Vec::new();

    let mut all_names: BTreeSet<&str> = BTreeSet::new();
    all_names.extend(old_funcs.keys().map(String::as_str));
    all_names.extend(new_funcs.keys().map(String::as_str));

    let empty: Vec<FunctionDef> = Vec::new();
    for name in &all_names {
        let olds = old_funcs.get(*name).unwrap_or(&empty);
        let news = new_funcs.get(*name).unwrap_or(&empty);
        let (within, u_old, u_new) = pair_within_name(olds, news, similarity_method, language);
        for (oi, ni) in within {
            pairs.push(((*name).to_string(), oi, ni));
        }
        unmatched_old.extend(u_old.into_iter().map(|i| ((*name).to_string(), i)));
        unmatched_new.extend(u_new.into_iter().map(|i| ((*name).to_string(), i)));
    }
    pairs.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.cmp(&b.2)));

    let moved_function_names = stable_order_moved_names(&old_funcs, &new_funcs, &pairs);

    // Phase 2: cross-name rename detection over leftovers.
    let mut consumed_old: HashSet<InstanceRef> = HashSet::new();
    for (new_name, ni) in &unmatched_new {
        let new_func = &new_funcs[new_name][*ni];
        let renamed_from = unmatched_old
            .iter()
            .filter(|(on, oi)| !consumed_old.contains(&(on.clone(), *oi)))
            .filter(|(on, _)| on != new_name)
            .filter_map(|(on, oi)| {
                let old_func = &old_funcs[on][*oi];
                let similarity = compute_similarity_with_language(
                    &normalized_function_for_matching(&old_func.content, on),
                    &normalized_function_for_matching(&new_func.content, new_name),
                    similarity_method,
                    language,
                );
                let same_location_update = old_path == new_path
                    && old_func.start_line.abs_diff(new_func.start_line) <= 5
                    && similarity >= 0.30;
                (similarity >= FUNCTION_RENAME_SIMILARITY_THRESHOLD || same_location_update)
                    .then_some(((on.clone(), *oi), similarity))
            })
            .max_by(
                |(left_key, left_similarity), (right_key, right_similarity)| {
                    left_similarity
                        .total_cmp(right_similarity)
                        .then_with(|| right_key.cmp(left_key))
                },
            )
            .map(|(key, _)| key);

        if let Some((old_name, old_idx)) = renamed_from {
            consumed_old.insert((old_name.clone(), old_idx));
            changes.push(SemanticChange::FunctionRenamed {
                file: new_path.to_path_buf(),
                old_name,
                new_name: new_name.clone(),
                importance: Some(ChangeImportance::Low),
            });
            file_modified = true;
        } else {
            let source = extraction_source(&old_funcs, new_func);
            if let Some(source_name) = source {
                changes.push(SemanticChange::FunctionExtracted {
                    file: new_path.to_path_buf(),
                    name: new_name.clone(),
                    source_file: Some(old_path.to_path_buf()),
                    source_name: Some(source_name),
                    importance: Some(ChangeImportance::High),
                });
            } else {
                changes.push(SemanticChange::FunctionAdded {
                    file: new_path.to_path_buf(),
                    name: new_name.clone(),
                    importance: Some(ChangeImportance::High),
                });
            }
            file_modified = true;
        }
    }

    // Phase 3: unconsumed unmatched_old → deletions.
    for (old_name, oi) in &unmatched_old {
        if consumed_old.contains(&(old_name.clone(), *oi)) {
            continue;
        }
        changes.push(SemanticChange::FunctionDeleted {
            file: new_path.to_path_buf(),
            name: old_name.clone(),
            importance: Some(ChangeImportance::High),
        });
        file_modified = true;
    }

    // Phase 4: paired instances → signature / move / modified.
    for (name, oi, ni) in &pairs {
        let old_func = &old_funcs[name][*oi];
        let new_func = &new_funcs[name][*ni];
        if old_func.signature != new_func.signature {
            changes.push(SemanticChange::SignatureChanged {
                file: new_path.to_path_buf(),
                name: name.clone(),
                old_signature: old_func.signature.clone(),
                new_signature: new_func.signature.clone(),
                importance: Some(ChangeImportance::Medium),
            });
            file_modified = true;
        } else if old_path == new_path
            && old_func.content == new_func.content
            && old_func.start_line != new_func.start_line
            && moved_function_names.contains(name)
        {
            changes.push(SemanticChange::FunctionMoved {
                file: new_path.to_path_buf(),
                name: name.clone(),
                old_start_line: old_func.start_line,
                new_start_line: new_func.start_line,
                importance: Some(ChangeImportance::Low),
            });
            file_modified = true;
        } else if old_func.content != new_func.content {
            changes.push(SemanticChange::FunctionModified {
                file: new_path.to_path_buf(),
                name: name.clone(),
                importance: Some(ChangeImportance::Medium),
            });
            file_modified = true;
        }
    }

    if file_modified {
        changes.push(SemanticChange::FileModified {
            path: new_path.to_path_buf(),
            classification: None,
            importance: None,
            confidence: None,
        });
    }

    changes
}

fn extraction_source(old_funcs: &FunctionMap, extracted: &FunctionDef) -> Option<String> {
    let extracted_lines = meaningful_body_lines(&extracted.content);
    if extracted_lines.is_empty() {
        return None;
    }

    old_funcs
        .iter()
        .flat_map(|(name, funcs)| funcs.iter().map(move |func| (name.clone(), func)))
        .filter_map(|(name, old_func)| {
            let old_lines = meaningful_body_lines(&old_func.content);
            let evidence = extraction_evidence(&old_lines, &extracted_lines);
            evidence.is_strong().then_some((name, evidence))
        })
        .max_by(|left, right| {
            left.1
                .score
                .total_cmp(&right.1.score)
                .then_with(|| left.1.matched.cmp(&right.1.matched))
                .then_with(|| right.0.cmp(&left.0))
        })
        .map(|(name, _)| name)
}

#[derive(Debug)]
struct ExtractionEvidence {
    matched: usize,
    score: f64,
    exact_matches: usize,
    longest_exact_expression_len: usize,
    extracted_lines: usize,
}

impl ExtractionEvidence {
    fn is_strong(&self) -> bool {
        if self.extracted_lines == 0 {
            return false;
        }

        let coverage = self.matched as f64 / self.extracted_lines as f64;
        let weighted_coverage = self.score / self.extracted_lines as f64;

        if self.extracted_lines == 1 {
            return self.exact_matches == 1
                && weighted_coverage >= 0.95
                && self.longest_exact_expression_len >= 20;
        }

        coverage >= 0.70 && weighted_coverage >= 0.70
    }
}

fn extraction_evidence(old_lines: &[String], extracted_lines: &[String]) -> ExtractionEvidence {
    let mut matched = 0;
    let mut score = 0.0;
    let mut exact_matches = 0;
    let mut longest_exact_expression_len = 0;

    for line in extracted_lines {
        let best = old_lines
            .iter()
            .map(|old_line| body_line_match(old_line, line))
            .max_by(|left, right| left.score.total_cmp(&right.score))
            .unwrap_or_default();
        if best.score > 0.0 {
            matched += 1;
            score += best.score;
        }
        if best.score >= 1.0 {
            exact_matches += 1;
            longest_exact_expression_len = longest_exact_expression_len.max(best.expression_len);
        }
    }

    ExtractionEvidence {
        matched,
        score,
        exact_matches,
        longest_exact_expression_len,
        extracted_lines: extracted_lines.len(),
    }
}

#[derive(Clone, Copy, Debug, Default)]
struct BodyLineMatch {
    score: f64,
    expression_len: usize,
}

fn body_line_match(old_line: &str, extracted_line: &str) -> BodyLineMatch {
    let old = comparable_body_expression(old_line);
    let extracted = comparable_body_expression(extracted_line);
    if old == extracted {
        return BodyLineMatch {
            score: 1.0,
            expression_len: extracted.len(),
        };
    }
    if extracted.len() >= 24 && old.contains(&extracted) {
        return BodyLineMatch {
            score: 0.75,
            expression_len: extracted.len(),
        };
    }
    if old.len() >= 24 && extracted.contains(&old) {
        return BodyLineMatch {
            score: 0.75,
            expression_len: old.len(),
        };
    }
    BodyLineMatch::default()
}

fn comparable_body_expression(line: &str) -> String {
    let trimmed = line
        .trim()
        .trim_end_matches(';')
        .trim_start_matches("return ")
        .trim();
    let expression = trimmed
        .split_once('=')
        .map(|(_, rhs)| rhs.trim())
        .unwrap_or(trimmed);
    expression.trim_end_matches(';').trim().to_string()
}

fn meaningful_body_lines(content: &str) -> Vec<String> {
    content
        .lines()
        .map(str::trim)
        .filter(|line| {
            !line.is_empty()
                && *line != "{"
                && *line != "}"
                && !line.starts_with("fn ")
                && !line.starts_with("pub fn ")
                && !line.starts_with("async fn ")
                && !line.starts_with("pub async fn ")
        })
        .map(ToString::to_string)
        .collect()
}

fn stable_order_moved_names(
    old_funcs: &FunctionMap,
    new_funcs: &FunctionMap,
    pairs: &[(String, usize, usize)],
) -> HashSet<String> {
    let mut old_order: Vec<(usize, String)> = Vec::new();
    let mut new_order: Vec<(usize, String)> = Vec::new();
    for (name, oi, ni) in pairs {
        let old_func = &old_funcs[name][*oi];
        let new_func = &new_funcs[name][*ni];
        if old_func.content == new_func.content {
            old_order.push((old_func.start_line, name.clone()));
            new_order.push((new_func.start_line, name.clone()));
        }
    }
    old_order.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));
    new_order.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1)));

    let old_names: Vec<String> = old_order.into_iter().map(|(_, n)| n).collect();
    let new_names: Vec<String> = new_order.into_iter().map(|(_, n)| n).collect();
    if old_names == new_names {
        return HashSet::new();
    }
    old_names
        .into_iter()
        .zip(new_names)
        .filter_map(|(old_name, new_name)| (old_name != new_name).then_some([old_name, new_name]))
        .flatten()
        .collect()
}

fn normalized_function_for_matching(content: &str, name: &str) -> String {
    renamed_function_content(content, name)
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

fn renamed_function_content(content: &str, name: &str) -> String {
    content.replace(name, "__function_name__")
}