rapx 0.7.39

A static analysis platform for Rust program analysis and verification
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
//! Discovery of verification targets and their contract obligations.
//!
//! `VerifyTargetCollector` walks the crate's HIR (in `targeted` or `scan`
//! mode), and for each candidate assembles a [`FunctionTarget`]: unsafe
//! call-site checkpoints with per-callee preconditions, raw-pointer/static-mut
//! synthetic checkpoints, struct invariants, and std type invariants.

use crate::analysis::Analysis;
use crate::analysis::safety_flow::root::{
    function_has_struct_invariant, function_has_trait_ensurance, hir_contains_unsafe,
};
use crate::cli::VerifyMode;
use crate::compat::FxHashMap;
use crate::helpers::mir_scan::{collect_raw_ptr_deref_info, collect_static_mut_access_info};
use crate::helpers::name::short_fn_name;
#[cfg(not(rapx_ge_100))]
use rustc_hir::LangItem;
#[cfg(rapx_ge_100)]
use rustc_hir::attrs::lang_items::LangItem;
use rustc_hir::{
    Attribute, BodyId, FnDecl, ItemKind,
    def_id::{DefId, LocalDefId},
    intravisit::{FnKind, Visitor},
};
use rustc_middle::{hir::nested_filter, ty::TyCtxt};
use rustc_span::Span;
use std::collections::{HashMap, HashSet};

use super::{
    contract::{
        ContractExpr, ContractPlace, PlaceBase, Property, PropertyArg, PropertyKind,
        attr::parse_rapx_attr,
    },
    path_extractor::PathExtractor,
    type_invariants::build_type_invariants_from_params,
};
use crate::helpers::fn_info::get_adt_def_id_by_adt_method;
use crate::helpers::mir_scan::{Checkpoint, collect_unsafe_callsites};
use crate::helpers::mir_utils::{
    collect_return_block_indices, has_rapx_verify_attr, is_std_crate_def_id, is_trait_unsafe,
    resolve_impl_self_ty_def_id,
};

/// A list of parsed `requires` contracts.
pub(crate) type FnContracts<'tcx> = Vec<Property<'tcx>>;

/// A list of parsed struct invariants.
pub(crate) type StructInvariants<'tcx> = Vec<Property<'tcx>>;

/// Collected verification data for a single function under analysis.
///
/// `FunctionTarget` is the complete **problem statement** for one function: it
/// records every unsafe operation found in the function's MIR body, the safety
/// contracts that each operation demands, and any contracts or invariants that
/// serves as entry assumptions or structural guarantees.
///
/// # How it is built
///
/// [`VerifyTargetCollector::build_function_target`] assembles a `FunctionTarget`
/// in one pass over the MIR body:
///
/// 1. Unsafe checkpoints are collected via [`collect_unsafe_callsites`].
/// 2. Each unique callee `DefId` gets its `#[rapx::requires]` contracts parsed
///    (with fallback to bundled JSON contracts for standard-library callees).
/// 3. Raw pointer dereferences are detected and converted into synthetic
///    (pseudo-checkpoint, `[ValidPtr, Align, (Typed)]`) pairs.
/// 4. The caller's own `#[rapx::requires]` contracts become entry assumptions.
/// 5. If the function is a method on a struct, struct-level `#[rapx::invariant]`
///    and `#[rapx::requires]` annotations are collected.
///
/// # Role in the pipeline
///
/// The [`VerifyDriver`](super::driver::VerifyDriver) consumes a `FunctionTarget`
/// to route each unsafe operation to the verifier engine along reachability paths
/// extracted from the MIR CFG.  The target is the primary data carrier between
/// the *target collection* stage and the *path extraction / verification* stage.
#[derive(Clone, Debug)]
pub(crate) struct FunctionTarget<'tcx> {
    /// The function being verified.
    pub def_id: DefId,

    /// Owning struct when this function is an associated method (e.g.
    /// `impl MyStruct { fn foo(...) }`).  `None` for free functions.
    ///
    /// Used to associate struct invariants and to group method-level
    /// verification results under the owning struct in diagnostic output.
    pub owner_struct_def_id: Option<DefId>,

    /// All call-terminator-based unsafe checkpoints found in this function's MIR.
    ///
    /// Each [`Checkpoint`] records the callee `DefId`, the source-span of the
    /// call, the basic-block location, and the MIR operands passed as arguments.
    pub checkpoints: Vec<Checkpoint<'tcx>>,

    /// Safety contracts demanded by each unique unsafe callee reachable from
    /// this function, keyed by callee `DefId`.
    ///
    /// Contracts are sourced from `#[rapx::requires(...)]` annotations on the
    /// callee (inline mode) or from a bundled JSON contract database for
    /// standard-library functions.  Each value is a `Vec<Property>` — the
    /// concrete safety requirements the callee expects its caller to satisfy.
    pub callee_requires: HashMap<DefId, FnContracts<'tcx>>,

    /// Safety contracts that the **caller itself** requires as entry
    /// assumptions, parsed from `#[rapx::requires(...)]` on this function.
    ///
    /// During verification the engine prepends these properties as *facts* that
    /// are assumed to hold at function entry, constraining the backward
    /// data-dependency analysis and forward simulation.
    pub caller_requires: FnContracts<'tcx>,

    /// Struct invariants that methods of the owning struct must maintain.
    ///
    /// Collected from `#[rapx::invariant(...)]` / `#[rapx::requires(...)]`
    /// annotations on the struct definition.  Checked at constructor return
    /// blocks and at all path endpoints for non-constructor methods.
    pub struct_invariants: Vec<Property<'tcx>>,

    /// Built-in type invariants (e.g. the synthesized `NonNull`/`Init`/`Alive`
    /// slice invariant for `&[T]`/`&mut [T]` receivers and returns).
    ///
    /// Like [`struct_invariants`](Self::struct_invariants), these are assumed
    /// at entry (via `caller_requires`) and re-proved at return so a mutation
    /// that breaks them (e.g. an out-of-bounds write) is caught even without a
    /// user-written `#[rapx::invariant]`.
    pub type_invariants: Vec<Property<'tcx>>,

    /// Raw pointer dereference checks with their required safety properties.
    ///
    /// Each entry is a `(Checkpoint, Vec<Property>)` pair where the `Checkpoint`
    /// carries a synthetic dummy `DefId` (so the path extractor can treat
    /// dereferences uniformly with checkpoints) and the properties encode the
    /// pointer-validity requirements: always [`Allocated`](PropertyKind::Allocated),
    /// [`InBound`](PropertyKind::InBound), and [`Align`](PropertyKind::Align);
    /// additionally [`Typed`](PropertyKind::Typed) when the dereference is a read.
    pub raw_ptr_deref_checks: Vec<(Checkpoint<'tcx>, Vec<Property<'tcx>>)>,

    /// Static mut access checks with their required safety properties.
    ///
    /// Each entry is a `(Checkpoint, Vec<Property>)` pair following the same
    /// pattern as [`raw_ptr_deref_checks`](Self::raw_ptr_deref_checks).  The
    /// properties are [`Allocated`](PropertyKind::Allocated),
    /// [`InBound`](PropertyKind::InBound), [`Align`](PropertyKind::Align),
    /// and [`Init`](PropertyKind::Init)
    /// (conservatively checked for both reads and writes).
    pub static_mut_checks: Vec<(Checkpoint<'tcx>, Vec<Property<'tcx>>)>,
}

