semver-analyzer-core 0.0.4

Core types, traits, and diff engine for the semver-analyzer
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
//! Individual comparison functions for the diff engine.
//!
//! Each function compares a specific aspect of two matched symbols
//! (visibility, modifiers, hierarchy, signatures, members) and emits
//! `StructuralChange` entries for detected differences.

use crate::traits::LanguageSemantics;
use crate::types::{
    ChangeSubject, Parameter, Signature, StructuralChange, StructuralChangeType, Symbol, SymbolKind,
};
use std::collections::HashMap;

use super::helpers::{change, kind_label, param_summary, symbol_summary, type_param_summary};
use super::rename::detect_renames;

// ─── Symbol-level diff ───────────────────────────────────────────────────

/// Compare all aspects of two matched symbols and emit changes.
///
/// This is the central dispatch for symbol-level comparison. It calls
/// individual comparison functions for each aspect. Note the mutual
/// recursion with `diff_members` (which calls back into `diff_symbol`
/// for matched member pairs).
pub(super) fn diff_symbol<M, S>(
    old: &Symbol<M>,
    new: &Symbol<M>,
    changes: &mut Vec<StructuralChange>,
    semantics: &S,
) where
    M: Default + Clone + PartialEq,
    S: LanguageSemantics<M>,
{
    diff_visibility(old, new, changes, semantics);
    diff_modifiers(old, new, changes);
    diff_hierarchy(old, new, changes);
    diff_signatures(old, new, changes, semantics);
    diff_members(old, new, changes, semantics);
}

// ─── Visibility diff ─────────────────────────────────────────────────────

fn diff_visibility<M, S>(
    old: &Symbol<M>,
    new: &Symbol<M>,
    changes: &mut Vec<StructuralChange>,
    semantics: &S,
) where
    M: Default + Clone + PartialEq,
    S: LanguageSemantics<M>,
{
    if old.visibility == new.visibility {
        return;
    }

    let old_rank = semantics.visibility_rank(old.visibility);
    let new_rank = semantics.visibility_rank(new.visibility);

    if new_rank < old_rank {
        changes.push(change(
            old,
            StructuralChangeType::Changed(ChangeSubject::Visibility),
            Some(format!("{:?}", old.visibility)),
            Some(format!("{:?}", new.visibility)),
            format!(
                "Visibility of `{}` was reduced from {:?} to {:?}",
                old.name, old.visibility, new.visibility
            ),
            true,
        ));
    } else {
        changes.push(change(
            old,
            StructuralChangeType::Changed(ChangeSubject::Visibility),
            Some(format!("{:?}", old.visibility)),
            Some(format!("{:?}", new.visibility)),
            format!(
                "Visibility of `{}` was increased from {:?} to {:?}",
                old.name, old.visibility, new.visibility
            ),
            false,
        ));
    }
}

// ─── Modifier diff ───────────────────────────────────────────────────────

fn diff_modifiers<M: Default + Clone + PartialEq>(
    old: &Symbol<M>,
    new: &Symbol<M>,
    changes: &mut Vec<StructuralChange>,
) {
    // readonly
    if !old.is_readonly && new.is_readonly {
        changes.push(change(
            old,
            StructuralChangeType::Added(ChangeSubject::Modifier {
                modifier: "readonly".into(),
            }),
            Some("mutable".into()),
            Some("readonly".into()),
            format!("`{}` was made readonly", old.name),
            true,
        ));
    } else if old.is_readonly && !new.is_readonly {
        changes.push(change(
            old,
            StructuralChangeType::Removed(ChangeSubject::Modifier {
                modifier: "readonly".into(),
            }),
            Some("readonly".into()),
            Some("mutable".into()),
            format!("`{}` is no longer readonly", old.name),
            false,
        ));
    }

    // abstract
    if !old.is_abstract && new.is_abstract {
        changes.push(change(
            old,
            StructuralChangeType::Added(ChangeSubject::Modifier {
                modifier: "abstract".into(),
            }),
            Some("concrete".into()),
            Some("abstract".into()),
            format!("`{}` was made abstract", old.name),
            true,
        ));
    } else if old.is_abstract && !new.is_abstract {
        changes.push(change(
            old,
            StructuralChangeType::Removed(ChangeSubject::Modifier {
                modifier: "abstract".into(),
            }),
            Some("abstract".into()),
            Some("concrete".into()),
            format!("`{}` is no longer abstract", old.name),
            false,
        ));
    }

    // static <-> instance
    if old.is_static != new.is_static {
        let (before, after) = if old.is_static {
            ("static", "instance")
        } else {
            ("instance", "static")
        };
        changes.push(change(
            old,
            StructuralChangeType::Changed(ChangeSubject::Modifier {
                modifier: "static".into(),
            }),
            Some(before.into()),
            Some(after.into()),
            format!("`{}` changed from {} to {} member", old.name, before, after),
            true,
        ));
    }

    // accessor kind changes
    if old.accessor_kind != new.accessor_kind {
        changes.push(change(
            old,
            StructuralChangeType::Changed(ChangeSubject::Modifier {
                modifier: "accessor".into(),
            }),
            Some(format!("{:?}", old.accessor_kind)),
            Some(format!("{:?}", new.accessor_kind)),
            format!(
                "`{}` accessor changed from {:?} to {:?}",
                old.name, old.accessor_kind, new.accessor_kind
            ),
            true,
        ));
    }
}

