exspec-lang-rust 0.4.4

Rust language support for exspec
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
pub mod observe;

use std::sync::OnceLock;

use exspec_core::extractor::{FileAnalysis, LanguageExtractor, TestAnalysis, TestFunction};
use exspec_core::query_utils::{
    apply_same_file_helper_tracing, collect_mock_class_names, count_captures,
    count_captures_within_context, count_duplicate_literals,
    extract_suppression_from_previous_line, has_any_match,
};
use streaming_iterator::StreamingIterator;
use tree_sitter::{Node, Parser, Query, QueryCursor};

const TEST_FUNCTION_QUERY: &str = include_str!("../queries/test_function.scm");
const ASSERTION_QUERY: &str = include_str!("../queries/assertion.scm");
const MOCK_USAGE_QUERY: &str = include_str!("../queries/mock_usage.scm");
const MOCK_ASSIGNMENT_QUERY: &str = include_str!("../queries/mock_assignment.scm");
const PARAMETERIZED_QUERY: &str = include_str!("../queries/parameterized.scm");
const IMPORT_PBT_QUERY: &str = include_str!("../queries/import_pbt.scm");
const IMPORT_CONTRACT_QUERY: &str = include_str!("../queries/import_contract.scm");
const HOW_NOT_WHAT_QUERY: &str = include_str!("../queries/how_not_what.scm");
const PRIVATE_IN_ASSERTION_QUERY: &str = include_str!("../queries/private_in_assertion.scm");
const ERROR_TEST_QUERY: &str = include_str!("../queries/error_test.scm");
const RELATIONAL_ASSERTION_QUERY: &str = include_str!("../queries/relational_assertion.scm");
const WAIT_AND_SEE_QUERY: &str = include_str!("../queries/wait_and_see.scm");
const HELPER_TRACE_QUERY: &str = include_str!("../queries/helper_trace.scm");

fn rust_language() -> tree_sitter::Language {
    tree_sitter_rust::LANGUAGE.into()
}

/// Check if an `attribute_item` node has an exact attribute name.
/// Walks the tree-sitter structure: attribute_item → attribute → identifier.
/// Avoids substring matches that could falsely trigger on names like
/// `my_crate::should_panic_handler`.
fn attribute_has_name(node: &Node, source_bytes: &[u8], name: &str) -> bool {
    // tree-sitter-rust structure:
    //   attribute_item → "#" → "[" → attribute → "]"
    //   attribute → path (identifier | scoped_identifier) [+ arguments]
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        // Direct identifier child (simple attribute like #[test])
        if child.kind() == "identifier" {
            if let Ok(text) = child.utf8_text(source_bytes) {
                if text == name {
                    return true;
                }
            }
        }
        // attribute or meta_item child
        if child.kind() == "attribute" || child.kind() == "meta_item" {
            let mut inner_cursor = child.walk();
            for inner in child.children(&mut inner_cursor) {
                if inner.kind() == "identifier" {
                    if let Ok(text) = inner.utf8_text(source_bytes) {
                        if text == name {
                            return true;
                        }
                    }
                    // Only check the first identifier (the attribute name, not arguments)
                    break;
                }
            }
        }
    }
    false
}

fn cached_query<'a>(lock: &'a OnceLock<Query>, source: &str) -> &'a Query {
    lock.get_or_init(|| Query::new(&rust_language(), source).expect("invalid query"))
}

static TEST_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static ASSERTION_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static MOCK_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static MOCK_ASSIGN_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static PARAMETERIZED_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static IMPORT_PBT_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static IMPORT_CONTRACT_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static HOW_NOT_WHAT_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static PRIVATE_IN_ASSERTION_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static ERROR_TEST_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static RELATIONAL_ASSERTION_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static WAIT_AND_SEE_QUERY_CACHE: OnceLock<Query> = OnceLock::new();
static HELPER_TRACE_QUERY_CACHE: OnceLock<Query> = OnceLock::new();

pub struct RustExtractor;

impl RustExtractor {
    pub fn new() -> Self {
        Self
    }

    pub fn parser() -> Parser {
        let mut parser = Parser::new();
        let language = tree_sitter_rust::LANGUAGE;
        parser
            .set_language(&language.into())
            .expect("failed to load Rust grammar");
        parser
    }
}

impl Default for RustExtractor {
    fn default() -> Self {
        Self::new()
    }
}

fn extract_mock_class_name(var_name: &str) -> String {
    // Rust uses snake_case: mock_service -> "service"
    if let Some(stripped) = var_name.strip_prefix("mock_") {
        if !stripped.is_empty() {
            return stripped.to_string();
        }
    }
    // camelCase: mockService -> "Service" (less common in Rust but handle it)
    if let Some(stripped) = var_name.strip_prefix("mock") {
        if !stripped.is_empty() && stripped.starts_with(|c: char| c.is_uppercase()) {
            return stripped.to_string();
        }
    }
    var_name.to_string()
}

struct TestMatch {
    name: String,
    fn_start_byte: usize,
    fn_end_byte: usize,
    fn_start_row: usize,
    fn_end_row: usize,
    /// Row of attribute_item (for suppression lookup)
    attr_start_row: usize,
    /// Whether #[should_panic] is present (counts as assertion for T001)
    has_should_panic: bool,
}

/// Find the root object of a field_expression chain (method call chain).
/// e.g. `Config::builder().timeout(30).build()`:
///   call_expression { function: field_expression { value: call_expression { function: field_expression { value: call_expression { function: scoped_identifier } } } } }
///   → root call_expression's function is scoped_identifier
/// Check if a call_expression is a "constructor" (setup) or "method on local" (action).
/// Returns true for fixture-like calls: Type::new(), free_func(), builder chains from constructors.
/// Returns false for method calls on local variables: service.create(), result.unwrap().
fn is_constructor_call(node: Node) -> bool {
    let func = match node.child_by_field_name("function") {
        Some(f) => f,
        None => return true, // conservative
    };
    match func.kind() {
        // Type::new(), Config::default() — constructor
        "scoped_identifier" => true,
        // add(1, 2), create_user() — free function call
        "identifier" => true,
        // obj.method() or chain.method() — need to find the root
        "field_expression" => {
            let value = match func.child_by_field_name("value") {
                Some(v) => v,
                None => return true,
            };
            if value.kind() == "call_expression" {
                // Chain: inner_call().method() — recurse to check inner call
                is_constructor_call(value)
            } else {
                // Root is a local variable: service.create(), result.unwrap()
                false
            }
        }
        _ => true,
    }
}

