1use 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#[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 #[serde(default)]
59 pub any: Option<Vec<AnyItem>>,
60}
61
62#[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
89pub(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 {
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
131fn 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
141fn 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
150pub(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
160fn 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, ¶m_names, has_names))
195 .map(|mut property| {
196 property.set_contract_kind(super::ContractKind::Postcond);
197 property
198 })
199 .collect()
200}
201
202pub(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
225pub(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
275fn 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
316fn 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
341pub(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
392pub(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
415pub(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
484pub(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
495pub(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
508pub(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 ¶m_names,
536 has_names,
537 ));
538 }
539 results
540}