// ─── Class hierarchy diff ────────────────────────────────────────────────

fn diff_hierarchy<M: Default + Clone + PartialEq>(
    old: &Symbol<M>,
    new: &Symbol<M>,
    changes: &mut Vec<StructuralChange>,
) {
    // extends (base class)
    if old.extends != new.extends {
        changes.push(change(
            old,
            StructuralChangeType::Changed(ChangeSubject::BaseClass),
            old.extends.clone(),
            new.extends.clone(),
            format!(
                "`{}` base class changed from {} to {}",
                old.name,
                old.extends.as_deref().unwrap_or("none"),
                new.extends.as_deref().unwrap_or("none")
            ),
            true,
        ));
    }

    // implements (interfaces) — detect added and removed
    let old_impls: std::collections::HashSet<&str> =
        old.implements.iter().map(|s| s.as_str()).collect();
    let new_impls: std::collections::HashSet<&str> =
        new.implements.iter().map(|s| s.as_str()).collect();

    for added in new_impls.difference(&old_impls) {
        changes.push(change(
            old,
            StructuralChangeType::Added(ChangeSubject::InterfaceImpl {
                interface_name: added.to_string(),
            }),
            None,
            Some(added.to_string()),
            format!("`{}` now implements `{}`", old.name, added),
            false,
        ));
    }

    for removed in old_impls.difference(&new_impls) {
        changes.push(change(
            old,
            StructuralChangeType::Removed(ChangeSubject::InterfaceImpl {
                interface_name: removed.to_string(),
            }),
            Some(removed.to_string()),
            None,
            format!("`{}` no longer implements `{}`", old.name, removed),
            true,
        ));
    }
}

// ─── Signature diff ──────────────────────────────────────────────────────

fn diff_signatures<M, S>(
    old: &Symbol<M>,
    new: &Symbol<M>,
    changes: &mut Vec<StructuralChange>,
    semantics: &S,
) where
    M: Default + Clone + PartialEq,
    S: LanguageSemantics<M>,
{
    match (&old.signature, &new.signature) {
        (Some(old_sig), Some(new_sig)) => {
            diff_parameters(old, old_sig, new_sig, changes, semantics);
            diff_return_type(old, old_sig, new_sig, changes, semantics);
            diff_type_parameters(old, old_sig, new_sig, changes);
        }
        (Some(_), None) => {
            // Signature was removed — symbol changed kind (e.g., function → variable)
            changes.push(change(
                old,
                StructuralChangeType::Changed(ChangeSubject::ReturnType),
                Some("(has signature)".into()),
                Some("(no signature)".into()),
                format!("`{}` no longer has a callable signature", old.name),
                true,
            ));
        }
        (None, Some(_)) => {
            // Signature was added — symbol became callable
            // This is informational, not necessarily breaking
        }
        (None, None) => {
            // Neither has a signature — compare return_type if stored in signature
        }
    }
}

// ─── Parameter diff ──────────────────────────────────────────────────────