/// Check if a let value expression represents fixture/setup (not action/prep).
/// In tree-sitter-rust, `obj.method()` is `call_expression { function: field_expression }`.
/// Fixture: Type::new(), struct literals, macros, free function calls, builder chains from constructors.
/// Non-fixture: method calls on local variables (e.g. service.create(), result.unwrap()).
fn is_fixture_value(node: Node) -> bool {
    match node.kind() {
        "call_expression" => is_constructor_call(node),
        "struct_expression" | "macro_invocation" => true,
        _ => true, // literals, etc. are test data (fixture-like)
    }
}

/// Count Rust assertion macros that have a message argument.
/// assert!(expr, "msg") has 1+ top-level commas in token_tree.
/// assert_eq!(a, b, "msg") has 2+ top-level commas in token_tree.
fn count_assertion_messages_rust(assertion_query: &Query, fn_node: Node, source: &[u8]) -> usize {
    let assertion_idx = match assertion_query.capture_index_for_name("assertion") {
        Some(idx) => idx,
        None => return 0,
    };
    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(assertion_query, fn_node, source);
    let mut count = 0;
    while let Some(m) = matches.next() {
        for cap in m.captures.iter().filter(|c| c.index == assertion_idx) {
            let node = cap.node;
            let macro_name = node
                .child_by_field_name("macro")
                .and_then(|n| n.utf8_text(source).ok())
                .unwrap_or("");

            // Find token_tree child
            let token_tree = (0..node.child_count()).find_map(|i| {
                let child = node.child(i)?;
                if child.kind() == "token_tree" {
                    Some(child)
                } else {
                    None
                }
            });

            if let Some(tt) = token_tree {
                // Count top-level commas in token_tree.
                // token_tree includes outer delimiters "(", ")".
                // Only count commas that are direct children of this token_tree
                // (not inside nested token_tree children).
                let mut comma_count = 0;
                for i in 0..tt.child_count() {
                    if let Some(child) = tt.child(i) {
                        if child.kind() == "," {
                            comma_count += 1;
                        }
                    }
                }

                // assert!(expr): needs 1+ comma for msg
                // assert_eq!(a, b): needs 2+ commas for msg
                let min_commas = if macro_name.contains("_eq") || macro_name.contains("_ne") {
                    2
                } else {
                    1
                };
                if comma_count >= min_commas {
                    count += 1;
                }
            }
        }
    }
    count
}

/// Count fixture-like `let` declarations in a Rust function body.
/// Excludes method calls on local variables (action/assertion prep).
fn count_fixture_lets(fn_node: Node) -> usize {
    let body = match fn_node.child_by_field_name("body") {
        Some(n) => n,
        None => return 0,
    };

    let mut count = 0;
    let mut cursor = body.walk();
    if cursor.goto_first_child() {
        loop {
            let node = cursor.node();
            if node.kind() == "let_declaration" {
                match node.child_by_field_name("value") {
                    Some(value) => {
                        if is_fixture_value(value) {
                            count += 1;
                        }
                    }
                    None => count += 1, // `let x;` without value — count conservatively
                }
            }
            if !cursor.goto_next_sibling() {
                break;
            }
        }
    }
    count
}