impl<'tcx> FunctionTarget<'tcx> {
    pub(crate) fn all_checkpoints(&self) -> Vec<&Checkpoint<'tcx>> {
        self.checkpoints
            .iter()
            .chain(
                self.raw_ptr_deref_checks
                    .iter()
                    .map(|(checkpoint, _)| checkpoint),
            )
            .chain(
                self.static_mut_checks
                    .iter()
                    .map(|(checkpoint, _)| checkpoint),
            )
            .collect()
    }

    pub(crate) fn properties_for_callsite(
        &self,
        checkpoint: &Checkpoint<'tcx>,
    ) -> &[Property<'tcx>] {
        let loc = checkpoint.location();
        match checkpoint.kind {
            crate::helpers::mir_scan::CheckpointKind::RawPtrDeref => self
                .raw_ptr_deref_checks
                .iter()
                .find(|(candidate, _)| candidate.location() == loc)
                .map(|(_, properties)| properties.as_slice())
                .unwrap_or(&[]),
            crate::helpers::mir_scan::CheckpointKind::StaticMutAccess => self
                .static_mut_checks
                .iter()
                .find(|(candidate, _)| candidate.location() == loc)
                .map(|(_, properties)| properties.as_slice())
                .unwrap_or(&[]),
            crate::helpers::mir_scan::CheckpointKind::UnsafeCall => checkpoint
                .callee
                .and_then(|callee| self.callee_requires.get(&callee))
                .map(Vec::as_slice)
                .unwrap_or(&[]),
        }
    }
}

/// Collected verification data for a struct that owns methods marked with `#[rapx::verify]`.
pub(crate) struct StructTarget<'tcx> {
    /// Struct that owns one or more methods selected as targets to verify.
    pub def_id: DefId,
    /// Parsed `invariant` contracts attached to the struct.
    pub invariants: StructInvariants<'tcx>,
    /// Methods of this struct selected as targets to verify.
    pub function_targets: Vec<FunctionTarget<'tcx>>,
}

/// Collected verification data for an `impl unsafe Trait for Type` block.
///
/// Covers two cases, distinguished by whether the trait has methods:
/// - marker traits (`Send`/`Sync`) carry *type-level* obligations, and
/// - unsafe traits with methods carry *method-level* `ensures` contracts
///   (verification deferred).
pub(crate) struct TraitEnsurance<'tcx> {
    /// The trait being implemented.
    pub def_id: DefId,
    /// The `impl ... for Type` block's DefId (carries the impl's generic bounds,
    /// e.g. `T: Send`).
    pub impl_def_id: DefId,
    /// The concrete type that implements the trait (e.g. `SomeStruct`).
    pub self_ty_def_id: Option<DefId>,
    /// The obligations to verify, keyed by whether the trait has methods.
    pub kind: TraitEnsuranceKind<'tcx>,
}

/// What a [`TraitEnsurance`] must verify.
pub(crate) enum TraitEnsuranceKind<'tcx> {
    /// A marker trait (`Send`/`Sync`, no methods): type-level obligations
    /// generated from the bundled `std-trait-ensures.json` template.
    Marker(MarkerTraitKind, Vec<Property<'tcx>>),
    /// An unsafe trait with methods: `ensures` contracts grouped by method name.
    Unsafe(Vec<(String, FnContracts<'tcx>)>),
}

/// Which marker trait an `unsafe impl` is claiming safety for.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum MarkerTraitKind {
    Send,
    Sync,
}

/// Follow an unsafe callee's call chain to find inherited safety contracts.
///
/// When an unsafe callee (e.g. B) lacks its own contracts, look into its MIR
/// body for the unsafe callees it calls (e.g. C, D).  If one of those has
/// contracts (e.g. D), inherit them.  The chain `A -> B -> C -> D` means A's
/// checkpoint on B is verified using D's contracts.
///
/// `visited` prevents infinite recursion on mutually-recursive functions.
fn resolve_chain_contracts<'tcx>(
    tcx: TyCtxt<'tcx>,
    callee_def_id: DefId,
    visited: &mut HashSet<DefId>,
) -> FnContracts<'tcx> {
    if !visited.insert(callee_def_id) {
        return Vec::new();
    }

    if !tcx.is_mir_available(callee_def_id) {
        return Vec::new();
    }

    let body = tcx.optimized_mir(callee_def_id);
    let mut contracts = Vec::new();

    for bb in body.basic_blocks.iter() {
        let Some(terminator) = &bb.terminator else {
            continue;
        };
        if let rustc_middle::mir::TerminatorKind::Call { func, .. } = &terminator.kind {
            if let rustc_middle::mir::Operand::Constant(c) = func {
                let rustc_middle::ty::TyKind::FnDef(sub_def_id, _) = c.const_.ty().kind() else {
                    continue;
                };
                let sub_def_id = *sub_def_id;

                let fn_sig = tcx.fn_sig(sub_def_id).skip_binder();
                if fn_sig.safety() != rustc_hir::Safety::Unsafe {
                    continue;
                }

                // Try annotation first.
                let mut reqs = get_contract_from_annotation(tcx, sub_def_id);

                // Try trait method requires.
                if reqs.is_empty() {
                    reqs = get_trait_method_requires(tcx, sub_def_id);
                }

                // Try std contracts database.
                if reqs.is_empty() && is_std_crate_def_id(tcx, sub_def_id) {
                    reqs = super::contract::json::query_json_contracts(tcx, sub_def_id);
                }

                // If still no contracts, recurse into this callee.
                if reqs.is_empty() {
                    reqs = resolve_chain_contracts(tcx, sub_def_id, visited);
                }

                contracts.extend(reqs);
            }
        }
    }

    contracts
}

/// Visitor that collects targets annotated with `#[rapx::verify]`.
pub(crate) struct VerifyTargetCollector<'tcx> {
    tcx: TyCtxt<'tcx>,
    mode: VerifyMode,
    skip_invariant: bool,
    crate_filter: Option<String>,
    crate_filter_matched: bool,
    module_filter: Option<String>,
    module_filter_matched: bool,
    /// All function targets to verify collected from the current crate.
    pub function_targets: Vec<FunctionTarget<'tcx>>,
    /// All struct targets to verify collected from the current crate.
    pub struct_targets: HashMap<DefId, StructTarget<'tcx>>,
    /// All trait impls to verify (marker traits and unsafe traits), one entry
    /// per `impl` block.
    pub trait_targets: Vec<TraitEnsurance<'tcx>>,
    /// Cached contracts for each callee function so repeated callees are parsed once.
    fn_contract_cache: HashMap<DefId, FnContracts<'tcx>>,
}