fn diff_parameters<M, S>(
    sym: &Symbol<M>,
    old_sig: &Signature,
    new_sig: &Signature,
    changes: &mut Vec<StructuralChange>,
    semantics: &S,
) where
    M: Default + Clone + PartialEq,
    S: LanguageSemantics<M>,
{
    let old_params = &old_sig.parameters;
    let new_params = &new_sig.parameters;

    let old_non_rest: Vec<&Parameter> = old_params.iter().filter(|p| !p.is_variadic).collect();
    let new_non_rest: Vec<&Parameter> = new_params.iter().filter(|p| !p.is_variadic).collect();
    let old_rest = old_params.iter().find(|p| p.is_variadic);
    let new_rest = new_params.iter().find(|p| p.is_variadic);

    // Compare matched parameters (by position)
    let common_len = old_non_rest.len().min(new_non_rest.len());
    for i in 0..common_len {
        let old_p = old_non_rest[i];
        let new_p = new_non_rest[i];

        // Type change
        if old_p.type_annotation != new_p.type_annotation {
            changes.push(change(
                sym,
                StructuralChangeType::Changed(ChangeSubject::Parameter {
                    name: old_p.name.clone(),
                }),
                old_p.type_annotation.clone(),
                new_p.type_annotation.clone(),
                format!(
                    "Parameter `{}` of `{}` changed type from `{}` to `{}`",
                    old_p.name,
                    sym.name,
                    old_p.type_annotation.as_deref().unwrap_or("untyped"),
                    new_p.type_annotation.as_deref().unwrap_or("untyped")
                ),
                true,
            ));

            // Also emit per-value union literal changes
            if let (Some(old_ta), Some(new_ta)) = (&old_p.type_annotation, &new_p.type_annotation) {
                diff_union_literals(sym, &old_p.name, old_ta, new_ta, changes, semantics);
            }
        }

        // Optionality change
        if old_p.optional && !new_p.optional {
            changes.push(change(
                sym,
                StructuralChangeType::Changed(ChangeSubject::Parameter {
                    name: old_p.name.clone(),
                }),
                Some("optional".into()),
                Some("required".into()),
                format!(
                    "Parameter `{}` of `{}` was made required",
                    old_p.name, sym.name
                ),
                true,
            ));
        } else if !old_p.optional && new_p.optional {
            changes.push(change(
                sym,
                StructuralChangeType::Changed(ChangeSubject::Parameter {
                    name: old_p.name.clone(),
                }),
                Some("required".into()),
                Some("optional".into()),
                format!(
                    "Parameter `{}` of `{}` was made optional",
                    old_p.name, sym.name
                ),
                false,
            ));
        }

        // Default value change
        if old_p.default_value != new_p.default_value && old_p.has_default && new_p.has_default {
            changes.push(change(
                sym,
                StructuralChangeType::Changed(ChangeSubject::Parameter {
                    name: old_p.name.clone(),
                }),
                old_p.default_value.clone(),
                new_p.default_value.clone(),
                format!(
                    "Default value of parameter `{}` in `{}` changed",
                    old_p.name, sym.name
                ),
                true,
            ));
        }
    }

    // Parameters removed (old has more non-rest params than new)
    for p in old_non_rest.iter().skip(common_len) {
        changes.push(change(
            sym,
            StructuralChangeType::Removed(ChangeSubject::Parameter {
                name: p.name.clone(),
            }),
            Some(param_summary(p)),
            None,
            format!("Parameter `{}` was removed from `{}`", p.name, sym.name),
            true,
        ));
    }

    // Parameters added (new has more non-rest params than old)
    for p in new_non_rest.iter().skip(common_len) {
        let is_breaking = !p.optional && !p.has_default;
        changes.push(change(
            sym,
            StructuralChangeType::Added(ChangeSubject::Parameter {
                name: p.name.clone(),
            }),
            None,
            Some(param_summary(p)),
            format!(
                "{} parameter `{}` was added to `{}`",
                if is_breaking { "Required" } else { "Optional" },
                p.name,
                sym.name
            ),
            is_breaking,
        ));
    }

    // Rest parameter changes
    match (old_rest, new_rest) {
        (Some(old_r), Some(new_r)) => {
            if old_r.type_annotation != new_r.type_annotation {
                changes.push(change(
                    sym,
                    StructuralChangeType::Changed(ChangeSubject::Parameter {
                        name: old_r.name.clone(),
                    }),
                    old_r.type_annotation.clone(),
                    new_r.type_annotation.clone(),
                    format!(
                        "Rest parameter `{}` of `{}` changed type",
                        old_r.name, sym.name
                    ),
                    true,
                ));
            }
        }
        (None, Some(new_r)) => {
            changes.push(change(
                sym,
                StructuralChangeType::Added(ChangeSubject::Parameter {
                    name: new_r.name.clone(),
                }),
                None,
                Some(param_summary(new_r)),
                format!(
                    "Rest parameter `{}` was added to `{}`",
                    new_r.name, sym.name
                ),
                false,
            ));
        }
        (Some(old_r), None) => {
            changes.push(change(
                sym,
                StructuralChangeType::Removed(ChangeSubject::Parameter {
                    name: old_r.name.clone(),
                }),
                Some(param_summary(old_r)),
                None,
                format!(
                    "Rest parameter `{}` was removed from `{}`",
                    old_r.name, sym.name
                ),
                true,
            ));
        }
        (None, None) => {}
    }
}

// ─── Return type diff ────────────────────────────────────────────────────

