Skip to main content

rapx/contract/
annotation.rs

1//! Contract annotations on functions and structs.
2
3use crate::contract::{
4    Property, PropertyArg, PropertyKind,
5    attr::{collect_properties_from_named_attrs, is_rapx_named_attr, parse_rapx_attr},
6    is_static_lifetime_ident,
7};
8use crate::util::fn_info::get_adt_def_id_by_adt_method;
9use crate::util::mir_utils::has_rapx_attr;
10use rustc_hir::{ItemKind, def_id::DefId};
11use rustc_middle::ty::{self, EarlyParamRegion, GenericParamDefKind, Region, Ty, TyCtxt};
12use rustc_span::Symbol;
13
14/// Check whether a local struct declares a RAPx invariant without parsing it.
15pub(crate) fn has_rapx_struct_invariant(tcx: TyCtxt<'_>, struct_def_id: DefId) -> bool {
16    let Some(local_def_id) = struct_def_id.as_local() else { return false };
17    has_rapx_attr(tcx, local_def_id, Symbol::intern("invariant"))
18}
19
20/// Check whether a function's owning struct declares a RAPx invariant.
21pub(crate) fn function_has_rapx_struct_invariant(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
22    get_adt_def_id_by_adt_method(tcx, def_id)
23        .is_some_and(|struct_def_id| has_rapx_struct_invariant(tcx, struct_def_id))
24}
25
26pub(crate) fn get_trait_method_requires<'tcx>(
27    tcx: TyCtxt<'tcx>,
28    callee_def_id: DefId,
29) -> Vec<Property<'tcx>> {
30    let Some(assoc_item) = tcx.opt_associated_item(callee_def_id) else {
31        return Vec::new();
32    };
33    let Some(trait_item_def_id) = assoc_item.trait_item_def_id() else {
34        return Vec::new();
35    };
36    get_contract_from_annotation(tcx, trait_item_def_id)
37}
38
39/// Parses `requires` contracts from source-level RAPx annotations attached to a definition.
40pub(crate) fn get_contract_from_annotation<'tcx>(
41    tcx: TyCtxt<'tcx>,
42    def_id: DefId,
43) -> Vec<Property<'tcx>> {
44    // Prefer HIR-level attrs for local defs (tool attributes visible),
45    // fall back to get_all_attrs for external defs.
46    if let Some(local_def_id) = def_id.as_local() {
47        let hir_id = tcx.local_def_id_to_hir_id(local_def_id);
48        let hir_attrs = tcx.hir_attrs(hir_id);
49        return collect_properties_from_named_attrs(tcx, hir_attrs, def_id, "requires", "requires");
50    }
51
52    let attrs = crate::compat::get_all_attrs(tcx, def_id);
53    collect_properties_from_named_attrs(tcx, attrs, def_id, "requires", "requires")
54}
55
56/// Parses struct invariants from source-level RAPx annotations attached to a struct definition.
57pub(crate) fn get_struct_invariants_from_annotation<'tcx>(
58    tcx: TyCtxt<'tcx>,
59    struct_def_id: DefId,
60    context_def_id: DefId,
61) -> Vec<Property<'tcx>> {
62    let Some(local_def_id) = struct_def_id.as_local() else {
63        return Vec::new();
64    };
65
66    let item = tcx.hir_expect_item(local_def_id);
67    if !matches!(item.kind, ItemKind::Struct(..)) {
68        return Vec::new();
69    }
70
71    let mut invariants = collect_properties_from_named_attrs(
72        tcx,
73        crate::compat::get_all_attrs(tcx, struct_def_id),
74        context_def_id,
75        "invariant",
76        "requires",
77    );
78    invariants.extend(collect_properties_from_named_attrs(
79        tcx,
80        crate::compat::get_all_attrs(tcx, struct_def_id),
81        context_def_id,
82        "invariant",
83        "invariant",
84    ));
85    // A lifetime in a struct invariant (`Alive(ptr, 'a)`) names a lifetime on
86    // the *struct*, so bind it here against the struct's own generics. Parsing
87    // used `context_def_id` (the method), whose generics lack `'a`.
88    for inv in &mut invariants {
89        bind_alive_regions(tcx, struct_def_id, inv);
90    }
91    invariants
92}
93
94/// Bind `Alive(p, 'a)` region idents in a contract to `Region`s, resolving `'a`
95/// against `def_id` (the item that declares `'a`: the struct for its
96/// invariants, the function for its `requires`).
97pub(crate) fn bind_alive_regions<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, property: &mut Property<'tcx>) {
98    match property {
99        Property::Atom(atom) => {
100            if atom.kind == PropertyKind::Alive
101                && let Some(PropertyArg::Ident(name)) = atom.args.get(1).cloned()
102                && let Some(region) =
103                    resolve_region_name(tcx, def_id, &name)
104            {
105                atom.args[1] = PropertyArg::Region(region);
106            }
107        }
108        Property::And(and) => {
109            for conjunct in &mut and.conjuncts {
110                bind_alive_regions(tcx, def_id, conjunct);
111            }
112        }
113        Property::Or(or) => {
114            for disjunct in &mut or.disjuncts {
115                bind_alive_regions(tcx, def_id, disjunct);
116            }
117        }
118    }
119}
120
121/// Resolve a lifetime name from a contract (e.g. `"a"`, `"static_lifetime"`) to a
122/// concrete `Region`. `name` is the raw ident, without the leading `'`.
123pub(crate) fn resolve_region_name<'tcx>(
124    tcx: TyCtxt<'tcx>,
125    def_id: DefId,
126    name: &str,
127) -> Option<Region<'tcx>> {
128    if is_static_lifetime_ident(name) {
129        return Some(tcx.lifetimes.re_static);
130    }
131    let ticked = format!("'{name}");
132    let generics = tcx.generics_of(def_id);
133    for param in &generics.own_params {
134        if matches!(param.kind, GenericParamDefKind::Lifetime)
135            && param.name.as_str() == ticked.as_str()
136        {
137            return Some(Region::new_early_param(
138                tcx,
139                EarlyParamRegion {
140                    index: param.index,
141                    name: param.name,
142                },
143            ));
144        }
145    }
146    None
147}
148
149
150/// Resolve `Owning(self.field...)` invariants on a local returned struct to
151/// field-index paths, without requiring a method `self` binding.
152pub(crate) fn owning_field_paths_from_annotation<'tcx>(
153    tcx: TyCtxt<'tcx>,
154    output: Ty<'tcx>,
155) -> Vec<Vec<usize>> {
156    let ty::Adt(adt, _) = output.kind() else {
157        return Vec::new();
158    };
159    if !adt.did().is_local() || !adt.is_struct() {
160        return Vec::new();
161    }
162    crate::compat::get_all_attrs(tcx, adt.did())
163        .into_iter()
164        .filter(|attr| is_rapx_named_attr(tcx, attr, "invariant"))
165        .filter_map(|attr| {
166            let text = crate::compat::attribute_to_string(tcx, attr);
167            parse_rapx_attr(&text, "invariant").ok().flatten()
168        })
169        .filter(|property| property.tag == "Owning")
170        .filter_map(|property| {
171            let mut members = Vec::new();
172            let mut expr = property.args.first()?;
173            while let syn::Expr::Field(field) = expr {
174                members.push(&field.member);
175                expr = &field.base;
176            }
177            let syn::Expr::Path(root) = expr else { return None };
178            if !root.path.is_ident("self") {
179                return None;
180            }
181            let mut ty = output;
182            let mut path = Vec::new();
183            for member in members.into_iter().rev() {
184                let ty::Adt(adt, args) = ty.kind() else { return None };
185                let fields = &adt.non_enum_variant().fields;
186                let index = match member {
187                    syn::Member::Named(name) =>
188                        fields.iter().position(|field| field.name.as_str() == name.to_string())?,
189                    syn::Member::Unnamed(index) => index.index as usize,
190                };
191                let field = fields.iter().nth(index)?;
192                path.push(index);
193                ty = crate::util::mir_utils::field_ty(tcx, field, args);
194            }
195            Some(path)
196        })
197        .collect()
198}