cuke-dedup 0.5.0

Static analysis for duplicate and reusable Cucumber step definitions
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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
use super::assertions::AssertionBindings;
use super::ast::push_named_children_reverse;
use super::node_text;
use super::registrations::{registration_callee, RegistrationCallee};
use crate::model::{stable_fingerprint, HandlerFingerprint};
use std::borrow::Cow;
use std::collections::BTreeMap;
use tree_sitter::Node;

const MAX_ASSERTION_CHAIN_DEPTH: usize = 16;
const UNRESOLVED_ASSERTION: &str = "assert:unresolved";
const DEFERRED_UNRESOLVED_ASSERTION: &str = "deferred-assert:unresolved";

#[derive(Clone, Copy)]
pub(super) struct HandlerBinding<'tree> {
    declaration: Node<'tree>,
    scope: Node<'tree>,
    start_byte: usize,
    hoisted: bool,
}

pub(super) fn collect_handler_bindings<'tree>(
    node: Node<'tree>,
    source: &[u8],
    output: &mut BTreeMap<String, Vec<HandlerBinding<'tree>>>,
) {
    let mut stack = vec![node];
    while let Some(node) = stack.pop() {
        if matches!(
            node.kind(),
            "function_declaration" | "generator_function_declaration"
        ) {
            if let (Some(name), Some(scope)) = (
                node.child_by_field_name("name"),
                nearest_scope(node.parent()),
            ) {
                output
                    .entry(node_text(name, source).to_owned())
                    .or_default()
                    .push(HandlerBinding {
                        declaration: node,
                        scope,
                        start_byte: node.start_byte(),
                        hoisted: true,
                    });
            }
        } else if node.kind() == "variable_declarator" {
            if let (Some(name), Some(value), Some(scope)) = (
                node.child_by_field_name("name"),
                node.child_by_field_name("value"),
                nearest_scope(node.parent()),
            ) {
                if name.kind() == "identifier"
                    && matches!(
                        value.kind(),
                        "arrow_function" | "function_expression" | "generator_function"
                    )
                {
                    output
                        .entry(node_text(name, source).to_owned())
                        .or_default()
                        .push(HandlerBinding {
                            declaration: value,
                            scope,
                            start_byte: node.start_byte(),
                            hoisted: false,
                        });
                }
            }
        }

        push_named_children_reverse(node, &mut stack);
    }
}

fn nearest_scope(mut node: Option<Node<'_>>) -> Option<Node<'_>> {
    while let Some(current) = node {
        if matches!(current.kind(), "program" | "statement_block") {
            return Some(current);
        }
        node = current.parent();
    }
    None
}

pub(super) fn resolve_handler<'tree>(
    mut handler: Node<'tree>,
    source: &[u8],
    bindings: &BTreeMap<String, Vec<HandlerBinding<'tree>>>,
) -> Option<Node<'tree>> {
    while handler.kind() == "parenthesized_expression" {
        handler = handler.named_child(0)?;
    }
    if matches!(
        handler.kind(),
        "arrow_function" | "function_expression" | "generator_function"
    ) {
        return Some(handler);
    }
    if handler.kind() == "call_expression" {
        let function = handler.child_by_field_name("function")?;
        if function.kind() == "member_expression"
            && function
                .child_by_field_name("property")
                .is_some_and(|property| node_text(property, source) == "bind")
        {
            return resolve_handler(function.child_by_field_name("object")?, source, bindings);
        }
        return None;
    }
    if handler.kind() != "identifier" {
        return None;
    }

    let name = node_text(handler, source);
    let candidates = bindings.get(name)?;
    let mut scopes = Vec::new();
    let mut ancestor = handler.parent();
    while let Some(node) = ancestor {
        if matches!(node.kind(), "program" | "statement_block") {
            scopes.push(node.id());
        }
        ancestor = node.parent();
    }

    candidates
        .iter()
        .filter(|binding| binding.hoisted || binding.start_byte <= handler.start_byte())
        .filter_map(|binding| {
            scopes
                .iter()
                .position(|scope| *scope == binding.scope.id())
                .map(|scope_depth| (scope_depth, binding))
        })
        .min_by(|(left_depth, left), (right_depth, right)| {
            left_depth
                .cmp(right_depth)
                .then_with(|| right.start_byte.cmp(&left.start_byte))
        })
        .map(|(_, binding)| binding.declaration)
}

pub(super) fn bind_arguments<'tree>(handler: Node<'tree>, source: &[u8]) -> Option<Node<'tree>> {
    if handler.kind() != "call_expression" {
        return None;
    }
    let function = handler.child_by_field_name("function")?;
    if function.kind() != "member_expression"
        || function
            .child_by_field_name("property")
            .is_none_or(|property| node_text(property, source) != "bind")
    {
        return None;
    }
    handler.child_by_field_name("arguments")
}

pub(super) fn fingerprint_handler(
    handler: Node<'_>,
    bound_arguments: Option<Node<'_>>,
    source: &[u8],
    comparable: bool,
    assertions: &AssertionBindings,
) -> HandlerFingerprint {
    let declared = declared_identifiers(handler, source);
    fingerprint_node(
        handler,
        bound_arguments,
        source,
        comparable,
        &declared,
        assertions,
    )
}