fn diff_return_type<M, S>(
    sym: &Symbol<M>,
    old_sig: &Signature,
    new_sig: &Signature,
    changes: &mut Vec<StructuralChange>,
    semantics: &S,
) where
    M: Default + Clone + PartialEq,
    S: LanguageSemantics<M>,
{
    if old_sig.return_type == new_sig.return_type {
        return;
    }

    let old_ret = old_sig.return_type.as_deref().unwrap_or("void");
    let new_ret = new_sig.return_type.as_deref().unwrap_or("void");

    let old_is_async = semantics.is_async_wrapper(old_ret);
    let new_is_async = semantics.is_async_wrapper(new_ret);

    if !old_is_async && new_is_async {
        changes.push(change(
            sym,
            StructuralChangeType::Changed(ChangeSubject::ReturnType),
            old_sig.return_type.clone(),
            new_sig.return_type.clone(),
            format!(
                "`{}` was made async (return type wrapped in async wrapper)",
                sym.name
            ),
            true,
        ));
    } else if old_is_async && !new_is_async {
        changes.push(change(
            sym,
            StructuralChangeType::Changed(ChangeSubject::ReturnType),
            old_sig.return_type.clone(),
            new_sig.return_type.clone(),
            format!("`{}` was made sync (async wrapper removed)", sym.name),
            true,
        ));
    } else {
        changes.push(change(
            sym,
            StructuralChangeType::Changed(ChangeSubject::ReturnType),
            old_sig.return_type.clone(),
            new_sig.return_type.clone(),
            format!(
                "Return type of `{}` changed from `{}` to `{}`",
                sym.name, old_ret, new_ret
            ),
            true,
        ));

        // Also emit per-value union literal changes if both types are string literal unions
        diff_union_literals(sym, &sym.name, old_ret, new_ret, changes, semantics);
    }
}

// ─── Type parameter diff ─────────────────────────────────────────────────

fn diff_type_parameters<M: Default + Clone + PartialEq>(
    sym: &Symbol<M>,
    old_sig: &Signature,
    new_sig: &Signature,
    changes: &mut Vec<StructuralChange>,
) {
    let old_tps = &old_sig.type_parameters;
    let new_tps = &new_sig.type_parameters;

    if old_tps.is_empty() && new_tps.is_empty() {
        return;
    }

    let common_len = old_tps.len().min(new_tps.len());

    // Check for reordering (names at same positions differ)
    for i in 0..common_len {
        let old_tp = &old_tps[i];
        let new_tp = &new_tps[i];

        if old_tp.name != new_tp.name {
            let old_names: Vec<&str> = old_tps.iter().map(|t| t.name.as_str()).collect();
            let new_names: Vec<&str> = new_tps.iter().map(|t| t.name.as_str()).collect();

            let mut old_sorted = old_names.clone();
            let mut new_sorted = new_names.clone();
            old_sorted.sort();
            new_sorted.sort();

            if old_sorted == new_sorted && old_names != new_names {
                changes.push(change(
                    sym,
                    StructuralChangeType::Changed(ChangeSubject::TypeParameter {
                        name: old_tp.name.clone(),
                    }),
                    Some(format!("<{}>", old_names.join(", "))),
                    Some(format!("<{}>", new_names.join(", "))),
                    format!("Type parameters of `{}` were reordered", sym.name),
                    true,
                ));
                return;
            }
        }

        // Constraint change
        if old_tp.constraint != new_tp.constraint {
            changes.push(change(
                sym,
                StructuralChangeType::Changed(ChangeSubject::TypeParameter {
                    name: old_tp.name.clone(),
                }),
                old_tp.constraint.clone(),
                new_tp.constraint.clone(),
                format!(
                    "Constraint on type parameter `{}` of `{}` changed from `{}` to `{}`",
                    old_tp.name,
                    sym.name,
                    old_tp.constraint.as_deref().unwrap_or("unconstrained"),
                    new_tp.constraint.as_deref().unwrap_or("unconstrained")
                ),
                true,
            ));
        }

        // Default change
        if old_tp.default != new_tp.default {
            changes.push(change(
                sym,
                StructuralChangeType::Changed(ChangeSubject::TypeParameter {
                    name: old_tp.name.clone(),
                }),
                old_tp.default.clone(),
                new_tp.default.clone(),
                format!(
                    "Default for type parameter `{}` of `{}` changed",
                    old_tp.name, sym.name
                ),
                true,
            ));
        }
    }

    // Type parameters removed
    for tp in old_tps.iter().skip(common_len) {
        changes.push(change(
            sym,
            StructuralChangeType::Removed(ChangeSubject::TypeParameter {
                name: tp.name.clone(),
            }),
            Some(type_param_summary(tp)),
            None,
            format!(
                "Type parameter `{}` was removed from `{}`",
                tp.name, sym.name
            ),
            true,
        ));
    }

    // Type parameters added
    for tp in new_tps.iter().skip(common_len) {
        let is_breaking = tp.default.is_none();
        changes.push(change(
            sym,
            StructuralChangeType::Added(ChangeSubject::TypeParameter {
                name: tp.name.clone(),
            }),
            None,
            Some(type_param_summary(tp)),
            format!(
                "{} type parameter `{}` was added to `{}`",
                if is_breaking {
                    "Required"
                } else {
                    "Optional (has default)"
                },
                tp.name,
                sym.name
            ),
            is_breaking,
        ));
    }
}