impl<'tcx> VerifyTargetCollector<'tcx> {
    /// Collect all verification targets across the current crate and optionally
    /// external crates (when `crate_filter` is set).
    pub(crate) fn collect_all(
        tcx: TyCtxt<'tcx>,
        mode: VerifyMode,
        skip_invariant: bool,
        crate_filter: Option<String>,
        module_filter: Option<String>,
    ) -> Self {
        let mut collector = Self::new(
            tcx,
            mode,
            skip_invariant,
            crate_filter.clone(),
            module_filter,
        );
        tcx.hir_visit_all_item_likes_in_crate(&mut collector);
        if crate_filter.is_some() {
            collector.collect_extern_crate_targets();
        }
        collector.check_module_filter_result();
        collector
    }

    /// Creates a new collector for the current type context.
    pub(crate) fn new(
        tcx: TyCtxt<'tcx>,
        mode: VerifyMode,
        skip_invariant: bool,
        crate_filter: Option<String>,
        module_filter: Option<String>,
    ) -> Self {
        VerifyTargetCollector {
            tcx,
            mode,
            skip_invariant,
            crate_filter,
            crate_filter_matched: false,
            module_filter,
            module_filter_matched: false,
            function_targets: Vec::new(),
            struct_targets: HashMap::new(),
            trait_targets: Vec::new(),
            fn_contract_cache: HashMap::new(),
        }
    }

    /// Returns (and caches) the contracts for an unsafe callee.
    ///
    /// Contracts are resolved with the following priority:
    /// 1. Inline RAPx annotations attached to the callee.
    /// 2. If the callee is a trait method impl without its own annotations,
    ///    fall back to the trait method's `#[rapx::requires(...)]`.
    /// 3. If no annotations are found and the callee belongs to the standard
    ///    library, fall back to the bundled JSON contract database.
    ///
    /// Results are memoized in `fn_contract_cache` to avoid recomputation.
    fn get_fn_contracts(&mut self, callee_def_id: DefId) -> FnContracts<'tcx> {
        let is_std = is_std_crate_def_id(self.tcx, callee_def_id);

        let trait_requires = get_trait_method_requires(self.tcx, callee_def_id);

        self.fn_contract_cache
            .entry(callee_def_id)
            .or_insert_with(|| {
                let mut requires = get_contract_from_annotation(self.tcx, callee_def_id);

                if requires.is_empty() && !trait_requires.is_empty() {
                    requires = trait_requires.clone();
                }

                if requires.is_empty() && is_std {
                    requires = super::contract::json::query_json_contracts(
                        self.tcx,
                        callee_def_id,
                    );

                if requires.is_empty() {
                    // Recursively resolve contracts from the callee's call chain.
                    // e.g. A -> B -> C -> D where B,C are unsafe unannotated,
                    // D has contracts; follow the chain to D and use its contracts.
                    let mut visited = HashSet::new();
                    requires = resolve_chain_contracts(
                        self.tcx,
                        callee_def_id,
                        &mut visited,
                    );
                    if requires.is_empty() {
                        let path = crate::helpers::name::get_cleaned_def_path_name(
                            self.tcx,
                            callee_def_id,
                        );
                        rap_warn!(
                            "no safety contracts found for callee \"{path}\""
                        );
                    } else {
                        let path = crate::helpers::name::get_cleaned_def_path_name(
                            self.tcx,
                            callee_def_id,
                        );
                        rap_debug!(
                            "resolved {} safety contract(s) for callee \"{path}\" via call chain",
                            requires.len()
                        );
                    }
                }
                }

                if requires.is_empty() {
                    requires.push(Property::new(
                        self.tcx,
                        callee_def_id,
                        "Unknown",
                        &[],
                    ));
                }

                requires
            })
            .clone()
    }

    /// Builds a function target to verify from a function definition.
    fn build_function_target(&mut self, def_id: DefId) -> FunctionTarget<'tcx> {
        let checkpoints = collect_unsafe_callsites(self.tcx, def_id);
        let unsafe_callees: HashSet<_> = checkpoints
            .iter()
            .filter_map(|checkpoint| checkpoint.callee)
            .collect();
        let callee_requires = unsafe_callees
            .iter()
            .map(|callee_def_id| {
                let mut contracts = self.get_fn_contracts(*callee_def_id);
                contracts.retain(|p| {
                    !matches!(
                        p.kind(),
                        Some(crate::verify::contract::PropertyKind::Unknown)
                    )
                });
                (*callee_def_id, contracts)
            })
            .collect();

        let mut caller_requires = self.get_fn_contracts(def_id);
        // `get_fn_contracts` already resolves the entry contracts with the
        // right precedence — inline `#[rapx::requires]`, then trait contracts,
        // then the std JSON database (only when no annotation is present).
        // Querying JSON again here would duplicate the annotation.

        let raw_ptr_deref_checks = build_raw_ptr_deref_checks(self.tcx, def_id);
        let static_mut_checks = build_static_mut_checks(self.tcx, def_id);

        let owner_struct_def_id = get_adt_def_id_by_adt_method(self.tcx, def_id);
        let mut struct_invariants = owner_struct_def_id
            .map(|struct_def_id| {
                get_struct_invariants_from_annotation(self.tcx, struct_def_id, def_id)
            })
            .unwrap_or_default();

        // Struct invariants are implicit preconditions for every method:
        // safe methods need them as automatic entry facts (no requires
        // needed), and unsafe constructors verify they hold at return.
        caller_requires.extend(struct_invariants.clone());

        // drop is a destructor — the struct is being torn down, so we skip
        // struct invariant checks at exit points.
        if is_drop_impl(self.tcx, def_id) {
            struct_invariants.clear();
        }

        // Standard-library type invariants: for each function parameter (and
        // the return type), look up the type's invariants from
        // std-type-invariants.json (including the built-in `[T]` slice key)
        // and add them as preconditions.
        let type_invariants = build_type_invariants_from_params(self.tcx, def_id);
        caller_requires.extend(type_invariants.clone());

        FunctionTarget {
            def_id,
            owner_struct_def_id,
            checkpoints,
            callee_requires,
            caller_requires,
            struct_invariants,
            type_invariants,
            raw_ptr_deref_checks,
            static_mut_checks,
        }
    }

    /// Adds a function target and updates its owning struct target when applicable.
    fn push_function_target(&mut self, function_target: FunctionTarget<'tcx>) {
        self.function_targets.push(function_target.clone());

        if let Some(struct_def_id) = function_target.owner_struct_def_id {
            self.struct_targets
                .entry(struct_def_id)
                .or_insert_with(|| StructTarget {
                    def_id: struct_def_id,
                    invariants: get_struct_invariants_from_annotation(
                        self.tcx,
                        struct_def_id,
                        function_target.def_id,
                    ),
                    function_targets: Vec::new(),
                })
                .function_targets
                .push(function_target);
        }
    }

    /// Process MIR keys from non-local crates that match the `--crate` filter.
    ///
    /// `hir_visit_all_item_likes_in_crate` only visits the *local* crate, but
    /// in a workspace the target crate (e.g. `core`) may be compiled as a
    /// dependency of another crate (e.g. `std`).  This method iterates all
    /// crates' MIR bodies and collects targets from those matching the filter.
    fn collect_extern_crate_targets(&mut self) {
        let local_crate = rustc_hir::def_id::LOCAL_CRATE;

        for def_id in self.tcx.mir_keys(()) {
            let def_id = def_id.to_def_id();
            if def_id.krate == local_crate {
                continue; // already visited via the HIR visitor
            }
            if !self.crate_name_matches(def_id) {
                continue;
            }
            let def_kind = self.tcx.def_kind(def_id);
            if !matches!(
                def_kind,
                rustc_hir::def::DefKind::Fn | rustc_hir::def::DefKind::AssocFn
            ) {
                continue;
            }

            // Skip `targeted` mode filtering — non-local crates don't have
            // HIR attributes available (only metadata is present).
            if matches!(self.mode, VerifyMode::Targeted) {
                continue;
            }

            self.crate_filter_matched = true;

            if !self.module_path_matches(def_id) {
                continue;
            }
            self.module_filter_matched = true;

            let function_target = self.build_function_target(def_id);
            self.push_function_target(function_target);
        }
    }

    fn crate_name_matches(&self, def_id: DefId) -> bool {
        match self.crate_filter {
            None => true,
            Some(ref filter) => {
                let crate_name = self.tcx.crate_name(def_id.krate);
                if crate_name.as_str() == *filter {
                    return true;
                }
                if let Ok(pkg_name) = std::env::var("CARGO_PKG_NAME") {
                    if pkg_name == *filter {
                        return true;
                    }
                }
                false
            }
        }
    }

    fn module_path_matches(&self, def_id: DefId) -> bool {
        let Some(ref filter) = self.module_filter else {
            return true;
        };
        let def_path = self.tcx.def_path_str(def_id);

        if def_path == *filter || def_path.starts_with(&format!("{}::", filter)) {
            return true;
        }
        let crate_name = self.tcx.crate_name(def_id.krate);
        let crate_prefix = format!("{}::", crate_name.as_str());

        // Try matching filter after stripping the crate prefix.
        // e.g. filter "slice" matches def_path "core::slice::raw::from_raw_parts"
        // after stripping "core::".
        if let Some(inner) = filter.strip_prefix(&crate_prefix) {
            if def_path == inner || def_path.starts_with(&format!("{}::", inner)) {
                return true;
            }
        }

        // Try matching def_path after stripping the crate prefix.
        // e.g. filter "core::slice" matches def_path "slice::raw::from_raw_parts"
        // after stripping "core::" from the filter.
        if let Some(inner) = def_path.strip_prefix(&crate_prefix) {
            if inner == *filter || inner.starts_with(&format!("{}::", filter)) {
                return true;
            }
        }

        false
    }

    pub(crate) fn check_module_filter_result(&self) {
        if let Some(ref filter) = self.crate_filter {
            if !self.crate_filter_matched {
                rap_warn!("[rapx::verify] --crate \"{filter}\" matched no targets");
            }
        }
        if let Some(ref filter) = self.module_filter {
            if !self.module_filter_matched {
                rap_warn!("[rapx::verify] --module \"{filter}\" matched no functions in the crate");
            }
        }
    }
}