/// Fingerprints a decorated class method without its name or decorator metadata.
///
/// Parameters and runtime modifiers remain part of the fingerprint: default initializers execute
/// at call time, and `async`/generator/static/accessor methods can behave differently even when
/// their bodies are textually identical.
pub(super) fn fingerprint_method_handler(
    method: Node<'_>,
    source: &[u8],
    assertions: &AssertionBindings,
) -> Option<HandlerFingerprint> {
    debug_assert_eq!(method.kind(), "method_definition");
    let name = method.child_by_field_name("name")?;
    let parameters = method.child_by_field_name("parameters")?;
    let body = method.child_by_field_name("body")?;
    let mut identifiers = Vec::new();
    collect_parameter_bindings(parameters, source, &mut identifiers);
    collect_declared_locals(body, source, &mut identifiers);
    let declared = identifier_map(identifiers);

    // Direct grammar tokens remain stable when comments separate a modifier from the name.
    // TypeScript accessibility and `override` nodes are deliberately ignored because they cannot
    // change execution behavior.
    let mut runtime_modifiers = Vec::new();
    for index in 0..method.child_count() {
        let child = method.child(index)?;
        if child.start_byte() >= name.start_byte() {
            break;
        }
        if !child.is_extra() && matches!(child.kind(), "static" | "async" | "*" | "get" | "set") {
            runtime_modifiers.push(child.kind());
        }
    }
    let modifier = runtime_modifiers.join(" ");
    let semantic_prefix = if modifier.is_empty() {
        "instance sync".to_owned()
    } else {
        modifier
    };

    let raw_parameters = node_text(parameters, source);
    let raw_body = node_text(body, source);
    let exact = format!("{semantic_prefix}\0{raw_parameters}\0{raw_body}");
    let normalized = method_representation(
        &semantic_prefix,
        parameters,
        body,
        source,
        &declared,
        AstMode::Normalized,
    );
    let alpha = method_representation(
        &semantic_prefix,
        parameters,
        body,
        source,
        &declared,
        AstMode::Alpha,
    );
    let structural = method_representation(
        &semantic_prefix,
        parameters,
        body,
        source,
        &declared,
        AstMode::Structural,
    );
    let local_constants = LocalConstants::collect(method, source, &declared);
    // Preserve invocation semantics for compatibility checks. Similarity removes this metadata
    // before measuring executed behavior so two one-assertion methods do not gain artificial
    // 50% overlap merely because both are methods.
    let mut signature = vec![format!("method:{semantic_prefix}")];
    signature.extend(behavior_signature(
        parameters,
        source,
        &declared,
        assertions,
        &local_constants,
    ));
    signature.extend(behavior_signature(
        body,
        source,
        &declared,
        assertions,
        &local_constants,
    ));
    let source_snippet = format!("{semantic_prefix} {raw_parameters} {raw_body}");
    let comparable = !signature.iter().any(|event| is_unresolved_assertion(event));

    Some(HandlerFingerprint {
        exact: stable_fingerprint(&exact),
        normalized: stable_fingerprint(&normalized),
        alpha_normalized: stable_fingerprint(&alpha),
        structural: stable_fingerprint(&structural),
        behavior_signature: signature,
        source_snippet: bounded_source_snippet(&source_snippet),
        comparable,
        // A default initializer executes before the body. Treating an empty method with one as a
        // stub would hide real behavior and could recreate pending-handler finding storms.
        trivial: !has_parameter_initializer(parameters) && is_trivial_handler(body, source),
    })
}

fn method_representation(
    semantic_prefix: &str,
    parameters: Node<'_>,
    body: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    mode: AstMode,
) -> String {
    let parameters = match mode {
        AstMode::Normalized => serialize_ast(parameters, source, declared, mode),
        AstMode::Alpha | AstMode::Structural => {
            serialize_parameter_semantics(parameters, source, declared, mode)
        }
    };
    format!(
        "{semantic_prefix}\0{}\0{}",
        parameters,
        serialize_ast(body, source, declared, mode)
    )
}

fn serialize_parameter_semantics(
    parameters: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    mode: AstMode,
) -> String {
    enum Event<'tree> {
        Visit(Node<'tree>),
        Text(String),
        Close,
    }

    let mut output = String::new();
    let mut stack = vec![Event::Visit(parameters)];
    while let Some(event) = stack.pop() {
        match event {
            Event::Text(text) => output.push_str(&text),
            Event::Close => output.push(')'),
            Event::Visit(node) => match node.kind() {
                "type_annotation" => {}
                "required_parameter" | "optional_parameter" => {
                    let binding = node
                        .child_by_field_name("name")
                        .or_else(|| node.child_by_field_name("pattern"));
                    let initializer = node.child_by_field_name("value");
                    output.push('(');
                    output.push_str(node.kind());
                    stack.push(Event::Close);
                    if let Some(initializer) = initializer {
                        stack.push(Event::Text(serialize_ast(
                            initializer,
                            source,
                            declared,
                            mode,
                        )));
                        stack.push(Event::Text("=".to_owned()));
                    }
                    if let Some(binding) = binding {
                        stack.push(Event::Visit(binding));
                    }
                }
                "identifier" => output.push_str("binding"),
                "shorthand_property_identifier_pattern" => {
                    output.push_str("property:");
                    output.push_str(node_text(node, source));
                    output.push_str("(binding)");
                }
                "pair_pattern" => {
                    let (Some(key), Some(value)) = (
                        node.child_by_field_name("key"),
                        node.child_by_field_name("value"),
                    ) else {
                        continue;
                    };
                    output.push_str("property:");
                    output.push_str(node_text(key, source));
                    output.push('(');
                    stack.push(Event::Close);
                    stack.push(Event::Visit(value));
                }
                "assignment_pattern" | "object_assignment_pattern" => {
                    let left = node
                        .child_by_field_name("left")
                        .or_else(|| node.named_child(0));
                    let right = node
                        .child_by_field_name("right")
                        .or_else(|| node.child_by_field_name("value"))
                        .or_else(|| node.named_child(1));
                    let (Some(left), Some(right)) = (left, right) else {
                        continue;
                    };
                    output.push_str("default(");
                    stack.push(Event::Close);
                    stack.push(Event::Text(serialize_ast(right, source, declared, mode)));
                    stack.push(Event::Text("=".to_owned()));
                    stack.push(Event::Visit(left));
                }
                _ => {
                    let mut cursor = node.walk();
                    let children: Vec<_> = node
                        .named_children(&mut cursor)
                        .filter(|child| child.kind() != "type_annotation")
                        .collect();
                    output.push('(');
                    output.push_str(node.kind());
                    stack.push(Event::Close);
                    for child in children.into_iter().rev() {
                        stack.push(Event::Visit(child));
                    }
                }
            },
        }
    }
    output
}

fn has_parameter_initializer(parameters: Node<'_>) -> bool {
    let mut stack = vec![parameters];
    while let Some(node) = stack.pop() {
        if matches!(
            node.kind(),
            "assignment_pattern" | "object_assignment_pattern"
        ) || matches!(node.kind(), "required_parameter" | "optional_parameter")
            && node.child_by_field_name("value").is_some()
        {
            return true;
        }
        push_named_children_reverse(node, &mut stack);
    }
    false
}

fn collect_parameter_bindings(parameters: Node<'_>, source: &[u8], output: &mut Vec<String>) {
    let mut stack = vec![parameters];
    while let Some(node) = stack.pop() {
        match node.kind() {
            "identifier" | "shorthand_property_identifier_pattern" => {
                push_identifier(output, node_text(node, source));
            }
            // Only the left side introduces a binding; traversing the initializer would alpha-
            // rename external calls such as `first()` and `second()` into a false match.
            "assignment_pattern" | "object_assignment_pattern" => {
                if let Some(left) = node
                    .child_by_field_name("left")
                    .or_else(|| node.named_child(0))
                {
                    stack.push(left);
                }
            }
            "required_parameter" | "optional_parameter" => {
                if let Some(binding) = node
                    .child_by_field_name("name")
                    .or_else(|| node.child_by_field_name("pattern"))
                {
                    stack.push(binding);
                }
            }
            // Object keys are property names. Only the value side binds a local identifier.
            "pair_pattern" => {
                if let Some(value) = node.child_by_field_name("value") {
                    stack.push(value);
                }
            }
            "type_annotation" => {}
            _ => push_named_children_reverse(node, &mut stack),
        }
    }
}