// ─── Member diff (classes, interfaces, enums) ────────────────────────────

/// Compare members of two matched symbols (class/interface/enum).
///
/// This function is mutually recursive with `diff_symbol` — matched members
/// are compared by calling `diff_symbol` again. This is why both functions
/// live in the same module visibility scope.
pub(super) fn diff_members<M, S>(
    old: &Symbol<M>,
    new: &Symbol<M>,
    changes: &mut Vec<StructuralChange>,
    semantics: &S,
) where
    M: Default + Clone + PartialEq,
    S: LanguageSemantics<M>,
{
    if old.members.is_empty() && new.members.is_empty() {
        return;
    }

    let old_map: HashMap<&str, &Symbol<M>> =
        old.members.iter().map(|m| (m.name.as_str(), m)).collect();
    let new_map: HashMap<&str, &Symbol<M>> =
        new.members.iter().map(|m| (m.name.as_str(), m)).collect();

    // Collect removed and added members
    let removed: Vec<&Symbol<M>> = old
        .members
        .iter()
        .filter(|m| !new_map.contains_key(m.name.as_str()))
        .collect();
    let added: Vec<&Symbol<M>> = new
        .members
        .iter()
        .filter(|m| !old_map.contains_key(m.name.as_str()))
        .collect();

    // Detect renames (skip for enums — enum member renames are rare and
    // would be confusing since values matter more than names).
    // Member-level renames are within the same parent interface, so
    // cross-family distinction is not meaningful — always same-family.
    let renames = if old.kind != SymbolKind::Enum {
        detect_renames(
            &removed,
            &added,
            |_, _| true,
            semantics.primitive_type_names(),
        )
    } else {
        Vec::new()
    };

    // Separate type-compatible from type-incompatible member renames.
    // Compatible renames (same type category) → StructuralChangeType::Renamed
    //   (mechanical codemod).
    // Incompatible renames (e.g., splitButtonOptions: SplitButtonOptions →
    //   splitButtonItems: ReactNode[]) → StructuralChangeType::Changed
    //   (signature change, routed to LLM-assisted fixing).
    let mut compatible_renames = Vec::new();
    let mut incompatible_renames = Vec::new();
    for rm in &renames {
        let old_rt = rm
            .old
            .signature
            .as_ref()
            .and_then(|s| s.return_type.as_deref());
        let new_rt = rm
            .new
            .signature
            .as_ref()
            .and_then(|s| s.return_type.as_deref());
        let types_match = match (old_rt, new_rt) {
            (Some(o), Some(n)) => {
                types_structurally_similar(o, n, semantics.primitive_type_names())
            }
            _ => true,
        };
        if types_match {
            compatible_renames.push(rm);
        } else {
            tracing::info!(
                parent = %old.name,
                old = %rm.old.name,
                new = %rm.new.name,
                old_type = old_rt.unwrap_or("?"),
                new_type = new_rt.unwrap_or("?"),
                "Type-incompatible member rename — emitting as signature change"
            );
            incompatible_renames.push(rm);
        }
    }

    // Build renamed sets from BOTH compatible and incompatible renames so
    // neither old nor new member appears as a separate Removed/Added entry.
    let renamed_old: std::collections::HashSet<&str> = compatible_renames
        .iter()
        .chain(incompatible_renames.iter())
        .map(|r| r.old.name.as_str())
        .collect();
    let renamed_new: std::collections::HashSet<&str> = compatible_renames
        .iter()
        .chain(incompatible_renames.iter())
        .map(|r| r.new.name.as_str())
        .collect();

    // Emit rename changes (type-compatible only)
    for rm in &compatible_renames {
        changes.push(StructuralChange {
            symbol: rm.old.name.clone(),
            qualified_name: format!("{}.{}", old.qualified_name, rm.old.name),
            kind: rm.old.kind,
            package: rm.old.package.clone(),
            change_type: StructuralChangeType::Renamed {
                from: ChangeSubject::Member {
                    name: rm.old.name.clone(),
                    kind: rm.old.kind,
                },
                to: ChangeSubject::Member {
                    name: rm.new.name.clone(),
                    kind: rm.new.kind,
                },
            },
            before: Some(rm.old.name.clone()),
            after: Some(rm.new.name.clone()),
            description: format!(
                "{} `{}` was renamed to `{}` in `{}`",
                kind_label(rm.old.kind),
                rm.old.name,
                rm.new.name,
                old.name
            ),
            is_breaking: true,
            impact: None,
            migration_target: None,
        });
    }

    // Emit type-incompatible renames as Changed (signature change).
    // These carry both old and new signatures so the rule generator can
    // produce a single LLM-assisted migration rule with full context,
    // instead of a disconnected Removed + Added pair.
    for rm in &incompatible_renames {
        changes.push(StructuralChange {
            symbol: rm.old.name.clone(),
            qualified_name: format!("{}.{}", old.qualified_name, rm.old.name),
            kind: rm.old.kind,
            package: rm.old.package.clone(),
            change_type: StructuralChangeType::Changed(ChangeSubject::Member {
                name: rm.old.name.clone(),
                kind: rm.old.kind,
            }),
            before: Some(symbol_summary(rm.old)),
            after: Some(symbol_summary(rm.new)),
            description: format!(
                "property `{}` was replaced by `{}` in `{}` with a different type",
                rm.old.name, rm.new.name, old.name
            ),
            is_breaking: true,
            impact: None,
            migration_target: None,
        });
    }

    // Removed members (not part of a rename)
    for member in &removed {
        if renamed_old.contains(member.name.as_str()) {
            continue;
        }
        let (change_type, description, is_breaking) = match old.kind {
            SymbolKind::Enum => (
                StructuralChangeType::Removed(ChangeSubject::Member {
                    name: member.name.clone(),
                    kind: SymbolKind::EnumMember,
                }),
                format!(
                    "Enum member `{}` was removed from `{}`",
                    member.name, old.name
                ),
                true,
            ),
            _ => (
                StructuralChangeType::Removed(ChangeSubject::Member {
                    name: member.name.clone(),
                    kind: member.kind,
                }),
                format!(
                    "{} `{}` was removed from `{}`",
                    kind_label(member.kind),
                    member.name,
                    old.name
                ),
                true,
            ),
        };
        changes.push(change(
            member,
            change_type,
            Some(symbol_summary(member)),
            None,
            description,
            is_breaking,
        ));
    }

    // Added members (not part of a rename)
    for member in &added {
        if renamed_new.contains(member.name.as_str()) {
            continue;
        }
        let is_breaking = semantics.is_member_addition_breaking(new, member);
        let (change_type, description) = match new.kind {
            SymbolKind::Enum => (
                StructuralChangeType::Added(ChangeSubject::Member {
                    name: member.name.clone(),
                    kind: SymbolKind::EnumMember,
                }),
                format!("Enum member `{}` was added to `{}`", member.name, new.name),
            ),
            _ => (
                StructuralChangeType::Added(ChangeSubject::Member {
                    name: member.name.clone(),
                    kind: member.kind,
                }),
                format!(
                    "{} `{}` was added to `{}`",
                    kind_label(member.kind),
                    member.name,
                    new.name
                ),
            ),
        };
        changes.push(change(
            member,
            change_type,
            None,
            Some(symbol_summary(member)),
            description,
            is_breaking,
        ));
    }

    // Matched members — diff recursively
    for old_member in &old.members {
        if let Some(new_member) = new_map.get(old_member.name.as_str()) {
            if old.kind == SymbolKind::Enum {
                diff_enum_member_value(old, old_member, new_member, changes);
            } else {
                diff_symbol(old_member, new_member, changes, semantics);
            }
        }
    }
}