fn get_trait_method_requires<'tcx>(tcx: TyCtxt<'tcx>, callee_def_id: DefId) -> FnContracts<'tcx> {
    let Some(assoc_item) = tcx.opt_associated_item(callee_def_id) else {
        return Vec::new();
    };
    let Some(trait_item_def_id) = assoc_item.trait_item_def_id() else {
        return Vec::new();
    };
    get_contract_from_annotation(tcx, trait_item_def_id)
}

impl<'tcx> Visitor<'tcx> for VerifyTargetCollector<'tcx> {
    type NestedFilter = nested_filter::OnlyBodies;

    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
        self.tcx
    }

    /// Detect `impl unsafe Trait for Type` blocks and record them as
    /// [`TraitEnsurance`] placeholders.
    ///
    /// In `targeted` mode, only `impl` blocks annotated with `#[rapx::verify]`
    /// are recorded.  In `scan` mode, all `unsafe trait` impls
    /// are recorded.
    fn visit_item(&mut self, item: &'tcx rustc_hir::Item<'tcx>) {
        if let ItemKind::Impl(rustc_hir::Impl { of_trait, .. }) = &item.kind
            && of_trait.is_some()
        {
            if matches!(self.mode, VerifyMode::Targeted)
                && !has_rapx_verify_attr(self.tcx, item.owner_id.def_id)
            {
                rustc_hir::intravisit::walk_item(self, item);
                return;
            }

            let impl_def_id = item.owner_id.to_def_id();

            if !self.crate_name_matches(impl_def_id) {
                rustc_hir::intravisit::walk_item(self, item);
                return;
            }
            self.crate_filter_matched = true;

            if !self.module_path_matches(impl_def_id) {
                rustc_hir::intravisit::walk_item(self, item);
                return;
            }
            self.module_filter_matched = true;

            let trait_ref = { self.tcx.impl_opt_trait_ref(impl_def_id) };

            if let Some(trait_ref) = trait_ref {
                let trait_def_id = trait_ref.skip_binder().def_id;

                let self_ty_def_id = resolve_impl_self_ty_def_id(&item);

                // Marker traits (`Send`/`Sync`) carry type-level obligations;
                // unsafe traits with methods carry method-level `ensures`.
                if let Some(kind) = marker_trait_kind(self.tcx, trait_def_id) {
                    let obligations =
                        build_marker_trait_obligations(self.tcx, self_ty_def_id, kind);
                    self.trait_targets.push(TraitEnsurance {
                        def_id: trait_def_id,
                        impl_def_id,
                        self_ty_def_id,
                        kind: TraitEnsuranceKind::Marker(kind, obligations),
                    });
                } else if is_trait_unsafe(self.tcx, trait_def_id) {
                    let ensures = get_trait_contracts_from_annotation(self.tcx, trait_def_id);

                    self.trait_targets.push(TraitEnsurance {
                        def_id: trait_def_id,
                        impl_def_id,
                        self_ty_def_id,
                        kind: TraitEnsuranceKind::Unsafe(ensures),
                    });
                }
            }
        }

        rustc_hir::intravisit::walk_item(self, item);
    }

    /// Visits each function body and records verification targets.
    ///
    /// In `targeted` mode, only functions annotated with `#[rapx::verify]` are collected.
    /// In `scan` mode, a HIR-level pre-filter (`contains_unsafe`
    /// and `function_has_struct_invariant`) avoids expensive MIR scanning for functions
    /// that have no unsafe content and no struct invariants.
    fn visit_fn(
        &mut self,
        _fk: FnKind<'tcx>,
        _fd: &'tcx FnDecl<'tcx>,
        body_id: BodyId,
        _span: Span,
        id: LocalDefId,
    ) -> Self::Result {
        if matches!(self.mode, VerifyMode::Targeted) && !has_rapx_verify_attr(self.tcx, id) {
            // Drop impls on structs with invariants are implicitly verified.
            if !is_drop_impl(self.tcx, id.to_def_id()) {
                return;
            }
        }

        // HIR pre-filter: skip functions that have nothing to verify.
        // `contains_unsafe` catches functions with unsafe blocks/declarations;
        // `function_has_struct_invariant` catches methods on structs with invariants;
        // `function_has_trait_ensurance` catches methods on unsafe trait impls with contracts.
        let def_id = id.to_def_id();

        // Skip never-returning (divergent) functions — they have no return
        // paths and can trigger stack overflows in downstream analysis.
        if let rustc_hir::def::DefKind::Fn = self.tcx.def_kind(def_id) {
            let fn_sig = self.tcx.fn_sig(def_id).skip_binder();
            if matches!(
                fn_sig.output().skip_binder().kind(),
                rustc_type_ir::TyKind::Never
            ) {
                return;
            }
        }

        if !matches!(self.mode, VerifyMode::Targeted) {
            if !hir_contains_unsafe(self.tcx, body_id)
                && !function_has_struct_invariant(self.tcx, def_id)
                && !function_has_trait_ensurance(self.tcx, def_id)
            {
                return;
            }
        }

        let function_target = self.build_function_target(def_id);

        match self.mode {
            VerifyMode::Targeted => {}
            VerifyMode::Scan => {
                if function_target.checkpoints.is_empty()
                    && function_target.raw_ptr_deref_checks.is_empty()
                    && function_target.static_mut_checks.is_empty()
                {
                    if !function_target.struct_invariants.is_empty() {
                        if self.skip_invariant {
                            return;
                        }
                    } else {
                        let root = crate::analysis::safety_flow::root::scan_mir(self.tcx, def_id);
                        if root.is_none() {
                            return;
                        }
                    }
                }
            }
        }

        if !self.crate_name_matches(def_id) {
            return;
        }
        self.crate_filter_matched = true;

        if !self.module_path_matches(def_id) {
            return;
        }
        self.module_filter_matched = true;

        self.push_function_target(function_target);
    }
}