fn fingerprint_node(
    handler: Node<'_>,
    bound_arguments: Option<Node<'_>>,
    source: &[u8],
    comparable: bool,
    declared: &BTreeMap<String, String>,
    assertions: &AssertionBindings,
) -> HandlerFingerprint {
    let raw = node_text(handler, source);
    let mut exact = raw.to_owned();
    let mut normalized = serialize_ast(handler, source, declared, AstMode::Normalized);
    let mut alpha = serialize_ast(handler, source, declared, AstMode::Alpha);
    let mut structural = serialize_ast(handler, source, declared, AstMode::Structural);
    let local_constants = LocalConstants::collect(handler, source, declared);
    let mut signature = behavior_signature(handler, source, declared, assertions, &local_constants);
    let mut source_snippet = raw.to_owned();
    if let Some(arguments) = bound_arguments {
        let no_declarations = BTreeMap::new();
        append_bound_context(&mut exact, node_text(arguments, source));
        append_bound_context(
            &mut normalized,
            &serialize_ast(arguments, source, &no_declarations, AstMode::Normalized),
        );
        append_bound_context(
            &mut alpha,
            &serialize_ast(arguments, source, &no_declarations, AstMode::Alpha),
        );
        append_bound_context(
            &mut structural,
            &serialize_ast(arguments, source, &no_declarations, AstMode::Structural),
        );
        signature.extend(behavior_signature(
            arguments,
            source,
            &no_declarations,
            assertions,
            &LocalConstants::default(),
        ));
        source_snippet.push_str(" bound with ");
        source_snippet.push_str(node_text(arguments, source));
    }
    let comparable = comparable && !signature.iter().any(|event| is_unresolved_assertion(event));
    HandlerFingerprint {
        exact: stable_fingerprint(&exact),
        normalized: stable_fingerprint(&normalized),
        alpha_normalized: stable_fingerprint(&alpha),
        structural: stable_fingerprint(&structural),
        behavior_signature: signature,
        source_snippet: bounded_source_snippet(&source_snippet),
        comparable,
        trivial: comparable && is_trivial_handler(handler, source),
    }
}

fn append_bound_context(target: &mut String, arguments: &str) {
    target.push_str("\0bind");
    target.push_str(arguments);
}

fn is_trivial_handler(handler: Node<'_>, source: &[u8]) -> bool {
    let body = if handler.kind() == "statement_block" {
        handler
    } else {
        if !matches!(
            handler.kind(),
            "arrow_function"
                | "function_expression"
                | "generator_function"
                | "function_declaration"
                | "generator_function_declaration"
        ) {
            return false;
        }
        let Some(body) = handler.child_by_field_name("body") else {
            return false;
        };
        body
    };
    if body.kind() != "statement_block" {
        return is_stub_expression(body, source);
    }
    let mut cursor = body.walk();
    let statements: Vec<_> = body
        .named_children(&mut cursor)
        .filter(|child| child.kind() != "comment")
        .collect();
    match statements.as_slice() {
        [] => true,
        [statement] if statement.kind() == "throw_statement" => statement
            .named_child(0)
            .is_some_and(|expression| contains_explicit_stub_marker(expression, source)),
        [statement] if statement.kind() == "return_statement" => statement
            .named_child(0)
            .is_none_or(|expression| is_stub_expression(expression, source)),
        [statement] if statement.kind() == "expression_statement" => statement
            .named_child(0)
            .is_some_and(|expression| is_stub_expression(expression, source)),
        _ => false,
    }
}

fn is_stub_expression(node: Node<'_>, source: &[u8]) -> bool {
    let mut node = node;
    while matches!(node.kind(), "await_expression" | "parenthesized_expression") {
        let Some(inner) = node.named_child(0) else {
            return false;
        };
        node = inner;
    }
    if matches!(node.kind(), "null" | "undefined") {
        return true;
    }
    if matches!(node.kind(), "string" | "template_string") {
        return is_stub_label(node_text(node, source));
    }
    if node.kind() == "unary_expression" {
        let compact = node_text(node, source)
            .chars()
            .filter(|character| !character.is_whitespace())
            .collect::<String>();
        return matches!(compact.as_str(), "void0" | "voidundefined");
    }
    if node.kind() != "call_expression" {
        return false;
    }
    let Some(function) = node.child_by_field_name("function") else {
        return false;
    };
    let name = callee_terminal_name(function, source)
        .unwrap_or_default()
        .chars()
        .filter(|character| character.is_alphanumeric())
        .collect::<String>()
        .to_lowercase();
    if matches!(name.as_str(), "pending" | "notimplemented" | "todo") {
        return true;
    }
    if function.kind() == "member_expression"
        && node_text(function, source)
            .chars()
            .filter(|character| !character.is_whitespace())
            .collect::<String>()
            == "Promise.resolve"
    {
        return node
            .child_by_field_name("arguments")
            .is_some_and(|arguments| arguments.named_child_count() == 0);
    }
    false
}

fn callee_terminal_name<'a>(function: Node<'_>, source: &'a [u8]) -> Option<&'a str> {
    match function.kind() {
        "identifier" => Some(node_text(function, source)),
        "member_expression" => function
            .child_by_field_name("property")
            .map(|property| node_text(property, source)),
        _ => None,
    }
}

fn is_stub_label(value: &str) -> bool {
    let value = value
        .trim()
        .trim_matches(|character| matches!(character, '\'' | '"' | '`'));
    let normalized = value
        .chars()
        .filter(|character| character.is_alphanumeric())
        .collect::<String>()
        .to_lowercase();
    matches!(normalized.as_str(), "pending" | "notimplemented" | "todo")
}

fn contains_explicit_stub_marker(node: Node<'_>, source: &[u8]) -> bool {
    let mut stack = vec![node];
    while let Some(node) = stack.pop() {
        if matches!(node.kind(), "string" | "template_string")
            && is_stub_label(node_text(node, source))
        {
            return true;
        }
        if node.kind() == "identifier" && is_stub_label(node_text(node, source)) {
            return true;
        }
        push_named_children_reverse(node, &mut stack);
    }
    false
}

pub(super) const MAX_HANDLER_SNIPPET_CHARS: usize = 4_000;