// ─── Union literal value diffing ─────────────────────────────────────────

/// Emit per-member union literal value changes.
///
/// When a property's type changes from `'a' | 'b' | 'c'` to `'a' | 'd'`,
/// emits:
///   - `UnionMemberRemoved` for `'b'` and `'c'`
///   - `UnionMemberAdded` for `'d'`
///
/// The parent symbol provides context (e.g., `Button.variant`).
fn diff_union_literals<M, S>(
    sym: &Symbol<M>,
    prop_name: &str,
    old_type: &str,
    new_type: &str,
    changes: &mut Vec<StructuralChange>,
    semantics: &S,
) where
    M: Default + Clone + PartialEq,
    S: LanguageSemantics<M>,
{
    let old_literals = match semantics.parse_union_values(old_type) {
        Some(l) => l,
        None => return,
    };
    let new_literals = match semantics.parse_union_values(new_type) {
        Some(l) => l,
        None => return,
    };

    // Skip if identical
    if old_literals == new_literals {
        return;
    }

    // Removed values (breaking)
    for removed in old_literals.difference(&new_literals) {
        changes.push(StructuralChange {
            symbol: format!("{}.{}", sym.name, prop_name),
            qualified_name: format!("{}.{}", sym.qualified_name, prop_name),
            kind: SymbolKind::Property,
            package: sym.package.clone(),
            change_type: StructuralChangeType::Removed(ChangeSubject::UnionValue {
                value: removed.clone(),
            }),
            before: Some(format!("'{}'", removed)),
            after: None,
            description: format!(
                "Value '{}' was removed from the `{}` prop on `{}`",
                removed, prop_name, sym.name
            ),
            is_breaking: true,
            impact: None,
            migration_target: None,
        });
    }

    // Added values (non-breaking, but useful for migration)
    for added in new_literals.difference(&old_literals) {
        changes.push(StructuralChange {
            symbol: format!("{}.{}", sym.name, prop_name),
            qualified_name: format!("{}.{}", sym.qualified_name, prop_name),
            kind: SymbolKind::Property,
            package: sym.package.clone(),
            change_type: StructuralChangeType::Added(ChangeSubject::UnionValue {
                value: added.clone(),
            }),
            before: None,
            after: Some(format!("'{}'", added)),
            description: format!(
                "Value '{}' was added to the `{}` prop on `{}`",
                added, prop_name, sym.name
            ),
            is_breaking: false,
            impact: None,
            migration_target: None,
        });
    }
}