/// Analysis pass that finds all verification targets.
///
/// In `targeted` mode, only functions annotated with `#[rapx::verify]` are listed.
/// In `scan` mode, all functions with unsafe callees or struct invariants are listed.
pub(crate) struct PrepareTargets<'tcx> {
    tcx: TyCtxt<'tcx>,
    mode: VerifyMode,
    skip_invariant: bool,
    crate_filter: Option<String>,
    module_filter: Option<String>,
}

impl<'tcx> Analysis for PrepareTargets<'tcx> {
    fn run(&mut self) {
        let collector = VerifyTargetCollector::collect_all(
            self.tcx,
            self.mode,
            self.skip_invariant,
            self.crate_filter.clone(),
            self.module_filter.clone(),
        );

        // Free functions (no owning struct)
        let free_targets: Vec<_> = collector
            .function_targets
            .iter()
            .filter(|target| target.owner_struct_def_id.is_none())
            .collect();
        for target in &free_targets {
            let target_path = self.tcx.def_path_str(target.def_id);
            rap_info!("============================================================");
            rap_info!(
                "[rapx::verify] prepare targets for free function: {}",
                target_path
            );
            rap_info!("============================================================");
            self.log_free_function_unsafe_callees(target);
            rap_info!("");
        }

        // Structs with methods
        let mut struct_ids: Vec<_> = collector.struct_targets.keys().copied().collect();
        struct_ids.sort_by_key(|def_id| self.tcx.def_path_str(*def_id));

        for struct_def_id in struct_ids {
            let Some(struct_target) = collector.struct_targets.get(&struct_def_id) else {
                continue;
            };
            let struct_path = self.tcx.def_path_str(struct_target.def_id);

            rap_info!("============================================================");
            rap_info!("[rapx::verify] prepare targets for struct: {}", struct_path);
            rap_info!("============================================================");

            self.log_struct_invariants(struct_target);

            for target in &struct_target.function_targets {
                self.log_method_target(target);
            }
        }

        // Traits with impl methods
        let mut trait_targets: Vec<_> = collector.trait_targets.iter().collect();
        trait_targets.sort_by_key(|t| self.tcx.def_path_str(t.def_id));

        for trait_target in trait_targets {
            let trait_path = self.tcx.def_path_str(trait_target.def_id);

            match &trait_target.kind {
                TraitEnsuranceKind::Unsafe(_) => {
                    rap_info!("============================================================");
                    rap_info!(
                        "[rapx::verify] prepare targets for unsafe trait: {}",
                        trait_path
                    );
                    rap_info!("============================================================");

                    self.log_trait_ensurance(trait_target);
                }
                TraitEnsuranceKind::Marker(kind, obligations) => {
                    let name = match kind {
                        MarkerTraitKind::Send => "Send",
                        MarkerTraitKind::Sync => "Sync",
                    };
                    rap_info!("============================================================");
                    rap_info!(
                        "[rapx::verify] prepare targets for marker trait: {}",
                        name
                    );
                    rap_info!("============================================================");

                    self.log_marker_trait(trait_target, obligations);
                }
            }

            rap_info!("");
        }

        let total_free = free_targets.len();
        let total_method = collector
            .function_targets
            .iter()
            .filter(|target| target.owner_struct_def_id.is_some())
            .count();
        let total_struct = collector.struct_targets.len();
        let total_trait = collector.trait_targets.len();

        rap_info!("============================================================");
        rap_info!(
            "[rapx::verify] total: {} free function(s), {} method(s), {} struct(s), {} trait(s)",
            total_free,
            total_method,
            total_struct,
            total_trait
        );
        rap_info!("============================================================");
    }
}

impl<'tcx> PrepareTargets<'tcx> {
    pub(crate) fn new(
        tcx: TyCtxt<'tcx>,
        mode: VerifyMode,
        skip_invariant: bool,
        crate_filter: Option<String>,
        module_filter: Option<String>,
    ) -> Self {
        PrepareTargets {
            tcx,
            mode,
            skip_invariant,
            crate_filter,
            module_filter,
        }
    }

    fn log_struct_invariants(&self, struct_target: &StructTarget<'tcx>) {
        if struct_target.invariants.is_empty() {
            rap_info!("  struct invariants: <none>");
        } else {
            rap_info!("  struct invariants:");
            for property in
                crate::verify::display::dedup_compound_props(struct_target.invariants.iter())
            {
                rap_info!(
                    "    - {}",
                    property.display_for_report(self.tcx, Some(struct_target.def_id), None,)
                );
            }
        }
    }

    fn log_trait_ensurance(&self, trait_target: &TraitEnsurance<'tcx>) {
        if let Some(self_ty) = trait_target.self_ty_def_id {
            rap_info!("  impl for: {}", self.tcx.def_path_str(self_ty));
        }
        let TraitEnsuranceKind::Unsafe(ensures) = &trait_target.kind else {
            return;
        };
        if ensures.is_empty() {
            rap_info!("  ensures: <none>");
        } else {
            rap_info!("  ensures (implementor must satisfy):");
            for (method_name, contracts) in ensures {
                rap_info!("    fn {}:", method_name);
                for property in crate::verify::display::dedup_compound_props(contracts.iter()) {
                    let (call, _meaning) = crate::verify::display::fmt_contract_expanded(
                        self.tcx,
                        property,
                        trait_target.self_ty_def_id,
                        None,
                    );
                    rap_info!("      - {call}");
                }
            }
        }
    }

