Skip to main content

rapx/contract/
ensures.rs

1//! Trait-method and foreign-call postcondition lookup.
2
3use rustc_hir::def_id::DefId;
4use rustc_middle::ty::TyCtxt;
5
6use super::{Property, attr::collect_properties_from_named_attrs};
7
8pub(crate) fn get_trait_method_ensures<'tcx>(
9    tcx: TyCtxt<'tcx>,
10    def_id: DefId,
11) -> Vec<Property<'tcx>> {
12    let trait_item_def_id = tcx
13        .opt_associated_item(def_id)
14        .and_then(|item| item.trait_item_def_id())
15        .unwrap_or(def_id);
16    if tcx.trait_of_assoc(trait_item_def_id).is_none() {
17        return Vec::new();
18    }
19    let mut ensures = if trait_item_def_id.is_local() {
20        collect_properties_from_named_attrs(
21            tcx,
22            crate::compat::get_all_attrs(tcx, trait_item_def_id),
23            trait_item_def_id,
24            "trait ensures",
25            "ensures",
26        )
27    } else {
28        Vec::new()
29    };
30    if ensures.is_empty() {
31        ensures = super::json::query_trait_method_ensures(tcx, def_id);
32    }
33    for property in &mut ensures {
34        property.set_contract_kind(super::ContractKind::Postcond);
35    }
36    ensures
37}
38
39pub(crate) fn get_call_ensures<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Vec<Property<'tcx>> {
40    if !tcx.is_foreign_item(def_id) {
41        return get_trait_method_ensures(tcx, def_id);
42    }
43    let mut ensures = collect_properties_from_named_attrs(
44        tcx,
45        crate::compat::get_all_attrs(tcx, def_id),
46        def_id,
47        "foreign function ensures",
48        "ensures",
49    );
50    for property in &mut ensures {
51        property.set_contract_kind(super::ContractKind::Postcond);
52    }
53    ensures
54}
55
56pub(crate) fn has_slice_offset_ensures(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
57    get_trait_method_ensures(tcx, def_id)
58        .iter()
59        .any(|property| property.kind() == Some(super::PropertyKind::SliceOffset))
60}