fn diff_enum_member_value<M: Default + Clone + PartialEq>(
    parent: &Symbol<M>,
    old_member: &Symbol<M>,
    new_member: &Symbol<M>,
    changes: &mut Vec<StructuralChange>,
) {
    let old_val = old_member
        .signature
        .as_ref()
        .and_then(|s| s.return_type.as_deref());
    let new_val = new_member
        .signature
        .as_ref()
        .and_then(|s| s.return_type.as_deref());

    if old_val != new_val {
        changes.push(change(
            old_member,
            StructuralChangeType::Changed(ChangeSubject::Member {
                name: old_member.name.clone(),
                kind: SymbolKind::EnumMember,
            }),
            old_val.map(|s| s.to_string()),
            new_val.map(|s| s.to_string()),
            format!(
                "Value of enum member `{}.{}` changed from `{}` to `{}`",
                parent.name,
                old_member.name,
                old_val.unwrap_or("undefined"),
                new_val.unwrap_or("undefined")
            ),
            true,
        ));
    }
}

/// Check if two type strings have the same structural shape.
///
/// This is a coarse check that distinguishes fundamentally different types
/// (object vs array, type-reference vs primitive) while treating types with
/// the same shape but different values/members as similar.
///
/// Check if two type strings have the same structural shape, using the
/// provided list of primitive type names for classification.
///
/// The `primitives` slice comes from `LanguageSemantics::primitive_type_names()`.
///
/// Examples:
/// - `SplitButtonOptions` vs `ReactNode[]` → false (reference vs array)
/// - `{ default?: 'spacerNone' | ... }` vs `{ default?: 'gapNone' | ... }` → true (both objects)
/// - `boolean` vs `string` → true (both primitives — rename is valid)
/// - `(e: Event) => void` vs `string` → false (function vs primitive)
pub(crate) fn types_structurally_similar(old: &str, new: &str, primitives: &[&str]) -> bool {
    let old_cat = type_category(old, primitives);
    let new_cat = type_category(new, primitives);
    old_cat == new_cat
}

#[derive(Debug, PartialEq)]
enum TypeCategory {
    Array,
    Object,
    Function,
    Tuple,
    Primitive,
    Reference,
}