    fn log_marker_trait(&self, trait_target: &TraitEnsurance<'tcx>, obligations: &[Property<'tcx>]) {
        if let Some(self_ty) = trait_target.self_ty_def_id {
            rap_info!("  impl for: {}", self.tcx.def_path_str(self_ty));
        }
        if obligations.is_empty() {
            rap_info!("  obligations: <none>");
        } else {
            rap_info!("  obligations:");
            for property in obligations {
                let (call, _meaning) = crate::verify::display::fmt_contract_expanded(
                    self.tcx,
                    property,
                    trait_target.self_ty_def_id,
                    None,
                );
                rap_info!("    - {call}");
            }
        }
    }

    fn log_method_target(&self, target: &FunctionTarget<'tcx>) {
        let name = short_fn_name(self.tcx, target.def_id);
        let dashes = 62usize.saturating_sub(10 + name.len());
        rap_info!("  --- method: {name} {}", "-".repeat(dashes));

        let return_blocks = collect_return_block_indices(self.tcx, target.def_id);
        rap_info!(
            "      return checkpoints: {} block(s) {:?}",
            return_blocks.len(),
            return_blocks
                .iter()
                .map(|bb| bb.as_usize())
                .collect::<Vec<_>>()
        );

        let path_map = self.build_checkpoint_path_map(target);
        self.log_unsafe_callees_and_contracts(target, &path_map);
    }

    fn log_free_function_unsafe_callees(&self, target: &FunctionTarget<'tcx>) {
        let path_map = self.build_checkpoint_path_map(target);
        self.log_unsafe_callees_and_contracts(target, &path_map);
    }

    fn log_unsafe_callees_and_contracts(
        &self,
        target: &FunctionTarget<'tcx>,
        path_map: &FxHashMap<DefId, Vec<(usize, Vec<String>)>>,
    ) {
        if target.callee_requires.is_empty() {
            rap_info!("      unsafe checkpoints: <none>");
            return;
        }

        let mut unsafe_callee_ids: Vec<_> = target.callee_requires.keys().copied().collect();
        unsafe_callee_ids.sort_by_key(|def_id| self.tcx.def_path_str(*def_id));

        for unsafe_callee_def_id in unsafe_callee_ids {
            let fn_sig = self.tcx.fn_sig(unsafe_callee_def_id).skip_binder();
            let unsafe_callee_path = self.tcx.def_path_str(unsafe_callee_def_id);
            let inputs: Vec<String> = fn_sig
                .inputs()
                .skip_binder()
                .iter()
                .map(|ty| format!("{}", ty))
                .collect();
            let output = format!("{}", fn_sig.output().skip_binder());
            rap_info!(
                "      unsafe callee: {}({}) -> {}",
                unsafe_callee_path,
                inputs.join(", "),
                output,
            );

            if let Some(requires) = target.callee_requires.get(&unsafe_callee_def_id) {
                if requires.is_empty() {
                    rap_info!("        safety contracts: <none>");
                } else {
                    rap_info!("        safety contracts:");
                    for property in crate::verify::display::dedup_compound_props(requires.iter()) {
                        rap_info!(
                            "          - {}",
                            property.display_for_report(
                                self.tcx,
                                target.owner_struct_def_id,
                                Some(unsafe_callee_def_id),
                            )
                        );
                    }
                }
            }

            if let Some(path_entries) = path_map.get(&unsafe_callee_def_id) {
                for (_block_idx, path_strings) in path_entries {
                    if path_strings.is_empty() {
                        rap_info!("        path: <none>");
                    } else {
                        for desc in path_strings {
                            rap_info!("        path: shortest path: {desc}");
                        }
                    }
                }
            }
        }
    }

    fn build_checkpoint_path_map(
        &self,
        target: &FunctionTarget<'tcx>,
    ) -> FxHashMap<DefId, Vec<(usize, Vec<String>)>> {
        let mut path_map: FxHashMap<DefId, Vec<(usize, Vec<String>)>> = FxHashMap::default();

        if target.checkpoints.is_empty() {
            return path_map;
        }

        let groups =
            PathExtractor::new(self.tcx, target.def_id, target.checkpoints.clone(), 0).run();

        for group in &groups {
            for checkpoint in &group.checkpoints {
                if let Some(callee_def_id) = checkpoint.callee {
                    let block_idx = checkpoint.block.as_usize();
                    let mut path_strings: Vec<String> = Vec::new();
                    let _ = group.tree.walk_prefixes(
                        checkpoint.block.as_usize(),
                        &mut |prefix: &[usize]| -> bool {
                            let desc = prefix
                                .iter()
                                .map(usize::to_string)
                                .collect::<Vec<_>>()
                                .join(" -> ");
                            path_strings.push(desc);
                            true
                        },
                    );

                    path_map
                        .entry(callee_def_id)
                        .or_insert_with(Vec::new)
                        .push((block_idx, path_strings));
                }
            }
        }

        path_map
    }
}

fn is_rapx_named_attr(attr: &Attribute, name: &str) -> bool {
    let path = attr.path();
    if path.len() >= 2
        && path[path.len() - 2].as_str() == "rapx"
        && path[path.len() - 1].as_str() == name
    {
        return true;
    }
    // In newer rustc, tool attrs may have the tool prefix stripped from the path.
    // Match bare name when the attribute has exactly one path segment.
    path.len() == 1 && path[0].as_str() == name
}

/// Resolve whether an `unsafe impl` is implementing the `Send`/`Sync` marker trait.
fn marker_trait_kind(tcx: TyCtxt<'_>, trait_def_id: DefId) -> Option<MarkerTraitKind> {
    if tcx.get_diagnostic_item(rustc_span::sym::Send) == Some(trait_def_id) {
        Some(MarkerTraitKind::Send)
    } else if tcx.get_diagnostic_item(rustc_span::sym::Sync) == Some(trait_def_id) {
        Some(MarkerTraitKind::Sync)
    } else {
        None
    }
}

/// Generate the type-level `ensures` obligations for a marker-trait impl from
/// the bundled `std-trait-ensures.json` template, substituting `ty:Self` with
/// the implementing type.
fn build_marker_trait_obligations<'tcx>(
    tcx: TyCtxt<'tcx>,
    self_ty_def_id: Option<DefId>,
    trait_kind: MarkerTraitKind,
) -> Vec<Property<'tcx>> {
    let Some(self_ty_def_id) = self_ty_def_id else {
        return Vec::new();
    };
    let self_ty = tcx.type_of(self_ty_def_id).skip_binder();

    let trait_def_id = match trait_kind {
        MarkerTraitKind::Send => tcx.get_diagnostic_item(rustc_span::sym::Send),
        MarkerTraitKind::Sync => tcx.get_diagnostic_item(rustc_span::sym::Sync),
    };
    let Some(trait_def_id) = trait_def_id else {
        return Vec::new();
    };

    let templates = super::contract::json::query_trait_ensures(tcx, trait_def_id);
    let mut obligations = Vec::new();
    for entry in templates {
        if let Some(prop) = build_type_atom(tcx, self_ty_def_id, &entry, self_ty) {
            obligations.push(prop);
        }
    }
    obligations
}