pub(super) fn bounded_source_snippet(source: &str) -> String {
    let normalized = source.trim().replace("\r\n", "\n").replace('\r', "\n");
    if normalized.chars().count() <= MAX_HANDLER_SNIPPET_CHARS {
        return normalized;
    }
    let mut snippet: String = normalized
        .chars()
        .take(MAX_HANDLER_SNIPPET_CHARS - 1)
        .collect();
    snippet.push('…');
    snippet
}

fn declared_identifiers(handler: Node<'_>, source: &[u8]) -> BTreeMap<String, String> {
    let mut identifiers = Vec::new();
    if matches!(
        handler.kind(),
        "function_declaration" | "generator_function_declaration"
    ) {
        if let Some(name) = handler.child_by_field_name("name") {
            collect_identifier_text(name, source, &mut identifiers);
        }
    }
    if let Some(parameters) = handler
        .child_by_field_name("parameters")
        .or_else(|| handler.child_by_field_name("parameter"))
    {
        // Initializers execute in the surrounding scope; only the binding side belongs in the
        // alpha map. Otherwise an external call such as `makePage()` is renamed differently when
        // the local parameter itself is renamed.
        collect_parameter_bindings(parameters, source, &mut identifiers);
    }
    collect_declared_locals(handler, source, &mut identifiers);
    identifier_map(identifiers)
}

fn identifier_map(identifiers: Vec<String>) -> BTreeMap<String, String> {
    identifiers
        .into_iter()
        .enumerate()
        .map(|(index, name)| (name, format!("v{index}")))
        .collect()
}

fn collect_declared_locals(node: Node<'_>, source: &[u8], output: &mut Vec<String>) {
    let mut stack = vec![node];
    while let Some(node) = stack.pop() {
        if node.kind() == "variable_declarator" {
            if let Some(name) = node.child_by_field_name("name") {
                collect_identifier_text(name, source, output);
            }
        }
        push_named_children_reverse(node, &mut stack);
    }
}

fn collect_identifier_text(node: Node<'_>, source: &[u8], output: &mut Vec<String>) {
    let mut stack = vec![node];
    while let Some(node) = stack.pop() {
        if matches!(
            node.kind(),
            "identifier" | "shorthand_property_identifier_pattern"
        ) {
            push_identifier(output, node_text(node, source));
        }
        push_named_children_reverse(node, &mut stack);
    }
}

fn push_identifier(output: &mut Vec<String>, identifier: &str) {
    if !output.iter().any(|existing| existing == identifier) {
        output.push(identifier.to_owned());
    }
}

#[derive(Clone, Copy)]
enum AstMode {
    Normalized,
    Alpha,
    Structural,
}

struct LocalConstant {
    declaration_start: usize,
    scope_start: usize,
    scope_end: usize,
    alpha: String,
    structural: String,
    safe: bool,
    parameter: bool,
    lexical: bool,
}

#[derive(Default)]
struct LocalConstants {
    bindings: BTreeMap<String, Vec<LocalConstant>>,
}

impl LocalConstants {
    fn collect(handler: Node<'_>, source: &[u8], declared: &BTreeMap<String, String>) -> Self {
        let mut constants = Self::default();
        let mut ancestor = handler.parent();
        while let Some(node) = ancestor {
            if matches!(
                node.kind(),
                "class" | "class_declaration" | "abstract_class_declaration"
            ) {
                if let Some(name) = node.child_by_field_name("name") {
                    constants.insert_unresolved_shadow(
                        name,
                        source,
                        node.start_byte(),
                        node,
                        false,
                    );
                }
            }
            ancestor = node.parent();
        }
        let mut pending = Vec::new();
        let mut stack = vec![handler];
        while let Some(node) = stack.pop() {
            if is_function_like(node) {
                if let Some(parameters) = node
                    .child_by_field_name("parameters")
                    .or_else(|| node.child_by_field_name("parameter"))
                {
                    let mut names = Vec::new();
                    collect_parameter_bindings(parameters, source, &mut names);
                    for name in names {
                        constants
                            .bindings
                            .entry(name)
                            .or_default()
                            .push(LocalConstant {
                                declaration_start: node.start_byte(),
                                scope_start: node.start_byte(),
                                scope_end: node.end_byte(),
                                alpha: String::new(),
                                structural: String::new(),
                                safe: true,
                                parameter: true,
                                lexical: false,
                            });
                    }
                }
            }
            let declaration_shadow = match node.kind() {
                "class_declaration" | "abstract_class_declaration" => node
                    .child_by_field_name("name")
                    .zip(local_constant_scope(node.parent(), handler))
                    .map(|(name, scope)| (name, scope, node.start_byte(), true)),
                "function_declaration" | "generator_function_declaration" | "enum_declaration" => {
                    node.child_by_field_name("name")
                        .zip(local_constant_scope(node.parent(), handler))
                        .map(|(name, scope)| (name, scope, scope.start_byte(), false))
                }
                "function_expression" | "generator_function" | "class" => node
                    .child_by_field_name("name")
                    .map(|name| (name, node, node.start_byte(), false)),
                "catch_clause" => node
                    .child_by_field_name("parameter")
                    .map(|parameter| (parameter, node, node.start_byte(), false)),
                // `for (const x of xs)` binds `x` for the loop, but the grammar attaches that
                // binding to the loop itself rather than to a `variable_declarator`, so the
                // declarator branch below never sees it and an outer constant of the same name
                // stayed visible inside the body. Without a declaration keyword the left side is
                // an assignment target and introduces no binding at all.
                "for_in_statement" => node
                    .child_by_field_name("kind")
                    .zip(node.child_by_field_name("left"))
                    .and_then(|(keyword, left)| {
                        let lexical = matches!(node_text(keyword, source), "let" | "const");
                        // `var` is function-scoped and hoists past the loop; `let`/`const` belong
                        // to the loop alone.
                        let scope = if lexical {
                            Some(node)
                        } else {
                            local_constant_scope(node.parent(), handler)
                        };
                        scope.map(|scope| (left, scope, node.start_byte(), lexical))
                    }),
                _ => None,
            };
            if let Some((name, scope, declaration_start, lexical)) = declaration_shadow {
                constants.insert_unresolved_shadow(name, source, declaration_start, scope, lexical);
            }
            if node.kind() == "variable_declarator" {
                let declaration = node.parent();
                if let (Some(name), Some(scope)) = (
                    node.child_by_field_name("name"),
                    local_constant_scope(node.parent(), handler),
                ) {
                    // Register shadows before evaluating any initializer: a later lexical
                    // declaration must never expose an outer constant through its TDZ.
                    let mut names = Vec::new();
                    collect_parameter_bindings(name, source, &mut names);
                    for binding_name in names {
                        let lexical =
                            declaration.is_none_or(|d| d.kind() != "variable_declaration");
                        if !lexical
                            && node.child_by_field_name("value").is_none()
                            && constants
                                .bindings
                                .get(&binding_name)
                                .is_some_and(|entries| {
                                    entries.iter().any(|b| {
                                        b.scope_start == scope.start_byte()
                                            && b.scope_end == scope.end_byte()
                                    })
                                })
                        {
                            continue;
                        }
                        constants
                            .bindings
                            .entry(binding_name)
                            .or_default()
                            .push(LocalConstant {
                                declaration_start: node.start_byte(),
                                scope_start: scope.start_byte(),
                                scope_end: scope.end_byte(),
                                alpha: String::new(),
                                structural: String::new(),
                                safe: false,
                                parameter: false,
                                lexical,
                            });
                    }
                    // Destructuring is a shadow too, but is not a proven primitive constant.
                    if let Some(value) = node
                        .child_by_field_name("value")
                        .filter(|_| name.kind() == "identifier")
                    {
                        pending.push((
                            node_text(name, source).to_owned(),
                            node.start_byte(),
                            scope.start_byte(),
                            scope.end_byte(),
                            value,
                            declaration.is_some_and(is_const_declaration),
                        ));
                    }
                }
            }
            push_named_children_reverse(node, &mut stack);
        }
        // Declaration order makes earlier immutable constants available while serializing later
        // initializers. This preserves semantics through bounded alias chains without recursive
        // AST traversal; forward references remain unresolved because they are invalid at runtime.
        pending.sort_by_key(|(_, declaration_start, _, _, _, _)| *declaration_start);
        for (name, declaration_start, scope_start, scope_end, value, immutable) in pending {
            let safe = immutable
                && match value.kind() {
                    "string" | "number" | "true" | "false" | "null" | "undefined" => true,
                    "identifier" => constants
                        .binding(node_text(value, source), value)
                        .is_some_and(|binding| binding.safe),
                    _ => false,
                };
            let fingerprint = |mode| {
                // Reuse the value digest across aliases instead of hashing the alias spelling.
                if safe && value.kind() == "identifier" {
                    if let Some(resolved) = constants.resolve(node_text(value, source), value, mode)
                    {
                        return resolved.to_owned();
                    }
                }
                let serialized = if safe {
                    serialize_ast(value, source, declared, mode)
                } else {
                    serialize_assertion_value(value, source, declared, mode, &constants)
                };
                stable_fingerprint(&serialized)
            };
            let alpha = fingerprint(AstMode::Alpha);
            let structural = fingerprint(AstMode::Structural);
            constants.bindings.entry(name).and_modify(|entries| {
                if let Some(binding) = entries
                    .iter_mut()
                    .find(|binding| binding.declaration_start == declaration_start)
                {
                    *binding = LocalConstant {
                        declaration_start,
                        scope_start,
                        scope_end,
                        alpha,
                        structural,
                        safe,
                        parameter: false,
                        lexical: binding.lexical,
                    };
                }
            });
        }
        constants
    }

