sem-core 0.6.0

Entity-level semantic diff engine. Extracts functions, classes, and methods from 20 languages via tree-sitter and diffs at the entity level.
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
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use serde::Serialize;

use crate::git::types::FileChange;

macro_rules! maybe_par_iter {
    ($slice:expr) => {{
        #[cfg(feature = "parallel")]
        {
            $slice.par_iter()
        }
        #[cfg(not(feature = "parallel"))]
        {
            $slice.iter()
        }
    }};
}
use crate::model::change::{ChangeType, SemanticChange};
use crate::model::entity::SemanticEntity;
use crate::model::identity::match_entities;
use crate::parser::registry::ParserRegistry;
use std::collections::{HashMap, HashSet};

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DiffResult {
    pub changes: Vec<SemanticChange>,
    pub file_count: usize,
    pub added_count: usize,
    pub modified_count: usize,
    pub deleted_count: usize,
    pub moved_count: usize,
    pub renamed_count: usize,
    pub reordered_count: usize,
    pub orphan_count: usize,
    pub total_entities_before: usize,
    pub total_entities_after: usize,
}

pub fn compute_semantic_diff(
    file_changes: &[FileChange],
    registry: &ParserRegistry,
    commit_sha: Option<&str>,
    author: Option<&str>,
) -> DiffResult {
    // Process files in parallel: each file's entity extraction and matching is independent
    let per_file_changes: Vec<(String, Vec<SemanticChange>, usize, usize)> =
        maybe_par_iter!(file_changes)
            .filter_map(|file| {
                let content_hint = file
                    .after_content
                    .as_deref()
                    .or(file.before_content.as_deref())
                    .unwrap_or("");
                let resolved = registry.resolve_file_path(&file.file_path);
                let detection_path = resolved.as_deref().unwrap_or(&file.file_path);
                let plugin = registry.get_plugin_with_content(detection_path, content_hint)?;

                let before_entities = if let Some(ref content) = file.before_content {
                    let before_path = file.old_file_path.as_deref().unwrap_or(&file.file_path);
                    let before_resolved = registry.resolve_file_path(before_path);
                    let before_detection = before_resolved.as_deref().unwrap_or(before_path);
                    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        plugin.extract_entities(content, before_detection)
                    })) {
                        Ok(entities) => entities,
                        Err(_) => Vec::new(),
                    }
                } else {
                    Vec::new()
                };

                let after_entities = if let Some(ref content) = file.after_content {
                    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        plugin.extract_entities(content, detection_path)
                    })) {
                        Ok(entities) => entities,
                        Err(_) => Vec::new(),
                    }
                } else {
                    Vec::new()
                };

                let before_count = before_entities.len();
                let after_count = after_entities.len();

                let sim_fn = |a: &crate::model::entity::SemanticEntity,
                              b: &crate::model::entity::SemanticEntity|
                 -> f64 { plugin.compute_similarity(a, b) };

                let mut result = match_entities(
                    &before_entities,
                    &after_entities,
                    &file.file_path,
                    Some(&sim_fn),
                    commit_sha,
                    author,
                );

                // Suppress parent entities whose modification is already explained
                // by child entity changes (e.g. impl blocks when methods changed).
                suppress_redundant_parents(&mut result.changes, &before_entities, &after_entities);

                // Detect orphan changes (lines that changed outside any entity span).
                let orphans = detect_orphan_changes(
                    file,
                    &before_entities,
                    &after_entities,
                    commit_sha,
                    author,
                );
                result.changes.extend(orphans);

                result.changes.sort_by_key(|change| change.entity_line);

                if result.changes.is_empty() {
                    None
                } else {
                    Some((
                        file.file_path.clone(),
                        result.changes,
                        before_count,
                        after_count,
                    ))
                }
            })
            .collect();

    let mut all_changes: Vec<SemanticChange> = Vec::new();
    let mut files_with_changes: HashSet<String> = HashSet::new();
    let mut total_entities_before: usize = 0;
    let mut total_entities_after: usize = 0;
    for (file_path, changes, before_count, after_count) in per_file_changes {
        files_with_changes.insert(file_path);
        all_changes.extend(changes);
        total_entities_before += before_count;
        total_entities_after += after_count;
    }

    // Single-pass counting (exclude orphan changes from entity counts)
    let mut added_count = 0;
    let mut modified_count = 0;
    let mut deleted_count = 0;
    let mut moved_count = 0;
    let mut renamed_count = 0;
    let mut reordered_count = 0;
    let mut orphan_count = 0;

    for c in &all_changes {
        if c.entity_type == "orphan" {
            orphan_count += 1;
            continue;
        }
        match c.change_type {
            ChangeType::Added => added_count += 1,
            ChangeType::Modified => modified_count += 1,
            ChangeType::Deleted => deleted_count += 1,
            ChangeType::Moved => moved_count += 1,
            ChangeType::Renamed => renamed_count += 1,
            ChangeType::Reordered => reordered_count += 1,
        }
    }

    DiffResult {
        changes: all_changes,
        file_count: files_with_changes.len(),
        added_count,
        modified_count,
        deleted_count,
        moved_count,
        renamed_count,
        reordered_count,
        orphan_count,
        total_entities_before,
        total_entities_after,
    }
}