/// Build a single type-level obligation from a `std-trait-ensures.json` entry,
/// substituting `ty:Self` with `self_ty`.  Supports the `any` disjunction and
/// falls back to named compound properties (`expand_compound`) for tags that are
/// not built-in primitives.
fn build_type_atom<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
    entry: &super::contract::json::JsonProperty,
    self_ty: rustc_middle::ty::Ty<'tcx>,
) -> Option<Property<'tcx>> {
    if let Some(items) = &entry.any {
        let disjuncts: Vec<Property<'tcx>> = items
            .iter()
            .filter_map(|item| match item {
                super::contract::json::AnyItem::Single(e) => {
                    build_type_atom(tcx, def_id, e, self_ty)
                }
                super::contract::json::AnyItem::And(es) => {
                    let conjuncts: Vec<Property<'tcx>> = es
                        .iter()
                        .filter_map(|e| build_type_atom(tcx, def_id, e, self_ty))
                        .collect();
                    if conjuncts.is_empty() {
                        None
                    } else {
                        Some(Property::new_and(conjuncts))
                    }
                }
            })
            .collect();
        return if disjuncts.is_empty() {
            None
        } else {
            Some(Property::new_or(disjuncts))
        };
    }

    match entry.tag.as_str() {
        "ContainNoType" => {
            let negatives: Vec<String> = entry.args[1..]
                .iter()
                .map(|s| s.strip_prefix("ty:").unwrap_or(s).to_string())
                .collect();
            let mut args = vec![PropertyArg::Ty(self_ty)];
            args.extend(negatives.into_iter().map(PropertyArg::Ident));
            Some(Property::new_atom(PropertyKind::ContainNoType, args))
        }
        "NoRawPtr" => Some(Property::new_atom(
            PropertyKind::NoRawPtr,
            vec![PropertyArg::Ty(self_ty)],
        )),
        "NoInternalMut" => Some(Property::new_atom(
            PropertyKind::NoInternalMut,
            vec![PropertyArg::Ty(self_ty)],
        )),
        "UniInternalMut" => Some(Property::new_atom(
            PropertyKind::UniInternalMut,
            vec![PropertyArg::Ty(self_ty)],
        )),
        "AtomicUpdate" => Some(Property::new_atom(
            PropertyKind::AtomicUpdate,
            vec![PropertyArg::Ty(self_ty)],
        )),
        "RefSend" => Some(Property::new_atom(
            PropertyKind::RefSend,
            vec![PropertyArg::Ty(self_ty)],
        )),
        // Fall back to a named compound property (e.g. `TamedRawPtr` defined in
        // `std-compound-properties.rs`).  The `ty:Self` placeholder is normalized
        // to `Self` and resolved by the compound's `Ty` parameter; a `Ptr`
        // parameter not supplied by the JSON template is filled in from the
        // struct's own `Allocated`/`Owning` invariant field.
        _ => {
            let mut exprs: Vec<syn::Expr> = entry
                .args
                .iter()
                .filter_map(|s| {
                    let normalized = super::contract::json::normalize_json_contract_arg(s);
                    syn::parse_str::<syn::Expr>(&normalized).ok()
                })
                .collect();
            if exprs.len() != entry.args.len() {
                return None;
            }

            if let Some(spec) = super::contract::compound::find_compound(def_id.krate, &entry.tag)
            {
                for i in exprs.len()..spec.param_tys.len() {
                    if spec.param_tys.get(i).map(|s| s.as_str()) != Some("Ptr") {
                        return None;
                    }
                    let Some(field) = extract_tamed_field(tcx, def_id) else {
                        return None;
                    };
                    let Ok(e) = syn::parse_str::<syn::Expr>(&field) else {
                        return None;
                    };
                    exprs.push(e);
                }
            }

            match super::contract::compound::expand_compound(tcx, def_id, &entry.tag, &exprs) {
                Some(mut props) if !props.is_empty() => {
                    // A compound body expands into one property per conjunct, each
                    // tagged with the compound's origin.  Hoist that origin onto the
                    // combined node so the report shows `Name(args)` once instead of
                    // `And(Name, Name, Name)`.
                    let origin = props.first().and_then(|p| p.origin()).cloned();
                    for p in &mut props {
                        p.clear_origin();
                    }
                    let mut combined = Property::conjunction(props);
                    if let Some(o) = origin {
                        combined.set_origin(o.name, o.args, o.meaning);
                    }
                    Some(combined)
                }
                _ => None,
            }
        }
    }
}

/// The raw-pointer field name a struct declares via `#[rapx::invariant(Allocated(field))]`
/// or `#[rapx::invariant(Owning(field))]`, used to bind a `TamedRawPtr` compound's
/// `Ptr` parameter.
fn extract_tamed_field<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<String> {
    let invariants = get_struct_invariants_from_annotation(tcx, def_id, def_id);
    invariants
        .iter()
        .find(|p| {
            matches!(
                p.kind(),
                Some(PropertyKind::Allocated) | Some(PropertyKind::Owning)
            )
        })
        .and_then(|p| p.args().first())
        .and_then(|a| super::contract::place::field_name_from_arg(tcx, def_id, a))
}

fn collect_properties_from_named_attrs<'tcx>(
    tcx: TyCtxt<'tcx>,
    attrs: impl IntoIterator<Item = &'tcx Attribute>,
    property_def_id: DefId,
    parse_error_label: &str,
    attr_name: &str,
) -> Vec<Property<'tcx>> {
    let mut results = Vec::new();

    for attr in attrs {
        if !is_rapx_named_attr(attr, attr_name) {
            continue;
        }

        let attr_str = crate::compat::attribute_to_string(tcx, attr);
        let parsed = match parse_rapx_attr(attr_str.as_str(), attr_name) {
            Ok(parsed) => parsed,
            Err(err) => {
                rap_error!(
                    "Failed to parse RAPx {} attr '{}': {}",
                    parse_error_label,
                    attr_str,
                    err
                );
                continue;
            }
        };

        let Some(property) = parsed else { continue };
        results.extend(
            Property::parse_list(tcx, property_def_id, property.tag.as_str(), &property.args)
                .into_iter()
                .map(move |mut p| {
                    p.apply_kind(property.kind.as_deref());
                    p
                }),
        );
    }

    results
}