    fn insert_unresolved_shadow(
        &mut self,
        pattern: Node<'_>,
        source: &[u8],
        declaration_start: usize,
        scope: Node<'_>,
        lexical: bool,
    ) {
        let mut names = Vec::new();
        if pattern.kind() == "type_identifier" {
            push_identifier(&mut names, node_text(pattern, source));
        } else {
            collect_parameter_bindings(pattern, source, &mut names);
        }
        for name in names {
            self.bindings.entry(name).or_default().push(LocalConstant {
                declaration_start,
                scope_start: scope.start_byte(),
                scope_end: scope.end_byte(),
                alpha: String::new(),
                structural: String::new(),
                safe: false,
                parameter: false,
                lexical,
            });
        }
    }

    fn resolve(&self, name: &str, use_site: Node<'_>, mode: AstMode) -> Option<&str> {
        let binding = self
            .binding(name, use_site)
            .filter(|binding| !binding.parameter)?;
        let fingerprint = match mode {
            AstMode::Alpha | AstMode::Normalized => binding.alpha.as_str(),
            AstMode::Structural => binding.structural.as_str(),
        };
        // Shadow placeholders have no resolved value; retain their identifier in the AST.
        (!fingerprint.is_empty()).then_some(fingerprint)
    }

    fn binding(&self, name: &str, use_site: Node<'_>) -> Option<&LocalConstant> {
        self.bindings
            .get(name)?
            .iter()
            .filter(|binding| {
                binding.scope_start <= use_site.start_byte()
                    && binding.scope_end >= use_site.end_byte()
            })
            .min_by(|left, right| {
                let left_width = left.scope_end.saturating_sub(left.scope_start);
                let right_width = right.scope_end.saturating_sub(right.scope_start);
                left_width.cmp(&right_width).then_with(|| {
                    let rank = |b: &LocalConstant| {
                        (
                            b.lexical || b.declaration_start <= use_site.start_byte(),
                            b.declaration_start,
                        )
                    };
                    rank(right).cmp(&rank(left))
                })
            })
            .filter(|binding| binding.declaration_start <= use_site.start_byte())
    }
}

fn is_function_like(node: Node<'_>) -> bool {
    matches!(
        node.kind(),
        "function_declaration"
            | "generator_function_declaration"
            | "function_expression"
            | "generator_function"
            | "arrow_function"
            | "method_definition"
    )
}

fn is_unresolved_assertion(event: &str) -> bool {
    matches!(event, UNRESOLVED_ASSERTION | DEFERRED_UNRESOLVED_ASSERTION)
}

fn has_function_parameters(node: Node<'_>) -> bool {
    node.child_by_field_name("parameters")
        .is_some_and(|parameters| parameters.named_child_count() > 0)
        || node.child_by_field_name("parameter").is_some()
}

fn is_const_declaration(declaration: Node<'_>) -> bool {
    declaration.kind() == "lexical_declaration"
        && (0..declaration.child_count()).any(|index| {
            declaration
                .child(index)
                .is_some_and(|child| !child.is_named() && child.kind() == "const")
        })
}

fn local_constant_scope<'tree>(
    mut node: Option<Node<'tree>>,
    handler: Node<'tree>,
) -> Option<Node<'tree>> {
    if node.is_some_and(|declaration| declaration.kind() == "variable_declaration") {
        return super::assertions::nearest_function_scope(node);
    }
    while let Some(candidate) = node {
        if candidate.id() == handler.id() {
            return Some(candidate);
        }
        if matches!(
            candidate.kind(),
            "statement_block"
                | "for_statement"
                | "for_in_statement"
                | "switch_body"
                | "catch_clause"
                | "class_static_block"
                | "internal_module"
                | "module"
        ) {
            return Some(candidate);
        }
        if is_function_like(candidate) {
            return None;
        }
        node = candidate.parent();
    }
    None
}