fn suppress_redundant_parents(
    changes: &mut Vec<SemanticChange>,
    before: &[SemanticEntity],
    after: &[SemanticEntity],
) {
    if changes.len() < 2 {
        return;
    }

    const CONTAINER_TYPES: &[&str] = &[
        "impl",
        "trait",
        "module",
        "class",
        "interface",
        "mixin",
        "extension",
        "namespace",
        "export",
        "package",
        "svelte_instance_script",
        "svelte_module_script",
        "object",
    ];

    let before_by_id: HashMap<&str, &SemanticEntity> =
        before.iter().map(|e| (e.id.as_str(), e)).collect();
    let after_by_id: HashMap<&str, &SemanticEntity> =
        after.iter().map(|e| (e.id.as_str(), e)).collect();

    let mut before_children: HashMap<&str, Vec<&SemanticEntity>> = HashMap::new();
    for e in before {
        if let Some(ref pid) = e.parent_id {
            before_children.entry(pid.as_str()).or_default().push(e);
        }
    }
    let mut after_children: HashMap<&str, Vec<&SemanticEntity>> = HashMap::new();
    for e in after {
        if let Some(ref pid) = e.parent_id {
            after_children.entry(pid.as_str()).or_default().push(e);
        }
    }

    let changed_ids: HashSet<&str> = changes.iter().map(|c| c.entity_id.as_str()).collect();

    let mut suppress: HashSet<String> = HashSet::new();
    for change in changes.iter() {
        if !matches!(
            change.change_type,
            ChangeType::Modified | ChangeType::Added | ChangeType::Deleted
        ) {
            continue;
        }
        if !CONTAINER_TYPES.contains(&change.entity_type.as_str()) {
            continue;
        }
        let eid = change.entity_id.as_str();
        let b_children = before_children
            .get(eid)
            .map(|v| v.as_slice())
            .unwrap_or(&[]);
        let a_children = after_children.get(eid).map(|v| v.as_slice()).unwrap_or(&[]);

        let has_changed_child = b_children
            .iter()
            .any(|c| changed_ids.contains(c.id.as_str()))
            || a_children
                .iter()
                .any(|c| changed_ids.contains(c.id.as_str()));
        if !has_changed_child {
            continue;
        }

        // Added/Deleted: suppress unconditionally; the children carry the detail.
        // Modified: only suppress if the container's own declaration is unchanged
        // and the value type didn't transition.
        let should_suppress = if change.change_type == ChangeType::Modified {
            match (before_by_id.get(eid), after_by_id.get(eid)) {
                (Some(bp), Some(ap)) if bp.entity_type == ap.entity_type => {
                    let before_own = strip_children_content(&bp.content, bp.start_line, b_children);
                    let after_own = strip_children_content(&ap.content, ap.start_line, a_children);
                    before_own == after_own
                }
                _ => false,
            }
        } else {
            true
        };

        if should_suppress {
            suppress.insert(change.entity_id.clone());
        }
    }

    // Suppress an old parent that a Moved child left behind when the old
    // parent itself appears as a change — handles the parent-rename case
    // where the parent itself failed to match.
    for change in changes.iter() {
        if change.change_type == ChangeType::Moved {
            if let Some(ref old_pid) = change.old_parent_id {
                if changed_ids.contains(old_pid.as_str()) {
                    suppress.insert(old_pid.clone());
                }
            }
        }
    }

    if !suppress.is_empty() {
        changes.retain(|c| !suppress.contains(&c.entity_id));
    }

    // Drop a Moved child whose key is unchanged and whose old parent matches
    // a Renamed entity — the child only "moved" because the parent renamed.
    let renamed_before_ids: HashSet<&str> = changes
        .iter()
        .filter(|c| c.change_type == ChangeType::Renamed)
        .filter_map(|c| {
            let old_name = c.old_entity_name.as_deref()?;
            let after_entity = after_by_id.get(c.entity_id.as_str())?;
            before
                .iter()
                .find(|e| {
                    e.name == old_name
                        && e.entity_type == after_entity.entity_type
                        && e.parent_id == after_entity.parent_id
                })
                .map(|e| e.id.as_str())
        })
        .collect();

    if !renamed_before_ids.is_empty() {
        changes.retain(|c| {
            !(c.change_type == ChangeType::Moved
                && c.old_entity_name.is_none()
                && c.old_parent_id
                    .as_deref()
                    .map_or(false, |pid| renamed_before_ids.contains(pid)))
        });
    }
}