fn type_category(t: &str, primitives: &[&str]) -> TypeCategory {
    let trimmed = t.trim();

    // Array: ends with [] or is Array<...>
    if trimmed.ends_with("[]") || trimmed.starts_with("Array<") {
        return TypeCategory::Array;
    }

    // Object: starts with {
    if trimmed.starts_with('{') {
        return TypeCategory::Object;
    }

    // Function: contains =>
    if trimmed.contains("=>") {
        return TypeCategory::Function;
    }

    // Tuple: starts with [
    if trimmed.starts_with('[') {
        return TypeCategory::Tuple;
    }

    // Primitive: check against the language-provided list
    let lower = trimmed.to_lowercase();
    if primitives.iter().any(|p| p.to_lowercase() == lower) {
        return TypeCategory::Primitive;
    }

    // Everything else is a type reference (PascalCase, qualified names, etc.)
    TypeCategory::Reference
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diff::MinimalSemantics;
    use crate::types::{Signature, StructuralChangeType, Visibility};
    use std::path::PathBuf;

    /// Build a Symbol representing a parent interface (e.g., MenuToggleProps)
    /// with the given member properties.
    fn make_interface(name: &str, qualified: &str, members: Vec<Symbol>) -> Symbol {
        Symbol {
            name: name.to_string(),
            qualified_name: qualified.to_string(),
            kind: SymbolKind::Interface,
            visibility: Visibility::Public,
            file: PathBuf::from(
                "packages/react-core/src/components/MenuToggle/MenuToggle.MenuToggleProps.d.ts",
            ),
            package: Some("@patternfly/react-core".to_string()),
            import_path: None,
            line: 1,
            signature: None,
            extends: None,
            implements: vec![],
            is_abstract: false,
            type_dependencies: vec![],
            is_readonly: false,
            is_static: false,
            accessor_kind: None,
            members,
            language_data: Default::default(),
        }
    }

    /// Build a Symbol representing a property member with a type.
    fn make_member(name: &str, parent_qualified: &str, return_type: &str) -> Symbol {
        Symbol {
            name: name.to_string(),
            qualified_name: format!("{}.{}", parent_qualified, name),
            kind: SymbolKind::Property,
            visibility: Visibility::Public,
            file: PathBuf::from(
                "packages/react-core/src/components/MenuToggle/MenuToggle.MenuToggleProps.d.ts",
            ),
            package: Some("@patternfly/react-core".to_string()),
            import_path: None,
            line: 1,
            signature: Some(Signature {
                return_type: Some(return_type.to_string()),
                parameters: vec![],
                is_async: false,
                type_parameters: vec![],
            }),
            extends: None,
            implements: vec![],
            is_abstract: false,
            type_dependencies: vec![],
            is_readonly: false,
            is_static: false,
            accessor_kind: None,
            members: vec![],
            language_data: Default::default(),
        }
    }

    /// Real PatternFly v5→v6 regression test: splitButtonOptions → splitButtonItems.
    ///
    /// In PF v5, MenuToggleProps had `splitButtonOptions: SplitButtonOptions`.
    /// In PF v6, it was replaced by `splitButtonItems: ReactNode[]`.
    /// The name similarity (0.73) is detected by rename Pass 4, but the types
    /// are structurally incompatible (Reference vs Array).
    ///
    /// This MUST produce a single Changed (signature change) entry carrying
    /// both old and new signatures — NOT separate Removed + Added entries,
    /// which would lose the linkage and produce a useless "remove prop, find
    /// alternative" fix strategy.
    #[test]
    fn test_type_incompatible_member_rename_produces_changed_not_removed_plus_added() {
        let parent_qn = "packages/react-core/src/components/MenuToggle/MenuToggle.MenuToggleProps";

        // PF v5 MenuToggleProps with splitButtonOptions: SplitButtonOptions
        // plus a stable member (onClick) that exists in both versions.
        let old = make_interface(
            "MenuToggleProps",
            parent_qn,
            vec![
                make_member("splitButtonOptions", parent_qn, "SplitButtonOptions"),
                make_member("onClick", parent_qn, "(event: MouseEvent) => void"),
            ],
        );

        // PF v6 MenuToggleProps with splitButtonItems: ReactNode[]
        // plus the same stable member.
        let new = make_interface(
            "MenuToggleProps",
            parent_qn,
            vec![
                make_member("splitButtonItems", parent_qn, "ReactNode[]"),
                make_member("onClick", parent_qn, "(event: MouseEvent) => void"),
            ],
        );

        let mut changes = Vec::new();
        diff_members(&old, &new, &mut changes, &MinimalSemantics);

        // There should be exactly one change for the splitButton prop pair.
        // It must be a Changed entry (structural type change), not Removed + Added.
        let split_changes: Vec<_> = changes
            .iter()
            .filter(|c| c.symbol.contains("splitButton") || c.description.contains("splitButton"))
            .collect();

        assert_eq!(
            split_changes.len(),
            1,
            "Type-incompatible rename should produce exactly 1 Changed entry, \
             not separate Removed + Added. Got {} entries: {:?}",
            split_changes.len(),
            split_changes
                .iter()
                .map(|c| format!("{:?}: {}", c.change_type, c.description))
                .collect::<Vec<_>>()
        );

        let sc = split_changes[0];

        // Must be a Changed variant (maps to SignatureChanged downstream)
        assert!(
            matches!(sc.change_type, StructuralChangeType::Changed(..)),
            "Expected Changed(..), got {:?}",
            sc.change_type
        );

        // before must carry the old signature
        assert_eq!(
            sc.before.as_deref(),
            Some("property: splitButtonOptions: SplitButtonOptions"),
            "before should carry old prop signature"
        );

        // after must carry the new signature
        assert_eq!(
            sc.after.as_deref(),
            Some("property: splitButtonItems: ReactNode[]"),
            "after should carry new prop signature"
        );

        // No separate Removed or Added entries for either prop
        let removed_or_added: Vec<_> = changes
            .iter()
            .filter(|c| {
                (c.symbol.contains("splitButton") || c.description.contains("splitButton"))
                    && matches!(
                        c.change_type,
                        StructuralChangeType::Removed(..) | StructuralChangeType::Added(..)
                    )
            })
            .collect();
        assert!(
            removed_or_added.is_empty(),
            "There should be no separate Removed/Added entries for the \
             type-incompatible rename. Found: {:?}",
            removed_or_added
                .iter()
                .map(|c| format!("{:?}: {}", c.change_type, c.description))
                .collect::<Vec<_>>()
        );
    }
}