fn serialize_ast(
    node: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    mode: AstMode,
) -> String {
    serialize_ast_with_constants(node, source, declared, mode, None, None)
}

/// Whether a decoded property name can also be written with dot access.
///
/// Only then do `obj['name']` and `obj.name` denote the same expression; any other name has no dot
/// spelling, so folding it into one would invent an equivalence.
fn is_identifier_name(name: &str) -> bool {
    let mut characters = name.chars();
    characters
        .next()
        .is_some_and(|first| first.is_alphabetic() || first == '_' || first == '$')
        && characters
            .all(|character| character.is_alphanumeric() || character == '_' || character == '$')
}

fn serialize_ast_with_constants(
    node: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    mode: AstMode,
    constants: Option<&LocalConstants>,
    assertions: Option<&AssertionBindings>,
) -> String {
    enum Event<'tree> {
        Visit(Node<'tree>, bool),
        Text(String),
        Close,
    }
    let mut output = String::new();
    let mut stack = vec![Event::Visit(node, false)];
    while let Some(event) = stack.pop() {
        match event {
            Event::Close => output.push(')'),
            Event::Text(text) => output.push_str(&text),
            Event::Visit(node, prefixed) => {
                if node.kind() == "comment" {
                    continue;
                }
                if prefixed {
                    output.push(' ');
                }
                if let Some((negated, matcher)) =
                    assertions.and_then(|bindings| bindings.asymmetric_matcher(node, source))
                {
                    output.push_str("(asymmetric_matcher:");
                    if negated {
                        output.push_str("not.");
                    }
                    output.push_str(&matcher);
                    if let Some(arguments) = node.child_by_field_name("arguments") {
                        stack.push(Event::Close);
                        stack.push(Event::Visit(arguments, true));
                    } else {
                        output.push(')');
                    }
                    continue;
                }
                if let Some(constants) = constants {
                    // Substitute at the use site so inline and local values retain identical shape.
                    let shorthand = node.kind() == "shorthand_property_identifier";
                    let resolved = (node.kind() == "identifier" || shorthand)
                        .then(|| constants.resolve(node_text(node, source), node, mode))
                        .flatten();
                    let literal = matches!(
                        node.kind(),
                        "string" | "number" | "true" | "false" | "null" | "undefined"
                    );
                    if resolved.is_some() || literal {
                        let fingerprint = resolved.map(str::to_owned).unwrap_or_else(|| {
                            stable_fingerprint(&serialize_ast(node, source, declared, mode))
                        });
                        if shorthand {
                            // A shorthand carries both a property key and a resolved value.
                            output.push_str(&format!("<key:{}>", node_text(node, source)));
                        }
                        output.push_str(&format!("<value:{fingerprint}>"));
                        continue;
                    }
                }
                if matches!(mode, AstMode::Structural)
                    && matches!(
                        node.kind(),
                        "string"
                            | "string_fragment"
                            | "number"
                            | "regex"
                            | "true"
                            | "false"
                            | "null"
                    )
                {
                    output.push('<');
                    output.push_str(node.kind());
                    output.push('>');
                    continue;
                }
                // `obj['name']` and `obj.name` read the same property, so a readable computed
                // form is serialized as the dot form and the two share a fingerprint. Only a
                // static string literal decoding to a valid identifier qualifies: that is the one
                // case where a dot spelling exists. A key such as `'not.resolves'` names a single
                // property and must not be folded into the chain `.not.resolves`.
                if node.kind() == "subscript_expression" {
                    if let Some((object, name)) = node
                        .child_by_field_name("object")
                        .zip(node.child_by_field_name("index"))
                        .and_then(|(object, index)| {
                            super::matcher::static_string_key(index, source)
                                .filter(|name| is_identifier_name(name))
                                .map(|name| (object, name))
                        })
                    {
                        // `a?.['b']` short-circuits where `a['b']` throws, so the optional link is
                        // part of the access and must survive canonicalisation. Emitting it in the
                        // shape the dotted form uses keeps `a?.['b']` equal to `a?.b` and distinct
                        // from `a.b`.
                        let mut cursor = node.walk();
                        let optional = node
                            .children(&mut cursor)
                            .any(|child| child.kind() == "optional_chain");
                        let link = if optional {
                            " (optional_chain ?.:?.)"
                        } else {
                            " .:."
                        };
                        output.push_str("(member_expression");
                        stack.push(Event::Close);
                        stack.push(Event::Text(format!("{link} property_identifier:{name}")));
                        stack.push(Event::Visit(object, true));
                        continue;
                    }
                }
                let mut cursor = node.walk();
                let children: Vec<_> = node
                    .children(&mut cursor)
                    .filter(|child| !child.is_extra() && child.kind() != "comment")
                    .collect();
                if children.is_empty() {
                    let text = node_text(node, source);
                    let value = match mode {
                        AstMode::Normalized => text,
                        AstMode::Alpha | AstMode::Structural
                            if matches!(
                                node.kind(),
                                "identifier" | "shorthand_property_identifier_pattern"
                            ) =>
                        {
                            declared.get(text).map_or(text, String::as_str)
                        }
                        AstMode::Alpha | AstMode::Structural => text,
                    };
                    output.push_str(node.kind());
                    output.push(':');
                    output.push_str(value);
                } else {
                    output.push('(');
                    output.push_str(node.kind());
                    stack.push(Event::Close);
                    for child in children.into_iter().rev() {
                        stack.push(Event::Visit(child, true));
                    }
                }
            }
        }
    }
    output
}

fn behavior_signature(
    handler: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    assertions: &AssertionBindings,
    local_constants: &LocalConstants,
) -> Vec<String> {
    let mut signature = Vec::new();
    collect_behavior(
        handler,
        source,
        declared,
        assertions,
        local_constants,
        &mut signature,
    );
    signature
}