/// Parses `requires` contracts from source-level RAPx annotations attached to a definition.
pub(crate) fn get_contract_from_annotation<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
) -> FnContracts<'tcx> {
    // Prefer HIR-level attrs for local defs (tool attributes visible),
    // fall back to get_all_attrs for external defs.
    if let Some(local_def_id) = def_id.as_local() {
        let hir_id = tcx.local_def_id_to_hir_id(local_def_id);
        let hir_attrs = tcx.hir_attrs(hir_id);
        // hir_attrs is &'tcx [Attribute<'tcx>]; iter yields &'tcx Attribute<'tcx>
        return collect_properties_from_named_attrs(tcx, hir_attrs, def_id, "requires", "requires");
    }

    let attrs = crate::compat::get_all_attrs(tcx, def_id);
    collect_properties_from_named_attrs(tcx, attrs, def_id, "requires", "requires")
}

/// Parses struct invariants from source-level RAPx annotations attached to a struct definition.
pub(crate) fn get_struct_invariants_from_annotation<'tcx>(
    tcx: TyCtxt<'tcx>,
    struct_def_id: DefId,
    context_def_id: DefId,
) -> StructInvariants<'tcx> {
    let Some(local_def_id) = struct_def_id.as_local() else {
        return Vec::new();
    };

    let item = tcx.hir_expect_item(local_def_id);
    if !matches!(item.kind, ItemKind::Struct(..)) {
        return Vec::new();
    }

    let mut invariants = collect_properties_from_named_attrs(
        tcx,
        crate::compat::get_all_attrs(tcx, struct_def_id),
        context_def_id,
        "invariant",
        "requires",
    );
    invariants.extend(collect_properties_from_named_attrs(
        tcx,
        crate::compat::get_all_attrs(tcx, struct_def_id),
        context_def_id,
        "invariant",
        "invariant",
    ));
    invariants
}

/// Parses trait safety contracts from `#[rapx::ensures(...)]` on unsafe trait
/// methods, grouped by method name.
fn get_trait_contracts_from_annotation<'tcx>(
    tcx: TyCtxt<'tcx>,
    trait_def_id: DefId,
) -> Vec<(String, FnContracts<'tcx>)> {
    let Some(local_id) = trait_def_id.as_local() else {
        return Vec::new();
    };

    let item = tcx.hir_expect_item(local_id);

    let trait_items = {
        #[cfg(not(rapx_ge_99))]
        if let ItemKind::Trait(.., items) = &item.kind {
            items
        } else {
            return Vec::new();
        }
        #[cfg(rapx_ge_99)]
        if let ItemKind::Trait { items, .. } = &item.kind {
            items
        } else {
            return Vec::new();
        }
    };

    let mut ensures: Vec<(String, FnContracts<'tcx>)> = Vec::new();

    for trait_item_id in trait_items.iter() {
        let trait_item_def_id = trait_item_id.owner_id.to_def_id();
        let method_name = tcx.def_path_str(trait_item_def_id);
        let attrs = crate::compat::get_all_attrs(tcx, trait_item_def_id);

        let method_ensures = collect_properties_from_named_attrs(
            tcx,
            attrs,
            trait_item_def_id,
            "trait ensures",
            "ensures",
        );

        if !method_ensures.is_empty() {
            ensures.push((method_name, method_ensures));
        }
    }

    ensures
}

/// Build (pseudo-checkpoint, properties) pairs for every raw pointer dereference
/// in the target function.
fn build_raw_ptr_deref_checks<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
) -> Vec<(Checkpoint<'tcx>, Vec<Property<'tcx>>)> {
    let infos = collect_raw_ptr_deref_info(tcx, def_id);
    if infos.is_empty() {
        return Vec::new();
    }

    infos
        .into_iter()
        .map(|info| {
            let target = PropertyArg::Expr(ContractExpr::Place(ContractPlace {
                base: PlaceBase::Arg(0),
                projections: vec![],
            }));
            let ty = PropertyArg::Ty(info.pointee_ty);
            let count = PropertyArg::Expr(ContractExpr::Const(1));

            let mut properties = if info.is_ptr2ref {
                vec![
                    Property::new_atom(
                        PropertyKind::Init,
                        vec![target.clone(), ty.clone(), count.clone()],
                    ),
                    Property::new_atom(PropertyKind::Align, vec![target.clone(), ty.clone()]),
                    {
                        let mut p = Property::new_atom(PropertyKind::Alias, vec![target.clone()]);
                        p.set_contract_kind(crate::verify::contract::ContractKind::Hazard);
                        p
                    },
                ]
            } else {
                vec![
                    Property::new_atom(
                        PropertyKind::Allocated,
                        vec![target.clone(), ty.clone(), count.clone()],
                    ),
                    Property::new_atom(
                        PropertyKind::InBound,
                        vec![target.clone(), ty.clone(), count.clone()],
                    ),
                    Property::new_atom(PropertyKind::Align, vec![target.clone(), ty.clone()]),
                ]
            };

            if info.is_read && !info.is_ptr2ref {
                properties.push(Property::new_atom(PropertyKind::Typed, vec![target, ty]));
            }

            (
                Checkpoint {
                    caller: def_id,
                    callee: None,
                    block: info.block,
                    args: vec![info.ptr_operand],
                    kind: crate::helpers::mir_scan::CheckpointKind::RawPtrDeref,
                    destination: Some(info.destination),
                },
                properties,
            )
        })
        .collect()
}

/// Build (pseudo-checkpoint, properties) pairs for every static mut access
/// in the target function.
fn build_static_mut_checks<'tcx>(
    tcx: TyCtxt<'tcx>,
    def_id: DefId,
) -> Vec<(Checkpoint<'tcx>, Vec<Property<'tcx>>)> {
    let infos = collect_static_mut_access_info(tcx, def_id);
    if infos.is_empty() {
        return Vec::new();
    }

    infos
        .into_iter()
        .map(|info| {
            let target = PropertyArg::Expr(ContractExpr::Place(ContractPlace {
                base: PlaceBase::Arg(0),
                projections: vec![],
            }));
            let ty = PropertyArg::Ty(info.ty);
            let count = PropertyArg::Expr(ContractExpr::Const(1));

            let properties = vec![
                Property::new_atom(
                    PropertyKind::Allocated,
                    vec![target.clone(), ty.clone(), count.clone()],
                ),
                Property::new_atom(
                    PropertyKind::InBound,
                    vec![target.clone(), ty.clone(), count.clone()],
                ),
                Property::new_atom(PropertyKind::Align, vec![target.clone(), ty.clone()]),
                Property::new_atom(PropertyKind::Init, vec![target, ty, count]),
            ];

            (
                Checkpoint {
                    caller: def_id,
                    callee: None,
                    block: info.block,
                    args: vec![info.ptr_operand],
                    kind: crate::helpers::mir_scan::CheckpointKind::StaticMutAccess,
                    destination: None,
                },
                properties,
            )
        })
        .collect()
}

fn is_drop_impl(tcx: TyCtxt<'_>, fn_did: DefId) -> bool {
    let Some(impl_id) = tcx.trait_impl_of_assoc(fn_did) else {
        return false;
    };
    let trait_did = tcx.impl_trait_id(impl_id);
    tcx.is_lang_item(trait_did, LangItem::Drop)
}