Skip to main content

rapx/contract/
json.rs

1//! The bundled JSON contract front-end: loading, lookup, and conversion.
2//!
3//! Embedded JSON assets provide std `requires`, type invariants, and trait contracts.
4//! Lookup uses exact, path-stripped, and wildcard
5//! fallback so trait-method impls and re-exported paths resolve correctly.
6//! Entries are then converted into [`Property`] values via [`entry_to_property`].
7
8use rustc_hir::def_id::DefId;
9use rustc_middle::ty::TyCtxt;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::sync::OnceLock;
13use syn::Expr;
14
15use crate::util::name::public_def_path;
16
17use super::{PlaceBase, Property, PropertyKind};
18
19/// Structure of JSON entries.
20///
21/// When the `any` field is present, the entry represents a disjunction (logical
22/// OR) of property groups.  Each element in `any` is either a single
23/// [`JsonProperty`] (one disjunct) or an array of entries (a conjunction group —
24/// all must hold).
25///
26/// JSON format for `any` (flat OR):
27/// ```json
28/// {
29///   "any": [
30///     {"tag": "Trait", "args": ["T", "Copy"]},
31///     {"tag": "Alias", "args": ["T", "return"]}
32///   ]
33/// }
34/// ```
35///
36/// JSON format for `any` with conjunction group (null-guard):
37/// ```json
38/// {
39///   "any": [
40///     {"tag": "Null", "args": ["head"]},
41///     [
42///       {"tag": "Align", "args": ["head", "Node"]},
43///       {"tag": "ValidPtr", "args": ["head", "Node", "1"]}
44///     ]
45///   ]
46/// }
47/// ```
48#[derive(Debug, Serialize, Deserialize, Clone)]
49pub(crate) struct JsonProperty {
50    #[serde(default)]
51    pub tag: String,
52    #[serde(default)]
53    pub args: Vec<String>,
54    #[serde(default)]
55    pub kind: Option<String>,
56    /// The list of disjuncts (OR alternatives) when this entry is a disjunction.
57    /// Each element is either a single entry or a conjunction group.
58    #[serde(default)]
59    pub any: Option<Vec<AnyItem>>,
60}
61
62/// One disjunct inside a JSON `any` entry.
63///
64/// `Single` is one property; `And` is a conjunction of properties
65/// (all must hold together, forming one OR alternative).
66#[derive(Debug, Serialize, Deserialize, Clone)]
67#[serde(untagged)]
68pub(crate) enum AnyItem {
69    Single(JsonProperty),
70    And(Vec<JsonProperty>),
71}
72
73#[derive(Debug, Deserialize)]
74struct StdTraitContracts {
75    #[serde(default)]
76    ensures: Vec<JsonProperty>,
77    #[serde(default)]
78    methods: HashMap<String, StdTraitMethodContracts>,
79}
80
81#[derive(Debug, Deserialize)]
82struct StdTraitMethodContracts {
83    #[serde(default)]
84    requires: Vec<JsonProperty>,
85    #[serde(default)]
86    ensures: Vec<JsonProperty>,
87}
88
89/// Looks up backup contracts for a standard-library function by its normalized path.
90/// For trait-method impls, resolves to the trait method's path first so that
91/// all impls share the same contracts.
92///
93/// After exact-path lookup, strips impl-block type segments so re-exported or
94/// impl-generic paths resolve.  For example, for `core::slice::<impl [T]>::as_chunks`:
95///
96/// 1. `core::slice::<impl [T]>::as_chunks`  (exact)
97/// 2. `core::slice::as_chunks`              (impl segments stripped)
98pub(crate) fn get_std_contracts_from_json(
99    tcx: TyCtxt<'_>,
100    def_id: DefId,
101) -> Option<&'static [JsonProperty]> {
102    let lookup_def_id = resolve_trait_method(tcx, def_id);
103    let cleaned_path_name = public_def_path(tcx, lookup_def_id);
104    if let Some(entries) = get_std_trait_method_requires(&cleaned_path_name) {
105        return Some(entries);
106    }
107    let db = load_std_contracts_json();
108
109    if let Some(entries) = db.get(&cleaned_path_name) {
110        return Some(entries.as_slice());
111    }
112
113    // Strip intra-path type segments that appear in impl blocks.
114    // E.g. `core::slice::[T]::as_chunks_unchecked` → `core::slice::as_chunks_unchecked`.
115    {
116        let stripped: Vec<&str> = cleaned_path_name
117            .split("::")
118            .filter(|s| !s.starts_with('[') && !s.starts_with('<'))
119            .collect();
120        if stripped.len() != cleaned_path_name.matches("::").count() + 1 {
121            let stripped_path = stripped.join("::");
122            if let Some(entries) = db.get(&stripped_path) {
123                return Some(entries.as_slice());
124            }
125        }
126    }
127
128    None
129}
130
131/// If `def_id` is a trait-method implementation, returns the corresponding
132/// trait method's [`DefId`]; otherwise returns `def_id` unchanged.
133fn resolve_trait_method(tcx: TyCtxt<'_>, def_id: DefId) -> DefId {
134    if let Some(assoc_item) = tcx.opt_associated_item(def_id)
135        && let Some(trait_def_id) = assoc_item.trait_item_def_id() {
136            return trait_def_id;
137        }
138    def_id
139}
140
141/// Lazily loads the backup contract database for standard-library APIs.
142fn load_std_contracts_json() -> &'static HashMap<String, Vec<JsonProperty>> {
143    static STD_CONTRACTS: OnceLock<HashMap<String, Vec<JsonProperty>>> = OnceLock::new();
144    STD_CONTRACTS.get_or_init(|| {
145        serde_json::from_str(include_str!("assets/std-api-requires.json"))
146            .expect("failed to parse verify std contracts backup")
147    })
148}
149
150/// Returns the std-type-invariants database, mapping a type path key
151/// (e.g. `"core::num::nonzero::NonZero"`) to its invariant entries.
152pub(crate) fn get_std_type_invariants() -> &'static HashMap<String, Vec<JsonProperty>> {
153    static TYPE_INVARIANTS: OnceLock<HashMap<String, Vec<JsonProperty>>> = OnceLock::new();
154    TYPE_INVARIANTS.get_or_init(|| {
155        serde_json::from_str(include_str!("assets/std-type-invariants.json"))
156            .expect("failed to parse std type invariants")
157    })
158}
159
160/// Lazily loads std trait contracts and marker-trait obligations.
161fn load_std_trait_json() -> &'static HashMap<String, StdTraitContracts> {
162    static STD_TRAITS: OnceLock<HashMap<String, StdTraitContracts>> = OnceLock::new();
163    STD_TRAITS.get_or_init(|| {
164        serde_json::from_str(include_str!("assets/std-trait.json"))
165            .expect("failed to parse std trait contracts")
166    })
167}
168
169fn get_std_trait_method(path: &str) -> Option<&'static StdTraitMethodContracts> {
170    let (trait_path, method_name) = path.rsplit_once("::")?;
171    load_std_trait_json()
172        .get(trait_path)?
173        .methods
174        .get(method_name)
175}
176
177fn get_std_trait_method_requires(path: &str) -> Option<&'static [JsonProperty]> {
178    get_std_trait_method(path).map(|method| method.requires.as_slice())
179}
180
181pub(crate) fn query_trait_method_ensures<'tcx>(
182    tcx: TyCtxt<'tcx>,
183    def_id: DefId,
184) -> Vec<Property<'tcx>> {
185    let path = public_def_path(tcx, resolve_trait_method(tcx, def_id));
186    let Some(method) = get_std_trait_method(&path) else {
187        return Vec::new();
188    };
189    let (param_names, _) = crate::util::name::parse_signature(tcx, def_id);
190    let has_names = !param_names.is_empty() && !param_names[0].chars().all(|c| c.is_ascii_digit());
191    method
192        .ensures
193        .iter()
194        .flat_map(|entry| entry_to_property(tcx, def_id, entry, &param_names, has_names))
195        .map(|mut property| {
196            property.set_contract_kind(super::ContractKind::Postcond);
197            property
198        })
199        .collect()
200}
201
202/// Returns the `ensures` obligation template for a marker trait such as
203/// `Send`/`Sync`, keyed by the trait's def path (e.g. `"core::marker::Send"`).
204///
205/// The returned entries are templates: `ty:Self` placeholders are resolved to
206/// the concrete implementing type by the caller (`TraitEnsurance` collection).
207///
208/// Matching falls back to the trait's short name so that `std`/`core` re-exports
209/// (`std::marker::Send` vs `core::marker::Send`) resolve to the same entry.
210pub(crate) fn query_trait_ensures(tcx: TyCtxt<'_>, trait_def_id: DefId) -> Vec<JsonProperty> {
211    let db = load_std_trait_json();
212    let key = tcx.def_path_str(trait_def_id);
213    if let Some(contracts) = db.get(&key) {
214        return contracts.ensures.clone();
215    }
216    let short = key.rsplit("::").next().unwrap_or(&key).to_string();
217    for (k, contracts) in db.iter() {
218        if k.rsplit("::").next() == Some(short.as_str()) {
219            return contracts.ensures.clone();
220        }
221    }
222    Vec::new()
223}
224
225// ── Entry conversion & argument normalization ───────────────────────────────
226
227/// Convert a single [`JsonProperty`] from JSON into the properties it denotes.
228///
229/// Resolves named parameter references (e.g. `"src"` → `"Arg_0"`), normalizes
230/// explicit JSON tokens (`arg:`, `const:`, `ty:`), and delegates to
231/// [`Property::parse_list`] for tag-based parsing.  A single entry may expand to
232/// several properties (via a compound property or `any`), hence the `Vec` return.
233pub(crate) fn entry_to_property<'tcx>(
234    tcx: TyCtxt<'tcx>,
235    def_id: DefId,
236    entry: &JsonProperty,
237    param_names: &[String],
238    has_names: bool,
239) -> Vec<Property<'tcx>> {
240    if let Some(disjuncts) = &entry.any {
241        if disjuncts.len() >= 2 {
242            let mut prop = any_entry_to_property(tcx, def_id, disjuncts, param_names, has_names);
243            prop.apply_kind(entry.kind.as_deref());
244            return vec![prop];
245        }
246        rap_error!(
247            "JSON any entry requires at least 2 disjuncts, got {}",
248            disjuncts.len()
249        );
250        return Vec::new();
251    }
252
253    let exprs = resolve_json_args(&entry.args, param_names, has_names, &entry.tag);
254    if exprs.len() != entry.args.len() {
255        return Vec::new();
256    }
257
258    let properties = Property::parse_list(tcx, def_id, entry.tag.as_str(), &exprs);
259    let mut result = Vec::new();
260    for mut property in properties {
261        property.apply_kind(entry.kind.as_deref());
262        if matches!(property.kind(), Some(PropertyKind::Unknown)) {
263            rap_debug!(
264                "skip unsupported std safety contract tag '{}' for callee {:?}",
265                entry.tag,
266                def_id
267            );
268            continue;
269        }
270        result.push(property);
271    }
272    result
273}
274
275/// Parse an `any` disjunction entry from JSON into a `Property::Or` property.
276///
277/// Each element of `disjuncts` is an [`AnyItem`]:
278/// - `Single(entry)` → one-property disjunct
279/// - `And(entries)` → conjunction group (all entries must hold for this disjunct)
280fn any_entry_to_property<'tcx>(
281    tcx: TyCtxt<'tcx>,
282    def_id: DefId,
283    disjuncts: &[AnyItem],
284    param_names: &[String],
285    has_names: bool,
286) -> Property<'tcx> {
287    let mut or_disjuncts: Vec<Property<'tcx>> = Vec::new();
288    for item in disjuncts {
289        match item {
290            AnyItem::Single(entry) => {
291                let group = resolve_entry_group(tcx, def_id, entry, param_names, has_names);
292                if !group.is_empty() {
293                    or_disjuncts.push(Property::conjunction(group));
294                }
295            }
296            AnyItem::And(entries) => {
297                let mut group: Vec<Property<'tcx>> = Vec::new();
298                for entry in entries {
299                    group.extend(resolve_entry_group(
300                        tcx,
301                        def_id,
302                        entry,
303                        param_names,
304                        has_names,
305                    ));
306                }
307                if !group.is_empty() {
308                    or_disjuncts.push(Property::conjunction(group));
309                }
310            }
311        }
312    }
313    Property::new_or(or_disjuncts)
314}
315
316/// Resolve a single JSON `any` entry into its property group (empty on error).
317fn resolve_entry_group<'tcx>(
318    tcx: TyCtxt<'tcx>,
319    def_id: DefId,
320    entry: &JsonProperty,
321    param_names: &[String],
322    has_names: bool,
323) -> Vec<Property<'tcx>> {
324    if entry.any.is_some() {
325        rap_error!("Nested 'any' inside 'any' is not supported in JSON contracts");
326        return Vec::new();
327    }
328    let exprs = resolve_json_args(&entry.args, param_names, has_names, &entry.tag);
329    if exprs.len() != entry.args.len() {
330        return Vec::new();
331    }
332    let props = Property::parse_list(tcx, def_id, entry.tag.as_str(), &exprs);
333    let mut group = Vec::new();
334    for mut prop in props {
335        prop.apply_kind(entry.kind.as_deref());
336        group.push(prop);
337    }
338    group
339}
340
341/// Resolve JSON contract argument strings to parsed [`syn::Expr`] values.
342///
343/// Handles:
344/// - Named parameter resolution (e.g. `"src"` → `"arg:0"`)
345/// - Explicit token normalization (`arg:`, `const:`, `ty:` prefixes)
346/// - Lifetime stripping (`'a` → `a`, `'static` → `static_lifetime`)
347pub(crate) fn resolve_json_args(
348    args: &[String],
349    param_names: &[String],
350    has_names: bool,
351    tag: &str,
352) -> Vec<Expr> {
353    let mut exprs: Vec<Expr> = Vec::new();
354    for arg_str in args {
355        let resolved = if has_names {
356            resolve_json_param_name(arg_str, param_names)
357        } else {
358            arg_str.clone()
359        };
360        let normalized_arg = normalize_json_contract_arg(&resolved);
361        match syn::parse_str::<Expr>(&normalized_arg) {
362            Ok(expr) => exprs.push(expr),
363            Err(_) => {
364                let lifetime = normalized_arg
365                    .strip_prefix('\'')
366                    .filter(|l| !l.is_empty() && l.chars().all(|c| c.is_alphabetic() || c == '_'));
367                match lifetime {
368                    Some(lifetime) => {
369                        let ident = if lifetime == "static" { super::STATIC_LIFETIME_IDENT } else { lifetime };
370                        match syn::parse_str::<Expr>(ident) {
371                            Ok(expr) => exprs.push(expr),
372                            Err(_) => rap_error!(
373                                "JSON Contract Error: Failed to parse lifetime \
374                                 '{}' as Rust Expr for tag {}",
375                                arg_str,
376                                tag
377                            ),
378                        }
379                    }
380                    None => rap_error!(
381                        "JSON Contract Error: Failed to parse arg '{}' as Rust Expr for tag {}",
382                        arg_str,
383                        tag
384                    ),
385                }
386            }
387        }
388    }
389    exprs
390}
391
392/// Resolve a simple parameter-name reference in a JSON contract arg string to
393/// the `arg:N` positional form.  Complex expressions (containing function
394/// calls, field access, etc.) are left unchanged — they are handled later by
395/// the expression parser which already knows how to resolve named parameters.
396pub(crate) fn resolve_json_param_name(arg: &str, param_names: &[String]) -> String {
397    if arg.starts_with("arg:")
398        || arg.starts_with("const:")
399        || arg.starts_with("ty:")
400        || arg.contains('(')
401        || arg.contains('.')
402        || arg.contains("::")
403        || arg.contains(' ')
404        || arg.starts_with('\'')
405    {
406        return arg.to_string();
407    }
408    if let Some(pos) = param_names.iter().position(|n| n == arg) {
409        format!("arg:{pos}")
410    } else {
411        arg.to_string()
412    }
413}
414
415/// Convert explicit JSON contract tokens into the expression syntax accepted by
416/// the existing property parser.
417///
418/// Supported explicit tokens:
419/// - `arg:N` names callee argument `N` and becomes internal `Arg_N`.
420/// - `const:N` names an integer constant and becomes `N`.
421/// - `ty:T` names a type parameter/type identifier and becomes `T`.
422///
423/// Unprefixed strings are kept unchanged for compatibility with older entries
424/// such as `"0"`, `"T"`, and `"1"`.
425pub(crate) fn normalize_json_contract_arg(arg: &str) -> String {
426    let mut out = String::with_capacity(arg.len());
427    let mut i = 0;
428
429    while i < arg.len() {
430        if arg[i..].starts_with("arg:") {
431            let start = i + "arg:".len();
432            let end = scan_while(arg, start, |ch| ch.is_ascii_digit());
433            if end > start {
434                out.push_str("Arg_");
435                out.push_str(&arg[start..end]);
436                i = end;
437                continue;
438            }
439        }
440
441        if arg[i..].starts_with("const:") {
442            let start = i + "const:".len();
443            let end = scan_while(arg, start, is_contract_token_char);
444            if end > start {
445                out.push_str(&arg[start..end]);
446                i = end;
447                continue;
448            }
449        }
450
451        if arg[i..].starts_with("ty:") {
452            let start = i + "ty:".len();
453            let end = scan_while(arg, start, is_contract_token_char);
454            if end > start {
455                out.push_str(&arg[start..end]);
456                i = end;
457                continue;
458            }
459        }
460
461        let ch = arg[i..].chars().next().unwrap();
462        out.push(ch);
463        i += ch.len_utf8();
464    }
465
466    out
467}
468
469fn scan_while(arg: &str, mut index: usize, predicate: impl Fn(char) -> bool) -> usize {
470    while index < arg.len() {
471        let ch = arg[index..].chars().next().unwrap();
472        if !predicate(ch) {
473            break;
474        }
475        index += ch.len_utf8();
476    }
477    index
478}
479
480fn is_contract_token_char(ch: char) -> bool {
481    ch.is_ascii_alphanumeric() || ch == '_' || ch == ':'
482}
483
484/// Query contracts for a function from the bundled JSON backup database.
485///
486/// Uses [`get_std_contracts_from_json`] for lookup with wildcard fallback,
487/// then parses each entry into a [`Property`] via [`entry_to_property`].
488pub(crate) fn query_json_contracts<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Vec<Property<'tcx>> {
489    let Some(entries) = get_std_contracts_from_json(tcx, def_id) else {
490        return Vec::new();
491    };
492    parse_json_contracts(tcx, def_id, entries)
493}
494
495/// Argument indices named by JSON `RefCountShare` requirements on this function.
496pub(crate) fn ref_count_share_arg_indices(tcx: TyCtxt<'_>, def_id: DefId) -> Vec<usize> {
497    query_json_contracts(tcx, def_id).iter().filter_map(|property| {
498        (property.kind() == Some(PropertyKind::RefCountShare))
499            .then(|| property.target_place())
500            .flatten()
501            .and_then(|place| match place.base {
502                PlaceBase::Arg(index) => Some(index),
503                _ => None,
504            })
505    }).collect()
506}
507
508/// Parse the contract at an explicit JSON key using a function's parameter types.
509pub(crate) fn query_json_contracts_at_path<'tcx>(
510    tcx: TyCtxt<'tcx>,
511    signature_def_id: DefId,
512    path: &str,
513) -> Vec<Property<'tcx>> {
514    let db = load_std_contracts_json();
515    let Some(entries) = db.get(path) else {
516        return Vec::new();
517    };
518    parse_json_contracts(tcx, signature_def_id, entries)
519}
520
521fn parse_json_contracts<'tcx>(
522    tcx: TyCtxt<'tcx>,
523    def_id: DefId,
524    entries: &[JsonProperty],
525) -> Vec<Property<'tcx>> {
526    let (param_names, _) = crate::util::name::parse_signature(tcx, def_id);
527    let has_names = !param_names.is_empty() && !param_names[0].chars().all(|c| c.is_ascii_digit());
528
529    let mut results = Vec::new();
530    for entry in entries {
531        results.extend(entry_to_property(
532            tcx,
533            def_id,
534            entry,
535            &param_names,
536            has_names,
537        ));
538    }
539    results
540}