1use std::{
26 collections::{HashMap, HashSet},
27 sync::{OnceLock, RwLock},
28};
29
30#[cfg(rapx_has_attr_ir)]
31use rustc_attr_ir::Attribute;
32#[cfg(not(rapx_has_attr_ir))]
33use rustc_hir::Attribute;
34use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
35use rustc_span::Symbol;
36use syn::{
37 Expr,
38 visit_mut::{self, VisitMut},
39};
40
41use super::spec::ArgKind;
42use super::{AtomProperty, ContractExpr, ContractKind, Property, PropertyArg, PropertyKind};
43
44#[derive(Debug, Clone, PartialEq, Eq, Hash)]
47pub(crate) enum CompoundArg {
48 Param(usize),
49 Lit(String),
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
58pub(crate) enum CompoundBody {
59 And(Vec<CompoundBody>),
60 Or(Vec<CompoundBody>),
61 Call { tag: String, args: Vec<CompoundArg> },
62}
63
64#[derive(Debug, Clone)]
66pub(crate) struct CompoundSpec {
67 pub name: String,
68 pub params: Vec<String>,
69 pub param_tys: Vec<String>,
70 pub required: usize,
72 pub body: CompoundBody,
73 pub doc: Vec<String>,
74}
75
76pub(crate) fn parse_compounds(source: &str) -> Vec<CompoundSpec> {
91 let mut compounds = Vec::new();
92 let mut doc: Vec<String> = Vec::new();
93
94 let mut s = source.trim_start();
95 loop {
96 loop {
97 if let Some(r) = s.strip_prefix("///") {
98 let end = r.find('\n').unwrap_or(r.len());
99 doc.push(r[..end].trim().to_string());
100 s = r[end..].trim_start();
101 } else if let Some(r) = s.strip_prefix("//") {
102 let end = r.find('\n').unwrap_or(r.len());
103 s = r[end..].trim_start();
104 } else {
105 break;
106 }
107 }
108 if s.is_empty() {
109 break;
110 }
111
112 let (Some(mut compound), consumed) = parse_one_compound_block(s) else {
113 let preview: String = s.chars().take(80).collect();
114 rap_error!("failed to parse contract compound near: {preview}");
115 break;
116 };
117 compound.doc = std::mem::take(&mut doc);
118 compounds.push(compound);
119 s = s[consumed..].trim_start();
120 }
121
122 compounds
123}
124
125fn parse_one_compound_block(s: &str) -> (Option<CompoundSpec>, usize) {
135 let Some(open) = s.find('(') else {
136 return (None, 0);
137 };
138 let name = s[..open].trim().to_string();
139 if name.is_empty() {
140 return (None, 0);
141 }
142
143 let Some(rel_close) = s[open + 1..].find(')') else {
146 return (None, 0);
147 };
148 let close = open + 1 + rel_close;
149 let params_str = &s[open + 1..close];
150
151 let after = s[close + 1..].trim_start();
152 if !after.starts_with('{') {
153 return (None, 0);
154 }
155 let brace_open = s.len() - after.len();
156 let body_start = brace_open + 1;
157
158 let bytes = s.as_bytes();
159 let mut depth = 1usize;
160 let mut j = body_start;
161 while j < bytes.len() {
162 match bytes[j] {
163 b'{' => depth += 1,
164 b'}' => {
165 depth -= 1;
166 if depth == 0 {
167 break;
168 }
169 }
170 _ => {}
171 }
172 j += 1;
173 }
174 if depth != 0 {
175 return (None, 0);
176 }
177 let body = s[body_start..j].trim();
178
179 let (params, param_tys, required) = parse_equation_params(params_str);
180 let Some(body_ast) = super::pest::parse_compound_body(body, ¶ms) else {
181 return (None, 0);
182 };
183
184 let compound = CompoundSpec {
185 name,
186 params,
187 param_tys,
188 required,
189 body: body_ast,
190 doc: Vec::new(),
191 };
192 (Some(compound), j + 1)
193}
194
195fn parse_equation_params(params_str: &str) -> (Vec<String>, Vec<String>, usize) {
196 let mut params = Vec::new();
197 let mut param_tys = Vec::new();
198 let mut required = 0usize;
199 let mut seen_optional = false;
200 for seg in params_str.split(',') {
201 let seg = seg.trim();
202 if seg.is_empty() {
203 continue;
204 }
205 let (name, ty) = match seg.split_once(':') {
206 Some((p, ty)) => (p.trim().to_string(), ty.trim().to_string()),
207 None => (seg.to_string(), String::new()),
208 };
209 let (ty, optional) = match ty.strip_suffix('?') {
210 Some(stripped) => (stripped.to_string(), true),
211 None => (ty, false),
212 };
213 if optional {
214 seen_optional = true;
215 } else if !seen_optional {
216 required += 1;
217 }
218 params.push(name);
219 param_tys.push(ty);
220 }
221 (params, param_tys, required)
222}
223
224fn render_expr_src(e: &Expr) -> String {
228 quote::ToTokens::to_token_stream(e)
229 .to_string()
230 .replace(" . ", ".")
231 .replace(" ,", ",")
232 .replace(" (", "(")
233 .replace(" :: ", "::")
234}
235
236fn resolve_arg_string<'tcx>(
240 tcx: rustc_middle::ty::TyCtxt<'tcx>,
241 def_id: rustc_hir::def_id::DefId,
242 param_ty: &str,
243 expr: &Expr,
244) -> String {
245 match param_ty {
246 "Ptr" => {
247 let arg = super::resolve::parse_target_arg(tcx, def_id, expr);
248 if let Some(ContractExpr::Place(place)) = arg.expr()
251 && let Some(name) = super::place::field_name_from_place(tcx, def_id, place)
252 {
253 return name;
254 }
255 arg.display_for_report(tcx, None, Some(def_id))
256 }
257 "Ty" => super::resolve::parse_type(tcx, def_id, expr, "compound")
258 .map(|ty| ty.to_string())
259 .unwrap_or_else(|| render_expr_src(expr)),
260 "Expr" => {
261 let ce = super::resolve::expr_to_pest(tcx, def_id, expr);
262 super::render::display_expr_user_friendly(&ce, tcx, None, Some(def_id))
263 }
264 _ => render_expr_src(expr),
265 }
266}
267
268struct Subst<'a> {
276 params: &'a [String],
277 args: &'a [Expr],
278}
279
280impl VisitMut for Subst<'_> {
281 fn visit_expr_mut(&mut self, node: &mut Expr) {
282 if let Expr::Path(path) = node
283 && path.qself.is_none()
284 && path.path.leading_colon.is_none()
285 && path.path.segments.len() == 1
286 {
287 let ident = path.path.segments[0].ident.to_string();
288 if let Some(i) = self.params.iter().position(|n| *n == ident)
289 && let Some(arg) = self.args.get(i) {
290 *node = arg.clone();
293 return;
294 }
295 }
296 visit_mut::visit_expr_mut(self, node);
297 }
298}
299
300fn compound_param_ty_matches_arg_kind(def_ty: &str, kind: super::spec::ArgKind) -> bool {
302 matches!(
303 (def_ty, kind),
304 ("Ptr", ArgKind::Target)
305 | ("Ty", ArgKind::Ty)
306 | ("Expr", ArgKind::Expr)
307 | ("Ident", ArgKind::Ident)
308 )
309}
310
311fn expand_compound_body<'tcx>(
317 tcx: rustc_middle::ty::TyCtxt<'tcx>,
318 def_id: rustc_hir::def_id::DefId,
319 body: &CompoundBody,
320 exprs: &[Expr],
321 params: &[String],
322 param_tys: &[String],
323) -> Vec<Property<'tcx>> {
324 match body {
325 CompoundBody::And(parts) => parts
326 .iter()
327 .flat_map(|p| expand_compound_body(tcx, def_id, p, exprs, params, param_tys))
328 .collect(),
329 CompoundBody::Or(parts) => {
330 let mut disjuncts: Vec<Property<'tcx>> = Vec::new();
331 for part in parts {
332 let conjuncts = expand_compound_body(tcx, def_id, part, exprs, params, param_tys);
333 if !conjuncts.is_empty() {
334 disjuncts.push(Property::conjunction(conjuncts));
335 }
336 }
337 vec![Property::new_or(disjuncts)]
338 }
339 CompoundBody::Call { tag, args } => {
340 if let Some(spec) = super::spec::find_spec(tag) {
343 match spec.kind {
344 PropertyKind::Alias | PropertyKind::Alive => {
345 for (pos, a) in args.iter().enumerate() {
346 if let CompoundArg::Param(i) = a
347 && let Some(def_ty) = param_tys.get(*i)
348 && !compound_param_ty_matches_arg_kind(
349 def_ty,
350 super::spec::ArgKind::Target,
351 )
352 {
353 let pname = params.get(*i).map(String::as_str).unwrap_or("?");
354 rap_warn!(
355 "contract compound type mismatch: `{tag}` arg {pos} expects \
356 {:?}, but param `{pname}` is annotated `{def_ty}`",
357 super::spec::ArgKind::Target
358 );
359 }
360 }
361 }
362 PropertyKind::Unknown => {}
363 _ => {
366 if let Some(form) = spec.forms.iter().find(|f| f.len() == args.len()) {
367 for (pos, a) in args.iter().enumerate() {
368 if let CompoundArg::Param(i) = a
369 && let (Some(def_ty), Some(&arg_kind)) =
370 (param_tys.get(*i), form.get(pos))
371 && !compound_param_ty_matches_arg_kind(def_ty, arg_kind)
372 {
373 let pname = params.get(*i).map(String::as_str).unwrap_or("?");
374 rap_warn!(
375 "contract compound type mismatch: `{tag}` arg {pos} expects \
376 {:?}, but param `{pname}` is annotated `{def_ty}`",
377 arg_kind
378 );
379 }
380 }
381 }
382 }
383 }
384 }
385
386 let mut resolved: Vec<Expr> = Vec::with_capacity(args.len());
387 for (idx, a) in args.iter().enumerate() {
388 match a {
389 CompoundArg::Param(i) => {
390 match exprs.get(*i) {
391 Some(e) => resolved.push(e.clone()),
392 None => {
393 if args[idx..]
399 .iter()
400 .any(|a| matches!(a, CompoundArg::Lit(_)))
401 {
402 return Vec::new();
403 }
404 break;
405 }
406 }
407 }
408 CompoundArg::Lit(s) => {
409 let Ok(mut e) = syn::parse_str::<Expr>(s) else {
410 return vec![unknown_property()];
411 };
412 Subst {
413 params,
414 args: exprs,
415 }
416 .visit_expr_mut(&mut e);
417 resolved.push(e);
418 }
419 }
420 }
421 Property::parse_list(tcx, def_id, tag, &resolved)
424 }
425 }
426}
427
428fn unknown_property<'tcx>() -> Property<'tcx> {
429 Property::new_atom(PropertyKind::Unknown, Vec::new())
430}
431
432fn builtin_subsumptions_map() -> &'static HashMap<String, CompoundSpec> {
436 static BUILTIN: OnceLock<HashMap<String, CompoundSpec>> = OnceLock::new();
437 BUILTIN.get_or_init(|| {
438 parse_compounds(include_str!("assets/std-subsumption.rs"))
439 .into_iter()
440 .map(|c| (c.name.clone(), c))
441 .collect()
442 })
443}
444
445pub(crate) fn subsumption_closure<'tcx>(atom: &AtomProperty<'tcx>) -> Vec<AtomProperty<'tcx>> {
458 let Some(head_tag) = super::spec::tag_name_for_kind(atom.kind) else {
459 return Vec::new();
460 };
461
462 let mut out: Vec<AtomProperty<'tcx>> = Vec::new();
467 let mut seen: HashSet<(String, Vec<CompoundArg>)> = HashSet::new();
468 let mut queue: Vec<(String, Vec<CompoundArg>)> = Vec::new();
469 if let Some(spec) = builtin_subsumptions_map().get(head_tag) {
470 queue.extend(flatten_subsumption_body(&spec.body));
471 }
472 let mut cursor = 0;
473 while cursor < queue.len() {
474 let (tag, args) = queue[cursor].clone();
475 cursor += 1;
476 if !seen.insert((tag.clone(), args.clone())) {
477 continue;
478 }
479 if let Some(kind) = super::spec::find_spec(&tag).map(|s| s.kind)
480 && let Some(resolved) = resolve_subsumption_args(&args, atom) {
481 out.push(AtomProperty {
482 kind,
483 args: resolved,
484 contract_kind: ContractKind::Precond,
485 origin: None,
486 });
487 }
488 if let Some(spec) = builtin_subsumptions_map().get(&tag) {
491 for (child_tag, child_args) in flatten_subsumption_body(&spec.body) {
492 let substituted: Vec<CompoundArg> = child_args
493 .into_iter()
494 .map(|a| match a {
495 CompoundArg::Param(j) => args
496 .get(j)
497 .cloned()
498 .unwrap_or(CompoundArg::Lit(String::new())),
499 lit @ CompoundArg::Lit(_) => lit,
500 })
501 .collect();
502 queue.push((child_tag, substituted));
503 }
504 }
505 }
506 out
507}
508
509fn resolve_subsumption_args<'tcx>(
512 args: &[CompoundArg],
513 atom: &AtomProperty<'tcx>,
514) -> Option<Vec<PropertyArg<'tcx>>> {
515 let mut resolved: Vec<PropertyArg<'tcx>> = Vec::with_capacity(args.len());
516 for a in args {
517 match a {
518 CompoundArg::Param(i) => {
519 let pa = atom.args.get(*i)?;
520 resolved.push(pa.clone())
521 }
522 CompoundArg::Lit(s) => {
523 rap_warn!("subsumption body literal `{s}` unsupported; skipping");
524 return None;
525 }
526 }
527 }
528 Some(resolved)
529}
530
531fn flatten_subsumption_body(body: &CompoundBody) -> Vec<(String, Vec<CompoundArg>)> {
534 match body {
535 CompoundBody::And(parts) => parts.iter().flat_map(flatten_subsumption_body).collect(),
536 CompoundBody::Call { tag, args } => vec![(tag.clone(), args.clone())],
537 CompoundBody::Or(_) => {
538 rap_warn!("subsumption body must be a conjunction (no `||`); ignoring disjunction");
539 Vec::new()
540 }
541 }
542}
543
544fn builtin_compounds_map() -> &'static HashMap<String, CompoundSpec> {
548 static BUILTIN: OnceLock<HashMap<String, CompoundSpec>> = OnceLock::new();
549 BUILTIN.get_or_init(builtin_compounds)
550}
551
552fn user_compounds_map() -> &'static RwLock<HashMap<CrateNum, HashMap<String, CompoundSpec>>> {
558 static USER: OnceLock<RwLock<HashMap<CrateNum, HashMap<String, CompoundSpec>>>> =
559 OnceLock::new();
560 USER.get_or_init(|| RwLock::new(HashMap::new()))
561}
562
563fn builtin_compounds() -> HashMap<String, CompoundSpec> {
567 let mut map = HashMap::new();
568 for compound in parse_compounds(include_str!("assets/std-compound-properties.rs")) {
569 map.insert(compound.name.clone(), compound);
570 }
571 for compound in parse_compounds(include_str!("assets/user-compound-properties.rs")) {
572 map.insert(compound.name.clone(), compound);
573 }
574 map
575}
576
577pub(crate) fn find_compound(krate: CrateNum, name: &str) -> Option<CompoundSpec> {
580 if let Some(d) = user_compounds_map()
581 .read()
582 .ok()
583 .and_then(|t| t.get(&krate).and_then(|m| m.get(name).cloned()))
584 {
585 return Some(d);
586 }
587 builtin_compounds_map().get(name).cloned()
588}
589
590pub(crate) fn expand_compound<'tcx>(
592 tcx: rustc_middle::ty::TyCtxt<'tcx>,
593 def_id: rustc_hir::def_id::DefId,
594 name: &str,
595 exprs: &[Expr],
596) -> Option<Vec<Property<'tcx>>> {
597 let compound = find_compound(def_id.krate, name)?;
598 if exprs.len() < compound.required || exprs.len() > compound.params.len() {
599 let expected = if compound.required == compound.params.len() {
600 compound.params.len().to_string()
601 } else {
602 format!("{}-{}", compound.required, compound.params.len())
603 };
604 rap_warn!(
605 "contract compound `{name}` expects {expected} argument(s), got {}",
606 exprs.len()
607 );
608 return None;
609 }
610 if let Some(cycle) = find_compound_cycle(def_id.krate, name) {
614 rap_error!("contract compound cycle detected: {}", cycle.join(" -> "));
615 return None;
616 }
617 let mut props = expand_compound_body(
618 tcx,
619 def_id,
620 &compound.body,
621 exprs,
622 &compound.params,
623 &compound.param_tys,
624 );
625 let arg_strings: Vec<String> = exprs
629 .iter()
630 .enumerate()
631 .map(|(i, e)| {
632 let param_ty = compound.param_tys.get(i).map(|s| s.as_str()).unwrap_or("");
633 resolve_arg_string(tcx, def_id, param_ty, e)
634 })
635 .collect();
636 let meaning = if compound.doc.is_empty() {
637 None
638 } else {
639 Some(compound.doc.join(" "))
640 };
641 for p in &mut props {
642 p.set_origin(name.to_string(), arg_strings.clone(), meaning.clone());
643 }
644 Some(props)
645}
646
647pub(crate) fn find_compound_cycle(krate: CrateNum, start: &str) -> Option<Vec<String>> {
654 let mut combined = builtin_compounds_map().clone();
655 if let Ok(user) = user_compounds_map().read()
656 && let Some(crate_defs) = user.get(&krate)
657 {
658 for (name, compound) in crate_defs {
659 combined.insert(name.clone(), compound.clone());
660 }
661 }
662 find_cycle_in(start, &combined)
663}
664
665fn find_cycle_in(start: &str, table: &HashMap<String, CompoundSpec>) -> Option<Vec<String>> {
666 fn dfs(
667 name: &str,
668 table: &HashMap<String, CompoundSpec>,
669 path: &mut Vec<String>,
670 done: &mut HashSet<String>,
671 ) -> Option<Vec<String>> {
672 if let Some(pos) = path.iter().position(|n| n == name) {
673 let mut cycle: Vec<String> = path[pos..].to_vec();
674 cycle.push(name.to_string());
675 return Some(cycle);
676 }
677 if done.contains(name) {
678 return None;
679 }
680 let compound = table.get(name)?;
681 path.push(name.to_string());
682 for tag in compound_refs(&compound.body) {
683 if let Some(cycle) = dfs(&tag, table, path, done) {
684 return Some(cycle);
685 }
686 }
687 path.pop();
688 done.insert(name.to_string());
689 None
690 }
691
692 let mut path = Vec::new();
693 let mut done = HashSet::new();
694 dfs(start, table, &mut path, &mut done)
695}
696
697fn compound_refs(body: &CompoundBody) -> Vec<String> {
699 let mut out = Vec::new();
700 collect_compound_refs(body, &mut out);
701 out
702}
703
704fn collect_compound_refs(body: &CompoundBody, out: &mut Vec<String>) {
705 match body {
706 CompoundBody::And(parts) | CompoundBody::Or(parts) => {
707 for part in parts {
708 collect_compound_refs(part, out);
709 }
710 }
711 CompoundBody::Call { tag, .. } => out.push(tag.clone()),
712 }
713}
714
715pub(crate) fn register_compounds_from_source(krate: CrateNum, source: &str) -> usize {
720 let compounds = parse_compounds(source);
721 let n = compounds.len();
722 if n == 0 {
723 return 0;
724 }
725 let mut table = user_compounds_map()
726 .write()
727 .expect("compound table poisoned");
728 let entry = table.entry(krate).or_default();
729 for compound in compounds {
730 entry.insert(compound.name.clone(), compound);
731 }
732 n
733}
734
735pub(crate) fn register_compound_properties(tcx: rustc_middle::ty::TyCtxt<'_>) -> usize {
741 struct Visitor<'tcx> {
742 tcx: rustc_middle::ty::TyCtxt<'tcx>,
743 count: usize,
744 }
745
746 impl<'tcx> rustc_hir::intravisit::Visitor<'tcx> for Visitor<'tcx> {
747 fn visit_item(&mut self, item: &'tcx rustc_hir::Item<'tcx>) {
748 let attrs = self.tcx.hir_attrs(item.hir_id());
749 for attr in attrs {
750 if !is_def_property_attr(self.tcx, attr) {
751 continue;
752 }
753 let attr_str = crate::compat::attribute_to_string(self.tcx, attr);
754 if let Some(def_str) = extract_def_property_string(&attr_str) {
755 let n = register_compounds_from_source(LOCAL_CRATE, &def_str);
756 if n > 0 {
757 rap_info!(
758 "rapx: registered {n} contract compound(s) from #[rapx::def_property]"
759 );
760 }
761 self.count += n;
762 }
763 }
764 rustc_hir::intravisit::walk_item(self, item);
765 }
766 }
767
768 let mut v = Visitor { tcx, count: 0 };
769 tcx.hir_visit_all_item_likes_in_crate(&mut v);
770 v.count
771}
772
773fn is_def_property_attr(tcx: rustc_middle::ty::TyCtxt<'_>, attr: &Attribute) -> bool {
776 let name = Symbol::intern("def_property");
777 crate::compat::attribute_path_matches(tcx, attr, &[Symbol::intern("rapx"), name])
778 || crate::compat::attribute_path_matches(tcx, attr, &[name])
779}
780
781fn extract_def_property_string(attr_str: &str) -> Option<String> {
784 let attr = syn::parse::Parser::parse_str(super::attr::parse_outer_attr, attr_str).ok()?;
785 let syn::Meta::List(list) = attr.meta else {
786 return None;
787 };
788 let lit: syn::LitStr = syn::parse2(list.tokens).ok()?;
789 Some(lit.value())
790}