fn extract_functions_from_tree(source: &str, file_path: &str, root: Node) -> Vec<TestFunction> {
    let test_query = cached_query(&TEST_QUERY_CACHE, TEST_FUNCTION_QUERY);
    let assertion_query = cached_query(&ASSERTION_QUERY_CACHE, ASSERTION_QUERY);
    let mock_query = cached_query(&MOCK_QUERY_CACHE, MOCK_USAGE_QUERY);
    let mock_assign_query = cached_query(&MOCK_ASSIGN_QUERY_CACHE, MOCK_ASSIGNMENT_QUERY);
    let how_not_what_query = cached_query(&HOW_NOT_WHAT_QUERY_CACHE, HOW_NOT_WHAT_QUERY);
    let private_query = cached_query(
        &PRIVATE_IN_ASSERTION_QUERY_CACHE,
        PRIVATE_IN_ASSERTION_QUERY,
    );
    let wait_query = cached_query(&WAIT_AND_SEE_QUERY_CACHE, WAIT_AND_SEE_QUERY);

    let source_bytes = source.as_bytes();

    // test_function.scm captures @test_attr (attribute_item).
    // The corresponding function_item is the next sibling of attribute_item.
    let attr_idx = test_query
        .capture_index_for_name("test_attr")
        .expect("no @test_attr capture");

    let mut test_matches: Vec<TestMatch> = Vec::new();
    let mut seen_fn_bytes: std::collections::HashSet<usize> = std::collections::HashSet::new();

    {
        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(test_query, root, source_bytes);
        while let Some(m) = matches.next() {
            let attr_capture = match m.captures.iter().find(|c| c.index == attr_idx) {
                Some(c) => c,
                None => continue,
            };
            let attr_node = attr_capture.node;
            let attr_start_row = attr_node.start_position().row;

            // Check previous siblings for #[should_panic] (handles #[should_panic] before #[test]).
            // Also update attr_start_row to the earliest attribute for suppression comment lookup.
            let mut has_should_panic = false;
            let mut attr_start_row = attr_start_row;
            {
                let mut prev = attr_node.prev_sibling();
                while let Some(p) = prev {
                    if p.kind() == "attribute_item" {
                        attr_start_row = p.start_position().row;
                        if attribute_has_name(&p, source_bytes, "should_panic") {
                            has_should_panic = true;
                        }
                    } else if p.kind() != "line_comment" && p.kind() != "block_comment" {
                        break;
                    }
                    prev = p.prev_sibling();
                }
            }

            // Walk next siblings to find the function_item.
            // Also detect #[should_panic] among sibling attribute_items.
            let mut sibling = attr_node.next_sibling();
            while let Some(s) = sibling {
                if s.kind() == "function_item" {
                    let fn_start_byte = s.start_byte();
                    if seen_fn_bytes.insert(fn_start_byte) {
                        let name = s
                            .child_by_field_name("name")
                            .and_then(|n| n.utf8_text(source_bytes).ok())
                            .unwrap_or("")
                            .to_string();
                        if !name.is_empty() {
                            test_matches.push(TestMatch {
                                name,
                                fn_start_byte,
                                fn_end_byte: s.end_byte(),
                                fn_start_row: s.start_position().row,
                                fn_end_row: s.end_position().row,
                                attr_start_row,
                                has_should_panic,
                            });
                        }
                    }
                    break;
                }
                // Skip over other attribute_items or whitespace nodes
                // If we hit something that is not an attribute_item, stop
                if s.kind() == "attribute_item" {
                    if attribute_has_name(&s, source_bytes, "should_panic") {
                        has_should_panic = true;
                    }
                } else if s.kind() != "line_comment" && s.kind() != "block_comment" {
                    break;
                }
                sibling = s.next_sibling();
            }
        }
    }

    let mut functions = Vec::new();
    for tm in &test_matches {
        let fn_node = match root.descendant_for_byte_range(tm.fn_start_byte, tm.fn_end_byte) {
            Some(n) => n,
            None => continue,
        };

        let line = tm.fn_start_row + 1;
        let end_line = tm.fn_end_row + 1;
        let line_count = end_line - line + 1;

        let mut assertion_count =
            count_captures(assertion_query, "assertion", fn_node, source_bytes);

        // #[should_panic] is outside fn_node (sibling attribute), detected during sibling walk
        if tm.has_should_panic {
            assertion_count += 1;
        }
        let mock_count = count_captures(mock_query, "mock", fn_node, source_bytes);
        let mock_classes = collect_mock_class_names(
            mock_assign_query,
            fn_node,
            source_bytes,
            extract_mock_class_name,
        );
        let how_not_what_count =
            count_captures(how_not_what_query, "how_pattern", fn_node, source_bytes);

        let private_in_assertion_count = count_captures_within_context(
            assertion_query,
            "assertion",
            private_query,
            "private_access",
            fn_node,
            source_bytes,
        );

        let fixture_count = count_fixture_lets(fn_node);

        // T108: wait-and-see detection
        let has_wait = has_any_match(wait_query, "wait", fn_node, source_bytes);

        // T107: assertion message count
        let assertion_message_count =
            count_assertion_messages_rust(assertion_query, fn_node, source_bytes);

        // T106: duplicate literal count
        let duplicate_literal_count = count_duplicate_literals(
            assertion_query,
            fn_node,
            source_bytes,
            &["integer_literal", "float_literal", "string_literal"],
        );

        // Suppression comment is the line before the attribute_item
        let suppressed_rules = extract_suppression_from_previous_line(source, tm.attr_start_row);

        functions.push(TestFunction {
            name: tm.name.clone(),
            file: file_path.to_string(),
            line,
            end_line,
            analysis: TestAnalysis {
                assertion_count,
                mock_count,
                mock_classes,
                line_count,
                how_not_what_count: how_not_what_count + private_in_assertion_count,
                fixture_count,
                has_wait,
                has_skip_call: false,
                assertion_message_count,
                duplicate_literal_count,
                suppressed_rules,
            },
        });
    }

    functions
}

impl LanguageExtractor for RustExtractor {
    fn extract_test_functions(&self, source: &str, file_path: &str) -> Vec<TestFunction> {
        let mut parser = Self::parser();
        let tree = match parser.parse(source, None) {
            Some(t) => t,
            None => return Vec::new(),
        };
        extract_functions_from_tree(source, file_path, tree.root_node())
    }

    fn extract_file_analysis(&self, source: &str, file_path: &str) -> FileAnalysis {
        let mut parser = Self::parser();
        let tree = match parser.parse(source, None) {
            Some(t) => t,
            None => {
                return FileAnalysis {
                    file: file_path.to_string(),
                    functions: Vec::new(),
                    has_pbt_import: false,
                    has_contract_import: false,
                    has_error_test: false,
                    has_relational_assertion: false,
                    parameterized_count: 0,
                };
            }
        };

        let root = tree.root_node();
        let source_bytes = source.as_bytes();

        let functions = extract_functions_from_tree(source, file_path, root);

        let param_query = cached_query(&PARAMETERIZED_QUERY_CACHE, PARAMETERIZED_QUERY);
        let parameterized_count = count_captures(param_query, "parameterized", root, source_bytes);

        let pbt_query = cached_query(&IMPORT_PBT_QUERY_CACHE, IMPORT_PBT_QUERY);
        let has_pbt_import = has_any_match(pbt_query, "pbt_import", root, source_bytes);

        let contract_query = cached_query(&IMPORT_CONTRACT_QUERY_CACHE, IMPORT_CONTRACT_QUERY);
        let has_contract_import =
            has_any_match(contract_query, "contract_import", root, source_bytes);

        let error_test_query = cached_query(&ERROR_TEST_QUERY_CACHE, ERROR_TEST_QUERY);
        let has_error_test = has_any_match(error_test_query, "error_test", root, source_bytes);

        let relational_query = cached_query(
            &RELATIONAL_ASSERTION_QUERY_CACHE,
            RELATIONAL_ASSERTION_QUERY,
        );
        let has_relational_assertion =
            has_any_match(relational_query, "relational", root, source_bytes);

        let mut file_analysis = FileAnalysis {
            file: file_path.to_string(),
            functions,
            has_pbt_import,
            has_contract_import,
            has_error_test,
            has_relational_assertion,
            parameterized_count,
        };

        // Apply same-file helper tracing (Phase 23a)
        let helper_trace_query = cached_query(&HELPER_TRACE_QUERY_CACHE, HELPER_TRACE_QUERY);
        let assertion_query_for_trace = cached_query(&ASSERTION_QUERY_CACHE, ASSERTION_QUERY);
        apply_same_file_helper_tracing(
            &mut file_analysis,
            &tree,
            source_bytes,
            helper_trace_query,
            helper_trace_query,
            assertion_query_for_trace,
        );

        file_analysis
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fixture(name: &str) -> String {
        let path = format!(
            "{}/tests/fixtures/rust/{}",
            env!("CARGO_MANIFEST_DIR").replace("/crates/lang-rust", ""),
            name
        );
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("failed to read {path}: {e}"))
    }