fn collect_behavior<'tree>(
    node: Node<'tree>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    assertions: &AssertionBindings,
    local_constants: &LocalConstants,
    output: &mut Vec<String>,
) {
    let root_id = node.id();
    let mut stack = vec![(node, false, false)];
    let push_children =
        |node: Node<'tree>, deferred, unresolved_callback_parameters, stack: &mut Vec<_>| {
            let start = stack.len();
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                stack.push((child, deferred, unresolved_callback_parameters));
            }
            stack[start..].reverse();
        };
    while let Some((node, deferred, unresolved_callback_parameters)) = stack.pop() {
        let nested_function = node.id() != root_id && is_function_like(node);
        if nested_function {
            let mut parent = node.parent();
            // Argument values can contain callbacks inside objects, arrays, or expressions.
            // Do not cross into an enclosing function's arguments or unrelated local bodies.
            while let Some(ancestor) = parent {
                if ancestor.kind() == "arguments" {
                    break;
                }
                if ancestor.id() == root_id
                    || is_function_like(ancestor)
                    || matches!(ancestor.kind(), "statement_block" | "class_body")
                {
                    parent = None;
                    break;
                }
                parent = ancestor.parent();
            }
            if parent.is_none() {
                continue;
            }
        }
        // Retain syntactic call evidence in callbacks without promoting their assertions
        // to executed behavior. Dropping the body makes unrelated callbacks look identical.
        let deferred = deferred || nested_function;
        let parameterized_callback = nested_function && has_function_parameters(node);
        if parameterized_callback {
            // Callback arguments are not evaluated, so any runtime parameter can change the
            // callback's behavior even when its body contains no recognized assertion.
            output.push(DEFERRED_UNRESOLVED_ASSERTION.to_owned());
        }
        let unresolved_callback_parameters =
            unresolved_callback_parameters || parameterized_callback;
        match node.kind() {
            "call_expression" => {
                if let Some(event) =
                    assertion_behavior_event(node, source, declared, assertions, local_constants)
                {
                    if unresolved_callback_parameters {
                        // The callback-level marker already makes this handler non-comparable.
                    } else if deferred {
                        output.push(if event == UNRESOLVED_ASSERTION {
                            DEFERRED_UNRESOLVED_ASSERTION.to_owned()
                        } else {
                            format!("deferred-{event}")
                        });
                    } else {
                        output.push(event);
                    }
                    // Treat the complete assertion as one atomic behavior event. Its subject and
                    // expected values are already fingerprinted, so traversing its children would
                    // count subject calls such as `page.locator()` a second time and make overlap
                    // depend on incidental expression complexity.
                    continue;
                }
                if let Some(function) = node.child_by_field_name("function") {
                    let invoked = super::registrations::unwrap_registration_callee(function)
                        .unwrap_or(function);
                    if invoked.kind() == "generator_function" {
                        // Arguments run now; the body stays suspended. Parameter initialization
                        // is unresolved, as for other parameterized inline functions.
                        if has_function_parameters(invoked) {
                            output.push(if deferred {
                                DEFERRED_UNRESOLVED_ASSERTION.to_owned()
                            } else {
                                UNRESOLVED_ASSERTION.to_owned()
                            });
                        }
                        if let Some(evaluated) = node.child_by_field_name("arguments") {
                            push_children(
                                evaluated,
                                deferred,
                                unresolved_callback_parameters,
                                &mut stack,
                            );
                        }
                        continue;
                    }
                    if matches!(invoked.kind(), "arrow_function" | "function_expression") {
                        // Parameter substitution is not evaluated; do not invent equal values.
                        if has_function_parameters(invoked) {
                            output.push(if deferred {
                                DEFERRED_UNRESOLVED_ASSERTION.to_owned()
                            } else {
                                UNRESOLVED_ASSERTION.to_owned()
                            });
                            if let Some(arguments) = node.child_by_field_name("arguments") {
                                push_children(
                                    arguments,
                                    deferred,
                                    unresolved_callback_parameters,
                                    &mut stack,
                                );
                            }
                            continue;
                        }
                        // Record the executed body, not an extra generic wrapper-call event.
                        push_children(
                            invoked,
                            deferred,
                            unresolved_callback_parameters,
                            &mut stack,
                        );
                        if let Some(arguments) = node.child_by_field_name("arguments") {
                            push_children(
                                arguments,
                                deferred,
                                unresolved_callback_parameters,
                                &mut stack,
                            );
                        }
                        continue;
                    }
                    output.push(call_behavior_event(function, source, declared));
                }
            }
            "if_statement" | "switch_statement" | "for_statement" | "for_in_statement"
            | "while_statement" | "do_statement" | "return_statement" | "throw_statement" => {
                output.push(node.kind().to_owned())
            }
            _ => {}
        }
        push_children(node, deferred, unresolved_callback_parameters, &mut stack);
    }
}

/// Describes an assertion by its terminal matcher, modifiers, and asserted subject.
///
/// A generic call shape such as `expect#toHaveValue` is not enough to establish shared
/// behavior: assertions against two different controls are distinct, and `.not` reverses the
/// meaning of an otherwise identical assertion. Expected matcher arguments remain semantic so
/// assertions for conflicting values do not collapse into the same near-duplicate behavior.
/// Literal normalization remains confined to the separate structural fingerprint.
fn assertion_behavior_event(
    call: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    assertions: &AssertionBindings,
    local_constants: &LocalConstants,
) -> Option<String> {
    let (receiver, method) = assertion_property(call.child_by_field_name("function")?, source)?;

    let mut modifiers = Vec::new();
    let invocation = find_expect_invocation(receiver, source, &mut modifiers, assertions)?;
    modifiers.reverse();
    let arguments = invocation.child_by_field_name("arguments")?;
    let subject = arguments.named_child(0)?;
    // Structural mode retains member and call identities while normalizing local bindings and
    // literal values. This distinguishes `form.title` from `form.date` without hiding the
    // existing parameterization signal for `page.locator("#one")` versus `"#two"`.
    let subject = serialize_assertion_value(
        subject,
        source,
        declared,
        AstMode::Structural,
        local_constants,
    );
    let expected = call.child_by_field_name("arguments")?;
    // An external name is not proof of an equal value across files. Preserve extraction and
    // matcher checks, but decline handler equivalence rather than invent module resolution.
    let mut pending = vec![expected];
    let mut cursor = arguments.walk();
    let configuration: Vec<_> = arguments.named_children(&mut cursor).skip(1).collect();
    pending.extend(configuration.iter().copied());
    while let Some(value) = pending.pop() {
        // Only known builders on a trusted assertion factory are syntax, not external
        // values. Their arguments still need the same conservative value validation.
        if assertions.is_asymmetric_matcher(value, source) {
            if let Some(arguments) = value.child_by_field_name("arguments") {
                pending.push(arguments);
            }
            continue;
        }
        if matches!(value.kind(), "identifier" | "shorthand_property_identifier")
            && !local_constants
                .binding(node_text(value, source), value)
                .is_some_and(|binding| binding.safe)
        {
            return Some(UNRESOLVED_ASSERTION.to_owned());
        }
        push_named_children_reverse(value, &mut pending);
    }
    // Alpha mode canonicalizes parameter and local names while retaining literal values and
    // member identities. The whole arguments node is included to preserve matcher arity.
    let mut expected = serialize_assertion_expected(
        expected,
        source,
        declared,
        AstMode::Alpha,
        local_constants,
        assertions,
    );
    // Factory options affect execution, unlike structural literal normalization.
    for option in configuration {
        expected.push_str("\0factory-option:");
        expected.push_str(&serialize_assertion_value(
            option,
            source,
            declared,
            AstMode::Alpha,
            local_constants,
        ));
    }
    let qualifier = if modifiers.is_empty() {
        "expect".to_owned()
    } else {
        format!("expect.{}", modifiers.join("."))
    };
    Some(format!(
        "assert:{qualifier}#{}:{}:{}",
        encode_event_component(method),
        stable_fingerprint(&subject),
        stable_fingerprint(&expected)
    ))
}