fn strip_children_content(
    content: &str,
    parent_start_line: usize,
    children: &[&SemanticEntity],
) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let mut excluded: HashSet<usize> = HashSet::new();
    for child in children {
        let start_idx = child.start_line.saturating_sub(parent_start_line);
        let end_idx = child.end_line.saturating_sub(parent_start_line);
        for i in start_idx..=end_idx.max(start_idx) {
            if i < lines.len() {
                excluded.insert(i);
            }
        }
    }
    lines
        .iter()
        .enumerate()
        .filter(|(i, _)| !excluded.contains(i))
        .map(|(_, l)| l.trim())
        .filter(|l| !l.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Detect changes in lines that fall outside any entity span.
/// These are things like use statements, crate-level attributes, standalone
/// comments, and macro invocations that aren't tracked as entities.
fn detect_orphan_changes(
    file: &FileChange,
    before_entities: &[SemanticEntity],
    after_entities: &[SemanticEntity],
    commit_sha: Option<&str>,
    author: Option<&str>,
) -> Vec<SemanticChange> {
    let before_text = file.before_content.as_deref().unwrap_or("");
    let after_text = file.after_content.as_deref().unwrap_or("");

    // Build covered line sets from entity spans
    let before_covered: HashSet<usize> = before_entities
        .iter()
        .flat_map(|e| e.start_line..=e.end_line)
        .collect();
    let after_covered: HashSet<usize> = after_entities
        .iter()
        .flat_map(|e| e.start_line..=e.end_line)
        .collect();

    // Extract uncovered lines, preserving line numbers for context
    let before_orphan: String = before_text
        .lines()
        .enumerate()
        .filter(|(i, _)| !before_covered.contains(&(i + 1)))
        .map(|(_, l)| l)
        .collect::<Vec<_>>()
        .join("\n");
    let after_orphan: String = after_text
        .lines()
        .enumerate()
        .filter(|(i, _)| !after_covered.contains(&(i + 1)))
        .map(|(_, l)| l)
        .collect::<Vec<_>>()
        .join("\n");

    // Skip if orphan content is unchanged
    if before_orphan == after_orphan {
        return Vec::new();
    }

    let change_type = if before_orphan.trim().is_empty() {
        ChangeType::Added
    } else if after_orphan.trim().is_empty() {
        ChangeType::Deleted
    } else {
        ChangeType::Modified
    };

    vec![SemanticChange {
        id: format!("{}::orphan", file.file_path),
        entity_id: format!("{}::orphan", file.file_path),
        change_type,
        entity_type: "orphan".to_string(),
        entity_name: "module-level".to_string(),
        entity_line: 0,
        parent_name: None,
        file_path: file.file_path.clone(),
        old_entity_name: None,
        old_file_path: None,
        old_parent_id: None,
        before_content: if before_orphan.is_empty() {
            None
        } else {
            Some(before_orphan)
        },
        after_content: if after_orphan.is_empty() {
            None
        } else {
            Some(after_orphan)
        },
        commit_sha: commit_sha.map(String::from),
        author: author.map(String::from),
        timestamp: None,
        structural_change: Some(true),
    }]
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::git::types::{FileChange, FileStatus};
    use crate::parser::plugins::create_default_registry;

    fn modified_file(path: &str, before: &str, after: &str) -> FileChange {
        FileChange {
            file_path: path.to_string(),
            status: FileStatus::Modified,
            old_file_path: None,
            before_content: Some(before.to_string()),
            after_content: Some(after.to_string()),
        }
    }

    fn renamed_file(old_path: &str, new_path: &str, before: &str, after: &str) -> FileChange {
        FileChange {
            file_path: new_path.to_string(),
            status: FileStatus::Renamed,
            old_file_path: Some(old_path.to_string()),
            before_content: Some(before.to_string()),
            after_content: Some(after.to_string()),
        }
    }

    #[test]
    fn test_parent_suppressed_when_only_child_modified() {
        let before = "class UserService:\n    def get_user(self, user_id):\n        return db.find(user_id)\n";
        let after  = "class UserService:\n    def get_user(self, user_id):\n        return db.find(user_id, include_deleted=False)\n";

        let registry = create_default_registry();
        let result = compute_semantic_diff(
            &[modified_file("svc.py", before, after)],
            &registry,
            None,
            None,
        );

        let names: Vec<&str> = result
            .changes
            .iter()
            .map(|c| c.entity_name.as_str())
            .collect();
        assert!(
            result.changes.iter().any(|c| c.entity_name == "get_user"),
            "expected method get_user in changes, got: {names:?}"
        );
        assert!(
            !result
                .changes
                .iter()
                .any(|c| c.entity_name == "UserService" && c.change_type == ChangeType::Modified),
            "class should be suppressed when only the method body changed, got: {names:?}"
        );
    }

    #[test]
    fn test_parent_not_suppressed_when_own_declaration_changes() {
        let before = "class UserService:\n    def get_user(self, user_id):\n        return db.find(user_id)\n";
        let after  = "class UserService(BaseService):\n    def get_user(self, user_id):\n        return db.find(user_id, include_deleted=False)\n";

        let registry = create_default_registry();
        let result = compute_semantic_diff(
            &[modified_file("svc.py", before, after)],
            &registry,
            None,
            None,
        );

        let names: Vec<&str> = result
            .changes
            .iter()
            .map(|c| c.entity_name.as_str())
            .collect();
        assert!(
            result.changes.iter().any(|c| c.entity_name == "get_user"),
            "expected method get_user in changes, got: {names:?}"
        );
        assert!(
            result
                .changes
                .iter()
                .any(|c| c.entity_name == "UserService" && c.change_type == ChangeType::Modified),
            "class should remain Modified when its own declaration changed, got: {names:?}"
        );
    }

    #[test]
    fn renamed_file_with_edited_entity_reports_move_not_add_delete() {
        let before = "def foo():\n    return alpha + beta + gamma\n";
        let after = "def foo():\n    return one + two + three\n";

        let registry = create_default_registry();
        let result = compute_semantic_diff(
            &[renamed_file("old.py", "new.py", before, after)],
            &registry,
            None,
            None,
        );

        assert_eq!(result.added_count, 0);
        assert_eq!(result.deleted_count, 0);
        assert_eq!(result.moved_count, 1);
        assert_eq!(result.changes.len(), 1);
        assert_eq!(result.changes[0].entity_name, "foo");
        assert_eq!(result.changes[0].old_file_path.as_deref(), Some("old.py"));
    }
}