    // --- Basic parser ---

    #[test]
    fn parse_rust_source() {
        let source = "#[test]\nfn test_example() {\n    assert_eq!(1, 1);\n}\n";
        let mut parser = RustExtractor::parser();
        let tree = parser.parse(source, None).unwrap();
        assert_eq!(tree.root_node().kind(), "source_file");
    }

    #[test]
    fn rust_extractor_implements_language_extractor() {
        let extractor = RustExtractor::new();
        let _: &dyn exspec_core::extractor::LanguageExtractor = &extractor;
    }

    // --- Test function extraction (TC-01, TC-02, TC-03) ---

    #[test]
    fn extract_single_test() {
        // TC-01: #[test] function is extracted
        let source = fixture("t001_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass.rs");
        assert_eq!(funcs.len(), 1, "should extract exactly 1 test function");
        assert_eq!(funcs[0].name, "test_create_user");
    }

    #[test]
    fn non_test_function_not_extracted() {
        // TC-02: functions without #[test] are not extracted
        let source = "fn helper() -> i32 { 42 }\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "helper.rs");
        assert_eq!(funcs.len(), 0, "non-test fn should not be extracted");
    }

    #[test]
    fn extract_tokio_test() {
        // TC-03: #[tokio::test] is extracted
        let source =
            "#[tokio::test]\nasync fn test_async_operation() {\n    assert_eq!(1, 1);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "tokio_test.rs");
        assert_eq!(funcs.len(), 1, "should extract #[tokio::test] function");
        assert_eq!(funcs[0].name, "test_async_operation");
    }

    // --- Assertion detection (TC-04, TC-05, TC-06, TC-07) ---

    #[test]
    fn assertion_count_zero_for_violation() {
        // TC-04: assertion-free test has count 0
        let source = fixture("t001_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_violation.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 0,
            "violation file should have 0 assertions"
        );
    }

    #[test]
    fn assertion_count_positive_for_pass() {
        // TC-05: assert_eq! is counted
        let source = fixture("t001_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.assertion_count >= 1,
            "pass file should have >= 1 assertion"
        );
    }

