Skip to main content

rapx/contract/
render.rs

1//! User-facing rendering of contract data structures.
2//!
3//! Converts `ContractPlace`, `ContractExpr`, `NumericPredicate`, `PropertyArg`
4//! and `Property` into readable strings for reports and debug output.  Kept
5//! separate from the data model (`types.rs`) so the model stays
6//! presentation-free.
7
8use rustc_hir::def_id::DefId;
9use rustc_middle::ty::TyCtxt;
10
11use super::{
12    ContractExpr, ContractPlace, ContractProjection, BinOp, NumericPredicate,
13    UnaryOp, PlaceBase, Property, PropertyArg, PropertyKind, RelOp,
14};
15
16/// Best-effort source snippet for a MIR local's declaration, if its function
17/// MIR is available and the local index is in range.
18fn local_snippet<'tcx>(
19    tcx: TyCtxt<'tcx>,
20    fn_def_id: Option<DefId>,
21    mir_local: usize,
22) -> Option<String> {
23    let fn_def_id = fn_def_id?;
24    if !tcx.is_mir_available(fn_def_id) {
25        return None;
26    }
27    let body = tcx.optimized_mir(fn_def_id);
28    if mir_local >= body.local_decls.len() {
29        return None;
30    }
31    let local = rustc_middle::mir::Local::from_usize(mir_local);
32    let span = body.local_decls[local].source_info.span;
33    tcx.sess.source_map().span_to_snippet(span).ok()
34}
35
36impl ContractPlace {
37    pub(crate) fn display_user_friendly<'tcx>(
38        &self,
39        tcx: TyCtxt<'tcx>,
40        struct_def_id: Option<DefId>,
41        fn_def_id: Option<DefId>,
42    ) -> String {
43        let has_projections = !self.projections.is_empty();
44
45        let base_str = match self.base {
46            PlaceBase::Return => {
47                if has_projections {
48                    String::new()
49                } else {
50                    "return".to_string()
51                }
52            }
53            PlaceBase::Arg(idx) => local_snippet(tcx, fn_def_id, idx + 1)
54                .filter(|s| !s.is_empty())
55                .unwrap_or_else(|| format!("arg{}", idx)),
56            PlaceBase::Local(n) => {
57                if n == 0 {
58                    "return".to_string()
59                } else {
60                    local_snippet(tcx, fn_def_id, n).unwrap_or_else(|| format!("arg{}", n))
61                }
62            }
63        };
64
65        let base_str = base_str
66            .strip_prefix("&mut ")
67            .unwrap_or(&base_str)
68            .to_string();
69        let base_str = base_str.strip_prefix("&").unwrap_or(&base_str).to_string();
70
71        if self.projections.is_empty() {
72            return base_str;
73        }
74
75        let mut result = base_str;
76        for projection in &self.projections {
77            match projection {
78                ContractProjection::Field { index } => {
79                    let field_name = crate::util::name::resolve_field_name(tcx, index, struct_def_id);
80                    if result.is_empty() {
81                        result = field_name;
82                    } else {
83                        result.push_str(&format!(".{}", field_name));
84                    }
85                }
86                ContractProjection::Downcast { .. } => {
87                    result.push_str(".unwrap_some()");
88                }
89                ContractProjection::ForEach => {
90                    result.push_str(".iter()");
91                }
92            }
93        }
94        result
95    }
96}
97
98impl<'tcx> NumericPredicate<'tcx> {
99    pub(crate) fn display_user_friendly(
100        &self,
101        tcx: TyCtxt<'tcx>,
102        struct_def_id: Option<DefId>,
103        fn_def_id: Option<DefId>,
104    ) -> String {
105        let op_str = match self.op {
106            RelOp::Eq => "==",
107            RelOp::Ne => "!=",
108            RelOp::Lt => "<",
109            RelOp::Le => "<=",
110            RelOp::Gt => ">",
111            RelOp::Ge => ">=",
112        };
113        format!(
114            "{} {} {}",
115            display_expr_user_friendly(&self.lhs, tcx, struct_def_id, fn_def_id),
116            op_str,
117            display_expr_user_friendly(&self.rhs, tcx, struct_def_id, fn_def_id),
118        )
119    }
120}
121
122pub(crate) fn display_expr_user_friendly<'tcx>(
123    expr: &ContractExpr<'tcx>,
124    tcx: TyCtxt<'tcx>,
125    struct_def_id: Option<DefId>,
126    fn_def_id: Option<DefId>,
127) -> String {
128    match expr {
129        ContractExpr::Const(n) => format!("{n}"),
130        ContractExpr::ConstParam { name, .. } => name.clone(),
131        ContractExpr::Place(p) => p.display_user_friendly(tcx, struct_def_id, fn_def_id),
132        ContractExpr::SizeOf(ty) => format!("size_of({ty})"),
133        ContractExpr::AlignOf(ty) => format!("align_of({ty})"),
134        ContractExpr::Len(e, _) => format!(
135            "{}.len()",
136            display_expr_user_friendly(e, tcx, struct_def_id, fn_def_id)
137        ),
138        ContractExpr::IsEmpty(e, _) => format!(
139            "{}.is_empty()",
140            display_expr_user_friendly(e, tcx, struct_def_id, fn_def_id)
141        ),
142        ContractExpr::IndexAccess { slice, index } => {
143            format!(
144                "{}[{}]",
145                display_expr_user_friendly(slice, tcx, struct_def_id, fn_def_id),
146                display_expr_user_friendly(index, tcx, struct_def_id, fn_def_id),
147            )
148        }
149        ContractExpr::Binary { op, lhs, rhs } => {
150            let lhs_str = display_expr_user_friendly(lhs, tcx, struct_def_id, fn_def_id);
151            let rhs_str = display_expr_user_friendly(rhs, tcx, struct_def_id, fn_def_id);
152            let op_str = match op {
153                BinOp::Min => return format!("min({lhs_str}, {rhs_str})"),
154                BinOp::Max => return format!("max({lhs_str}, {rhs_str})"),
155                BinOp::Add => "+",
156                BinOp::Sub => "-",
157                BinOp::Mul => "*",
158                BinOp::Div => "/",
159                BinOp::Rem => "%",
160                BinOp::BitAnd => "&",
161                BinOp::BitOr => "|",
162                BinOp::BitXor => "^",
163            };
164            format!("{lhs_str} {op_str} {rhs_str}")
165        }
166        ContractExpr::Unary { op, expr } => {
167            let op_str = match op {
168                UnaryOp::Not => "!",
169                UnaryOp::Neg => "-",
170            };
171            format!(
172                "{}{}",
173                op_str,
174                display_expr_user_friendly(expr, tcx, struct_def_id, fn_def_id),
175            )
176        }
177        ContractExpr::If {
178            cond,
179            then_expr,
180            else_expr,
181        } => {
182            format!(
183                "if {} {{ {} }} else {{ {} }}",
184                cond.display_user_friendly(tcx, struct_def_id, fn_def_id),
185                display_expr_user_friendly(then_expr, tcx, struct_def_id, fn_def_id),
186                display_expr_user_friendly(else_expr, tcx, struct_def_id, fn_def_id),
187            )
188        }
189        _ => format!("{:?}", expr),
190    }
191}
192
193impl<'tcx> PropertyArg<'tcx> {
194    pub(crate) fn display_for_report(
195        &self,
196        tcx: TyCtxt<'tcx>,
197        struct_def_id: Option<DefId>,
198        fn_def_id: Option<DefId>,
199    ) -> String {
200        match self {
201            PropertyArg::Ty(ty) => format!("{}", ty),
202            PropertyArg::Expr(expr) | PropertyArg::ForEach(expr) => {
203                display_expr_user_friendly(expr, tcx, struct_def_id, fn_def_id)
204            }
205            PropertyArg::Predicates(preds) => {
206                let p: Vec<_> = preds
207                    .iter()
208                    .map(|pred| pred.display_user_friendly(tcx, struct_def_id, fn_def_id))
209                    .collect();
210                p.join(" && ")
211            }
212            PropertyArg::Ident(s) => s.clone(),
213            PropertyArg::Region(r) => format!("'{r}"),
214        }
215    }
216}
217
218impl<'tcx> Property<'tcx> {
219    pub(crate) fn display_for_report(
220        &self,
221        tcx: TyCtxt<'tcx>,
222        struct_def_id: Option<DefId>,
223        fn_def_id: Option<DefId>,
224    ) -> String {
225        // Compound property (e.g. `Ptr2Ref`, `Deref`, user `pred!`): show
226        // it as a single `name(args)` entry instead of its underlying primitives.
227        if let Some(origin) = self.origin() {
228            return format!("{}({})", origin.name, origin.args.join(", "));
229        }
230
231        let kind_str = match self.kind() {
232            Some(k) => format!("{k:?}"),
233            None => {
234                if matches!(self, Property::And(_)) {
235                    "And".to_string()
236                } else {
237                    "Or".to_string()
238                }
239            }
240        };
241
242        if matches!(self.kind(), Some(PropertyKind::InBound))
243            && let Some(ContractExpr::IndexAccess { slice, index }) = self.args().first().and_then(PropertyArg::expr)
244        {
245            let slice_str = display_expr_user_friendly(slice, tcx, struct_def_id, fn_def_id);
246            let index_str = display_expr_user_friendly(index, tcx, struct_def_id, fn_def_id);
247            return format!("{}({}, {})", kind_str, slice_str, index_str);
248        }
249
250        if matches!(self.kind(), Some(PropertyKind::ValidNum))
251            && let Some(PropertyArg::Predicates(preds)) = self.args().first()
252        {
253            let inner: Vec<String> = preds
254                .iter()
255                .map(|pred| pred.display_user_friendly(tcx, struct_def_id, fn_def_id))
256                .collect();
257            if inner.is_empty() {
258                return kind_str.to_string();
259            }
260            return format!("{}({})", kind_str, inner.join(", "));
261        }
262
263        let args: Vec<String> = self
264            .args()
265            .iter()
266            .map(|arg| arg.display_for_report(tcx, struct_def_id, fn_def_id))
267            .collect();
268        if args.is_empty() {
269            kind_str
270        } else {
271            format!("{}({})", kind_str, args.join(", "))
272        }
273    }
274}