fn serialize_assertion_value(
    node: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    mode: AstMode,
    local_constants: &LocalConstants,
) -> String {
    serialize_ast_with_constants(node, source, declared, mode, Some(local_constants), None)
}

fn serialize_assertion_expected(
    node: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
    mode: AstMode,
    local_constants: &LocalConstants,
    assertions: &AssertionBindings,
) -> String {
    serialize_ast_with_constants(
        node,
        source,
        declared,
        mode,
        Some(local_constants),
        Some(assertions),
    )
}

/// Resolves a property access spelled either `object.name` or `object["name"]` to the same
/// receiver and name, so a statically computed key means what the dotted key means at every
/// position of an assertion chain. This is the resolver the factory and asymmetric-builder
/// positions already use; routing the chain walk through it keeps the supported spellings in one
/// place. A key that is not a static string yields `None`, so a runtime-selected property keeps
/// its conservative treatment instead of gaining trust it cannot prove.
/// Encodes a property name as a component of an assertion event.
///
/// Event components are joined with `.`, `#` and `:`, so a decoded string key containing one of
/// them would be indistinguishable from the join itself: `expect(x)['not.resolves']` would
/// otherwise produce the event that `expect(x).not.resolves` produces.
///
/// Only a decoded key is escaped. An identifier cannot contain those delimiters, and escaping it
/// too would make a name written with a unicode escape collide with a key that genuinely contains
/// a backslash — `x.foo\u0062ar` reads `foobar`, while `x['foo\\u0062ar']` reads a different
/// property entirely.
fn encode_event_component(name: Cow<'_, str>) -> Cow<'_, str> {
    const DELIMITERS: [char; 4] = ['\\', '.', '#', ':'];
    let Cow::Owned(decoded) = name else {
        return name;
    };
    if !decoded.contains(DELIMITERS) {
        return Cow::Owned(decoded);
    }
    let mut escaped = String::with_capacity(decoded.len() + 8);
    for character in decoded.chars() {
        if DELIMITERS.contains(&character) {
            escaped.push('\\');
        }
        escaped.push(character);
    }
    Cow::Owned(escaped)
}

fn assertion_property<'tree, 'source>(
    node: Node<'tree>,
    source: &'source [u8],
) -> Option<(Node<'tree>, Cow<'source, str>)> {
    match registration_callee(node, source)? {
        RegistrationCallee::Property { object, name } => Some((object, name)),
        RegistrationCallee::Identifier(_) => None,
    }
}

fn find_expect_invocation<'tree>(
    node: Node<'tree>,
    source: &[u8],
    modifiers: &mut Vec<String>,
    assertions: &AssertionBindings,
) -> Option<Node<'tree>> {
    let mut current = node;
    for _ in 0..MAX_ASSERTION_CHAIN_DEPTH {
        match current.kind() {
            "call_expression" => {
                let function = super::registrations::unwrap_registration_callee(
                    current.child_by_field_name("function")?,
                )?;
                if assertions.is_factory(function, source) {
                    return Some(current);
                }
                if let Some((object, option)) = assertion_property(function, source) {
                    if assertions.is_factory(object, source)
                        && matches!(option.as_ref(), "soft" | "poll")
                    {
                        modifiers.push(encode_event_component(option).into_owned());
                        return Some(current);
                    }
                }
                return None;
            }
            "member_expression" | "subscript_expression" => {
                let (object, modifier) = assertion_property(current, source)?;
                modifiers.push(encode_event_component(modifier).into_owned());
                current = object;
            }
            "parenthesized_expression"
            | "await_expression"
            | "as_expression"
            | "satisfies_expression"
            | "non_null_expression" => {
                current = current.named_child(0)?;
            }
            "type_assertion" => {
                let last = u32::try_from(current.named_child_count().checked_sub(1)?).ok()?;
                current = current.named_child(last)?;
            }
            _ => return None,
        }
    }
    None
}

fn call_behavior_event(
    function: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
) -> String {
    if function.kind() == "identifier" {
        let name = node_text(function, source);
        return format!("call:{}", declared.get(name).map_or(name, String::as_str));
    }
    // Both spellings of one property name the same method, so `page['locator']()` records the
    // event `page.locator()` records. `assertion_property` resolves only a static string literal,
    // so a runtime key still falls through to the structural form below.
    if let Some((object, property)) = assertion_property(function, source) {
        if let Some(receiver) = static_call_receiver(object, source, declared) {
            return format!(
                "call:{receiver}#{}",
                encode_event_component(property.clone())
            );
        }
    }
    format!(
        "call:{}",
        serialize_ast(function, source, declared, AstMode::Structural)
    )
}

fn static_call_receiver(
    node: Node<'_>,
    source: &[u8],
    declared: &BTreeMap<String, String>,
) -> Option<String> {
    match node.kind() {
        "identifier" => {
            let name = node_text(node, source);
            Some(declared.get(name).map_or(name, String::as_str).to_owned())
        }
        "this" | "super" => Some(node_text(node, source).to_owned()),
        "parenthesized_expression" | "await_expression" => {
            static_call_receiver(node.named_child(0)?, source, declared)
        }
        "member_expression" | "subscript_expression" => {
            let (object, property) = assertion_property(node, source)?;
            let object = static_call_receiver(object, source, declared)?;
            Some(format!("{object}.{}", encode_event_component(property)))
        }
        "call_expression" => {
            let function = node.child_by_field_name("function")?;
            if let Some((object, _)) = assertion_property(function, source) {
                static_call_receiver(object, source, declared)
            } else if function.kind() == "identifier" {
                let name = node_text(function, source);
                Some(declared.get(name).map_or(name, String::as_str).to_owned())
            } else {
                None
            }
        }
        _ => None,
    }
}