    #[test]
    fn all_assert_macros_counted() {
        // TC-06: assert!, assert_eq!, assert_ne! all counted
        let source = "#[test]\nfn test_all_asserts() {\n    assert!(true);\n    assert_eq!(1, 1);\n    assert_ne!(1, 2);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "test_asserts.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 3,
            "should count assert!, assert_eq!, assert_ne!"
        );
    }

    #[test]
    fn debug_assert_counted() {
        // TC-07: debug_assert! is also counted
        let source = "#[test]\nfn test_debug_assert() {\n    debug_assert!(true);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "test_debug.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 1,
            "debug_assert! should be counted"
        );
    }

    // --- Helper delegation assertion detection (#66) ---

    #[test]
    fn simple_assert_fn_call_detected() {
        // T1: assert_matches() function call counts as assertion
        let source = fixture("t001_pass_helper_delegation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass_helper_delegation.rs");
        let simple = funcs
            .iter()
            .find(|f| f.name == "test_simple_helper")
            .unwrap();
        assert!(
            simple.analysis.assertion_count >= 1,
            "assert_matches() fn call should be counted as assertion, got {}",
            simple.analysis.assertion_count
        );
    }

    #[test]
    fn scoped_assert_fn_call_detected() {
        // T2: common::assert_matches() scoped function call counts as assertion
        let source = fixture("t001_pass_helper_delegation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass_helper_delegation.rs");
        let scoped = funcs
            .iter()
            .find(|f| f.name == "test_scoped_helper")
            .unwrap();
        assert!(
            scoped.analysis.assertion_count >= 1,
            "common::assert_matches() should be counted as assertion, got {}",
            scoped.analysis.assertion_count
        );
    }

    #[test]
    fn mixed_macro_and_fn_call_counted() {
        // T3: Both macro and function call counted
        let source = fixture("t001_pass_helper_delegation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass_helper_delegation.rs");
        let mixed = funcs
            .iter()
            .find(|f| f.name == "test_mixed_macro_and_fn")
            .unwrap();
        assert_eq!(
            mixed.analysis.assertion_count, 2,
            "assert_eq! macro + assert_matches() fn call should total 2, got {}",
            mixed.analysis.assertion_count
        );
    }

    #[test]
    fn assertion_prefix_not_counted() {
        // T5: assertion_helper() should NOT be counted (^assert_ not ^assert)
        let source = "#[test]\nfn test_foo() {\n    assertion_helper(expected, actual);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "test_negative.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 0,
            "assertion_helper() should NOT be counted as assertion"
        );
    }

    #[test]
    fn ordinary_helper_not_counted() {
        // T6: helper_check() should NOT be counted
        let source = "#[test]\nfn test_foo() {\n    helper_check(expected, actual);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "test_negative2.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 0,
            "helper_check() should NOT be counted as assertion"
        );
    }

    // --- Mock detection (TC-08, TC-09, TC-10, TC-11) ---

    #[test]
    fn mock_pattern_detected() {
        // TC-08: MockXxx::new() is detected
        let source = "#[test]\nfn test_with_mock() {\n    let mock_svc = MockService::new();\n    assert_eq!(mock_svc.len(), 0);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "test_mock.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.mock_count >= 1,
            "MockService::new() should be detected"
        );
    }

    #[test]
    fn mock_count_for_violation() {
        // TC-09: mock_count > 5 triggers T002
        let source = fixture("t002_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t002_violation.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.mock_count > 5,
            "violation file should have > 5 mocks, got {}",
            funcs[0].analysis.mock_count
        );
    }

    #[test]
    fn mock_count_for_pass() {
        // TC-10: mock_count <= 5 passes
        let source = fixture("t002_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t002_pass.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.mock_count, 1,
            "pass file should have 1 mock"
        );
        assert_eq!(funcs[0].analysis.mock_classes, vec!["repo"]);
    }

    #[test]
    fn mock_class_name_extraction() {
        // TC-11: mock class name stripping
        assert_eq!(extract_mock_class_name("mock_service"), "service");
        assert_eq!(extract_mock_class_name("mock_db"), "db");
        assert_eq!(extract_mock_class_name("service"), "service");
        assert_eq!(extract_mock_class_name("mockService"), "Service");
    }

    // --- Giant test (TC-12, TC-13) ---

    #[test]
    fn giant_test_line_count() {
        // TC-12: > 50 lines triggers T003
        let source = fixture("t003_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t003_violation.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.line_count > 50,
            "violation file line_count should > 50, got {}",
            funcs[0].analysis.line_count
        );
    }

    #[test]
    fn short_test_line_count() {
        // TC-13: <= 50 lines passes
        let source = fixture("t003_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t003_pass.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.line_count <= 50,
            "pass file line_count should <= 50, got {}",
            funcs[0].analysis.line_count
        );
    }

    // --- File-level rules (TC-14, TC-15, TC-16, TC-17, TC-18) ---

    #[test]
    fn file_analysis_detects_parameterized() {
        // TC-14: #[rstest] detected
        let source = fixture("t004_pass.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t004_pass.rs");
        assert!(
            fa.parameterized_count >= 1,
            "should detect #[rstest], got {}",
            fa.parameterized_count
        );
    }

    #[test]
    fn file_analysis_no_parameterized() {
        // TC-15: no #[rstest] means parameterized_count = 0
        let source = fixture("t004_violation.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t004_violation.rs");
        assert_eq!(
            fa.parameterized_count, 0,
            "violation file should have 0 parameterized"
        );
    }

    #[test]
    fn file_analysis_pbt_import() {
        // TC-16: use proptest detected
        let source = fixture("t005_pass.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t005_pass.rs");
        assert!(fa.has_pbt_import, "should detect proptest import");
    }

    #[test]
    fn file_analysis_no_pbt_import() {
        // TC-17: no PBT import
        let source = fixture("t005_violation.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t005_violation.rs");
        assert!(!fa.has_pbt_import, "should not detect PBT import");
    }

    #[test]
    fn file_analysis_no_contract() {
        // TC-18: T008 always INFO for Rust (no contract library)
        let source = fixture("t008_violation.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t008_violation.rs");
        assert!(!fa.has_contract_import, "Rust has no contract library");
    }

    // --- prop_assert detection (#10) ---

    #[test]
    fn prop_assert_counts_as_assertion() {
        // #10: prop_assert_eq! should be counted as assertion
        let source = fixture("t001_proptest_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_proptest_pass.rs");
        assert_eq!(funcs.len(), 1, "should extract test from proptest! macro");
        assert!(
            funcs[0].analysis.assertion_count >= 1,
            "prop_assert_eq! should be counted, got {}",
            funcs[0].analysis.assertion_count
        );
    }

    // --- Inline suppression (TC-19) ---

    #[test]
    fn suppressed_test_has_suppressed_rules() {
        // TC-19: // exspec-ignore: T001 suppresses T001
        let source = fixture("suppressed.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "suppressed.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0]
                .analysis
                .suppressed_rules
                .iter()
                .any(|r| r.0 == "T001"),
            "T001 should be suppressed, got: {:?}",
            funcs[0].analysis.suppressed_rules
        );
    }

    // --- Query capture name verification (#14) ---

    fn make_query(scm: &str) -> Query {
        Query::new(&rust_language(), scm).unwrap()
    }

    #[test]
    fn query_capture_names_test_function() {
        let q = make_query(include_str!("../queries/test_function.scm"));
        assert!(
            q.capture_index_for_name("test_attr").is_some(),
            "test_function.scm must define @test_attr capture"
        );
    }

    #[test]
    fn query_capture_names_assertion() {
        let q = make_query(include_str!("../queries/assertion.scm"));
        assert!(
            q.capture_index_for_name("assertion").is_some(),
            "assertion.scm must define @assertion capture"
        );
    }

    #[test]
    fn query_capture_names_mock_usage() {
        let q = make_query(include_str!("../queries/mock_usage.scm"));
        assert!(
            q.capture_index_for_name("mock").is_some(),
            "mock_usage.scm must define @mock capture"
        );
    }

    #[test]
    fn query_capture_names_mock_assignment() {
        let q = make_query(include_str!("../queries/mock_assignment.scm"));
        assert!(
            q.capture_index_for_name("var_name").is_some(),
            "mock_assignment.scm must define @var_name (required by collect_mock_class_names .expect())"
        );
    }

    #[test]
    fn query_capture_names_parameterized() {
        let q = make_query(include_str!("../queries/parameterized.scm"));
        assert!(
            q.capture_index_for_name("parameterized").is_some(),
            "parameterized.scm must define @parameterized capture"
        );
    }

    #[test]
    fn query_capture_names_import_pbt() {
        let q = make_query(include_str!("../queries/import_pbt.scm"));
        assert!(
            q.capture_index_for_name("pbt_import").is_some(),
            "import_pbt.scm must define @pbt_import capture"
        );
    }

    // Comment-only file by design (Rust has no contract validation library).
    // This assertion will fail when a real library is added.
    // When that happens, update the has_any_match call site in extract_file_analysis() accordingly.
    #[test]
    fn query_capture_names_import_contract_comment_only() {
        let q = make_query(include_str!("../queries/import_contract.scm"));
        assert!(
            q.capture_index_for_name("contract_import").is_none(),
            "Rust import_contract.scm is intentionally comment-only"
        );
    }

    // --- T103: missing-error-test ---

    #[test]
    fn error_test_should_panic() {
        let source = fixture("t103_pass.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t103_pass.rs");
        assert!(
            fa.has_error_test,
            "#[should_panic] should set has_error_test"
        );
    }

    #[test]
    fn error_test_unwrap_err() {
        let source = fixture("t103_pass_unwrap_err.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t103_pass_unwrap_err.rs");
        assert!(fa.has_error_test, ".unwrap_err() should set has_error_test");
    }

    #[test]
    fn error_test_no_patterns() {
        let source = fixture("t103_violation.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t103_violation.rs");
        assert!(
            !fa.has_error_test,
            "no error patterns should set has_error_test=false"
        );
    }

    #[test]
    fn error_test_is_err_only_not_sufficient() {
        let source = fixture("t103_is_err_only.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t103_is_err_only.rs");
        assert!(
            !fa.has_error_test,
            ".is_err() alone should not count as error test (weak proxy)"
        );
    }

    #[test]
    fn query_capture_names_error_test() {
        let q = make_query(include_str!("../queries/error_test.scm"));
        assert!(
            q.capture_index_for_name("error_test").is_some(),
            "error_test.scm must define @error_test capture"
        );
    }

    // --- T105: deterministic-no-metamorphic ---

    #[test]
    fn relational_assertion_pass_contains() {
        let source = fixture("t105_pass.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t105_pass.rs");
        assert!(
            fa.has_relational_assertion,
            ".contains() should set has_relational_assertion"
        );
    }

    #[test]
    fn relational_assertion_violation() {
        let source = fixture("t105_violation.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t105_violation.rs");
        assert!(
            !fa.has_relational_assertion,
            "only assert_eq! should not set has_relational_assertion"
        );
    }

    #[test]
    fn query_capture_names_relational_assertion() {
        let q = make_query(include_str!("../queries/relational_assertion.scm"));
        assert!(
            q.capture_index_for_name("relational").is_some(),
            "relational_assertion.scm must define @relational capture"
        );
    }

    // --- T101: how-not-what ---

    #[test]
    fn how_not_what_expect_method() {
        let source = fixture("t101_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t101_violation.rs");
        assert!(
            funcs[0].analysis.how_not_what_count > 0,
            "mock.expect_save() should trigger how_not_what, got {}",
            funcs[0].analysis.how_not_what_count
        );
    }

    #[test]
    fn how_not_what_pass() {
        let source = fixture("t101_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t101_pass.rs");
        assert_eq!(
            funcs[0].analysis.how_not_what_count, 0,
            "no mock patterns should have how_not_what_count=0"
        );
    }

    #[test]
    fn how_not_what_private_field_limited_by_token_tree() {
        // Rust macro arguments are token_tree (not AST), so field_expression
        // with _name inside assert_eq!() is not detectable.
        // Private field access outside macros IS detected as field_expression,
        // but count_captures_within_context requires it to be inside an
        // assertion node (macro_invocation), which doesn't contain field_expression.
        let source = fixture("t101_private_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t101_private_violation.rs");
        assert_eq!(
            funcs[0].analysis.how_not_what_count, 0,
            "Rust token_tree limitation: private field access in test is not detected"
        );
    }

    #[test]
    fn query_capture_names_how_not_what() {
        let q = make_query(include_str!("../queries/how_not_what.scm"));
        assert!(
            q.capture_index_for_name("how_pattern").is_some(),
            "how_not_what.scm must define @how_pattern capture"
        );
    }

    #[test]
    fn query_capture_names_private_in_assertion() {
        let q = make_query(include_str!("../queries/private_in_assertion.scm"));
        assert!(
            q.capture_index_for_name("private_access").is_some(),
            "private_in_assertion.scm must define @private_access capture"
        );
    }

    // --- T102: fixture-sprawl ---

    #[test]
    fn fixture_count_for_violation() {
        let source = fixture("t102_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t102_violation.rs");
        assert_eq!(
            funcs[0].analysis.fixture_count, 7,
            "expected 7 let bindings as fixture_count"
        );
    }

    #[test]
    fn fixture_count_for_pass() {
        let source = fixture("t102_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t102_pass.rs");
        assert_eq!(
            funcs[0].analysis.fixture_count, 1,
            "expected 1 let binding as fixture_count"
        );
    }

    #[test]
    fn fixture_count_excludes_method_calls_on_locals() {
        let source = fixture("t102_method_chain.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t102_method_chain.rs");
        assert_eq!(
            funcs[0].analysis.fixture_count, 6,
            "scoped calls (3) + struct (1) + macro (1) + builder chain (1) = 6, method calls on locals excluded"
        );
    }

    // --- T108: wait-and-see ---

    #[test]
    fn wait_and_see_violation_sleep() {
        let source = fixture("t108_violation_sleep.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t108_violation_sleep.rs");
        assert!(!funcs.is_empty());
        for func in &funcs {
            assert!(
                func.analysis.has_wait,
                "test '{}' should have has_wait=true",
                func.name
            );
        }
    }

    #[test]
    fn wait_and_see_pass_no_sleep() {
        let source = fixture("t108_pass_no_sleep.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t108_pass_no_sleep.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            !funcs[0].analysis.has_wait,
            "test without sleep should have has_wait=false"
        );
    }

    #[test]
    fn query_capture_names_wait_and_see() {
        let q = make_query(include_str!("../queries/wait_and_see.scm"));
        assert!(
            q.capture_index_for_name("wait").is_some(),
            "wait_and_see.scm must define @wait capture"
        );
    }

    // --- T107: assertion-roulette ---

    #[test]
    fn t107_violation_no_messages() {
        let source = fixture("t107_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t107_violation.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.assertion_count >= 2,
            "should have multiple assertions"
        );
        assert_eq!(
            funcs[0].analysis.assertion_message_count, 0,
            "no assertion should have a message"
        );
    }

    #[test]
    fn t107_pass_with_messages() {
        let source = fixture("t107_pass_with_messages.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t107_pass_with_messages.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.assertion_message_count >= 1,
            "assertions with messages should be counted"
        );
    }

    // --- T109: undescriptive-test-name ---

    #[test]
    fn t109_violation_names_detected() {
        let source = fixture("t109_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t109_violation.rs");
        assert!(!funcs.is_empty());
        for func in &funcs {
            assert!(
                exspec_core::rules::is_undescriptive_test_name(&func.name),
                "test '{}' should be undescriptive",
                func.name
            );
        }
    }

    #[test]
    fn t109_pass_descriptive_names() {
        let source = fixture("t109_pass.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t109_pass.rs");
        assert!(!funcs.is_empty());
        for func in &funcs {
            assert!(
                !exspec_core::rules::is_undescriptive_test_name(&func.name),
                "test '{}' should be descriptive",
                func.name
            );
        }
    }

    // --- T106: duplicate-literal-assertion ---

    #[test]
    fn t106_violation_duplicate_literal() {
        let source = fixture("t106_violation.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t106_violation.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.duplicate_literal_count >= 3,
            "42 appears 3 times, should be >= 3: got {}",
            funcs[0].analysis.duplicate_literal_count
        );
    }

    #[test]
    fn t106_pass_no_duplicates() {
        let source = fixture("t106_pass_no_duplicates.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t106_pass_no_duplicates.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.duplicate_literal_count < 3,
            "each literal appears once: got {}",
            funcs[0].analysis.duplicate_literal_count
        );
    }

    // --- T001 FP fix: #[should_panic] as assertion (#25) ---

    #[test]
    fn t001_should_panic_counts_as_assertion() {
        // TC-09: #[should_panic] only -> T001 should NOT fire
        let source = fixture("t001_should_panic.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_should_panic.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.assertion_count >= 1,
            "#[should_panic] should count as assertion, got {}",
            funcs[0].analysis.assertion_count
        );
    }

    #[test]
    fn t001_should_panic_before_test_counts_as_assertion() {
        // TC-09c: #[should_panic] BEFORE #[test] -> T001 should NOT fire
        let source = fixture("t001_should_panic_before_test.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_should_panic_before_test.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.assertion_count >= 1,
            "#[should_panic] before #[test] should count as assertion, got {}",
            funcs[0].analysis.assertion_count
        );
    }

    #[test]
    fn t001_should_panic_in_mod_counts_as_assertion() {
        // TC-09b: #[should_panic] inside mod tests {} -> T001 should NOT fire
        let source = fixture("t001_should_panic_in_mod.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_should_panic_in_mod.rs");
        assert_eq!(funcs.len(), 1);
        assert!(
            funcs[0].analysis.assertion_count >= 1,
            "#[should_panic] in mod should count as assertion, got {}",
            funcs[0].analysis.assertion_count
        );
    }

    #[test]
    fn t001_should_panic_substring_not_matched() {
        // TC-09d: #[my_should_panic_wrapper] should NOT count as #[should_panic]
        // Substring match was tightened to exact identifier match (#29)
        let source = fixture("t001_should_panic_substring_no_match.rs");
        let extractor = RustExtractor::new();
        let funcs =
            extractor.extract_test_functions(&source, "t001_should_panic_substring_no_match.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 0,
            "#[my_should_panic_wrapper] should NOT count as assertion (exact match only), got {}",
            funcs[0].analysis.assertion_count
        );
    }

    // --- Phase 22: custom assert macro auto-detection ---

    #[test]
    fn tc01_assert_pending_macro_counted_as_assertion() {
        // TC-01: assert_pending!(val) should be counted as assertion
        let source = fixture("t001_pass_custom_assert_macro.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass_custom_assert_macro.rs");
        let func = funcs
            .iter()
            .find(|f| f.name == "test_with_assert_pending")
            .expect("test_with_assert_pending not found");
        assert!(
            func.analysis.assertion_count >= 1,
            "assert_pending! should be counted as assertion, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn tc02_assert_ready_ok_macro_counted_as_assertion() {
        // TC-02: assert_ready_ok!(future) should be counted as assertion
        let source = fixture("t001_pass_custom_assert_macro.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass_custom_assert_macro.rs");
        let func = funcs
            .iter()
            .find(|f| f.name == "test_with_assert_ready_ok")
            .expect("test_with_assert_ready_ok not found");
        assert!(
            func.analysis.assertion_count >= 1,
            "assert_ready_ok! should be counted as assertion, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn tc03_assert_data_eq_macro_counted_as_assertion() {
        // TC-03: assert_data_eq!(actual, expected) should be counted as assertion
        let source = fixture("t001_pass_custom_assert_macro.rs");
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "t001_pass_custom_assert_macro.rs");
        let func = funcs
            .iter()
            .find(|f| f.name == "test_with_assert_data_eq")
            .expect("test_with_assert_data_eq not found");
        assert!(
            func.analysis.assertion_count >= 1,
            "assert_data_eq! should be counted as assertion, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn tc04_standard_assert_macros_still_detected_regression() {
        // TC-04: assert!, assert_eq!, debug_assert!, prop_assert_eq! continue to be detected
        let source = "#[test]\nfn test_standard_asserts() {\n    assert!(true);\n    assert_eq!(1, 1);\n    assert_ne!(1, 2);\n    debug_assert!(true);\n    prop_assert_eq!(1, 1);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "regression_standard.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 5,
            "assert!, assert_eq!, assert_ne!, debug_assert!, prop_assert_eq! should all be counted, got {}",
            funcs[0].analysis.assertion_count
        );
    }

    #[test]
    fn tc05_assertion_macro_not_counted_as_assertion() {
        // TC-05: assertion!() should NOT be counted — prefix guard rejects non-assert macros
        let source = "#[test]\nfn test_with_assertion_macro() {\n    assertion!(x == 5);\n}\n";
        let extractor = RustExtractor::new();
        let funcs = extractor.extract_test_functions(&source, "assertion_macro.rs");
        assert_eq!(funcs.len(), 1);
        assert_eq!(
            funcs[0].analysis.assertion_count, 0,
            "assertion!() should NOT be counted as assertion, got {}",
            funcs[0].analysis.assertion_count
        );
    }

    // --- Same-file helper tracing (Phase 23a, TC-01 ~ TC-06) ---

    #[test]
    fn helper_tracing_tc01_delegates_to_helper_with_assertion() {
        // TC-01: test that calls a helper with assertion → assertion_count >= 1 after tracing
        // RED: apply_same_file_helper_tracing is a stub → assertion_count stays 0 → FAIL expected
        let source = fixture("t001_pass_helper_tracing.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t001_pass_helper_tracing.rs");
        let func = fa
            .functions
            .iter()
            .find(|f| f.name == "test_delegates_to_helper_with_assertion")
            .expect("test_delegates_to_helper_with_assertion not found");
        assert!(
            func.analysis.assertion_count >= 1,
            "TC-01: helper with assertion traced → assertion_count >= 1, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn helper_tracing_tc02_delegates_to_helper_without_assertion() {
        // TC-02: test that calls a helper WITHOUT assertion → assertion_count stays 0
        let source = fixture("t001_pass_helper_tracing.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t001_pass_helper_tracing.rs");
        let func = fa
            .functions
            .iter()
            .find(|f| f.name == "test_delegates_to_helper_without_assertion")
            .expect("test_delegates_to_helper_without_assertion not found");
        assert_eq!(
            func.analysis.assertion_count, 0,
            "TC-02: helper without assertion → assertion_count == 0, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn helper_tracing_tc03_has_own_assertion_and_calls_helper() {
        // TC-03: test with own assert_eq! → assertion_count >= 1 (direct assertion, no tracing needed)
        let source = fixture("t001_pass_helper_tracing.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t001_pass_helper_tracing.rs");
        let func = fa
            .functions
            .iter()
            .find(|f| f.name == "test_has_own_assertion_and_calls_helper")
            .expect("test_has_own_assertion_and_calls_helper not found");
        assert!(
            func.analysis.assertion_count >= 1,
            "TC-03: own assertion present → assertion_count >= 1, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn helper_tracing_tc04_calls_undefined_function() {
        // TC-04: calling a function not defined in the file → no crash, assertion_count stays 0
        let source = fixture("t001_pass_helper_tracing.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t001_pass_helper_tracing.rs");
        let func = fa
            .functions
            .iter()
            .find(|f| f.name == "test_calls_undefined_function")
            .expect("test_calls_undefined_function not found");
        assert_eq!(
            func.analysis.assertion_count, 0,
            "TC-04: undefined function call → no crash, assertion_count == 0, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn helper_tracing_tc05_two_hop_not_traced() {
        // TC-05: 2-hop helper (intermediate_helper → check_result) — only 1-hop traced.
        // intermediate_helper itself has no assertion → assertion_count stays 0
        let source = fixture("t001_pass_helper_tracing.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t001_pass_helper_tracing.rs");
        let func = fa
            .functions
            .iter()
            .find(|f| f.name == "test_two_hop_not_traced")
            .expect("test_two_hop_not_traced not found");
        assert_eq!(
            func.analysis.assertion_count, 0,
            "TC-05: 2-hop helper not traced → assertion_count == 0, got {}",
            func.analysis.assertion_count
        );
    }

    #[test]
    fn helper_tracing_tc06_all_functions_have_assertions_early_return() {
        // TC-06: when all functions already have assertion_count > 0,
        // apply_same_file_helper_tracing should early-return without extra cost.
        // We verify by calling apply_same_file_helper_tracing on a FileAnalysis
        // where all functions have assertion_count > 0 — counts must not change.
        use exspec_core::query_utils::apply_same_file_helper_tracing;
        use tree_sitter::Query;

        // Build a source where the only test has an assertion
        let source = "#[test]\nfn test_has_assertion() {\n    assert_eq!(1, 1);\n}\n";
        let extractor = RustExtractor::new();
        let mut fa = extractor.extract_file_analysis(source, "tc06.rs");

        // All functions already have assertion_count > 0
        assert!(
            fa.functions.iter().all(|f| f.analysis.assertion_count > 0),
            "TC-06 precondition: all functions must have assertion_count > 0"
        );

        // Prepare stub queries (content does not matter since stub does nothing)
        let language = tree_sitter_rust::LANGUAGE;
        let lang: tree_sitter::Language = language.into();
        // Minimal valid queries for Rust
        let call_query =
            Query::new(&lang, "(call_expression function: (identifier) @call_name)").unwrap();
        let def_query = Query::new(
            &lang,
            "(function_item name: (identifier) @def_name body: (block) @def_body)",
        )
        .unwrap();
        let assertion_query =
            Query::new(&lang, "(macro_invocation macro: (identifier) @assertion)").unwrap();

        let mut parser = RustExtractor::parser();
        let tree = parser.parse(source, None).unwrap();

        let before: Vec<usize> = fa
            .functions
            .iter()
            .map(|f| f.analysis.assertion_count)
            .collect();

        apply_same_file_helper_tracing(
            &mut fa,
            &tree,
            source.as_bytes(),
            &call_query,
            &def_query,
            &assertion_query,
        );

        let after: Vec<usize> = fa
            .functions
            .iter()
            .map(|f| f.analysis.assertion_count)
            .collect();

        assert_eq!(
            before, after,
            "TC-06: assertion_counts must not change when all > 0 (early return)"
        );
    }

    #[test]
    fn helper_tracing_tc07_multiple_calls_to_same_helper() {
        // TC-07: test that calls same helper multiple times
        // Should deduplicate and count helper assertions once, not once per call
        let source = fixture("t001_pass_helper_tracing.rs");
        let extractor = RustExtractor::new();
        let fa = extractor.extract_file_analysis(&source, "t001_pass_helper_tracing.rs");
        let func = fa
            .functions
            .iter()
            .find(|f| f.name == "test_calls_helper_twice")
            .expect("test_calls_helper_twice not found");

        // check_result has 1 assertion. Calling it twice should add 1, not 2.
        // Expected: assertion_count == 1 (deduplicated)
        // Current bug: assertion_count == 2 (counted per call)
        assert_eq!(
            func.analysis.assertion_count, 1,
            "TC-07: multiple calls to same helper should be deduplicated, got {}",
            func.analysis.assertion_count
        );
    }
}