Skip to main content

rapx/contract/
pest.rs

1//! pest parser and semantic converter for the contract DSL.
2//!
3//! The grammar (`grammar.pest`) is the single source of truth for the
4//! contract-DSL surface; `ContractParser` is derived from it, and the
5//! conversion functions turn the resulting `Pairs<Rule>` into the contract AST
6//! (`types.rs` / `compound.rs`).
7//!
8//! Places (fields, projections) are bridged through the `place.rs` / `resolve.rs`
9//! helpers via a `syn` round-trip, since resolving a field name to a `Ty` still
10//! needs the rustc type context.  The arithmetic / call / if / constant layers
11//! are converted directly from the pest tree.
12
13use pest::Parser;
14use pest::iterators::Pair;
15use pest_derive::Parser;
16use rustc_hir::def_id::DefId;
17use rustc_middle::ty::TyCtxt;
18
19use super::compound::{CompoundArg, CompoundBody};
20use super::{ContractExpr, BinOp, NumericPredicate, UnaryOp, RelOp};
21use crate::util::name::match_ty_with_ident;
22
23/// Parser derived from `grammar.pest`.
24#[derive(Parser)]
25#[grammar = "contract/grammar.pest"]
26pub(crate) struct ContractParser;
27
28fn only_child(pair: Pair<Rule>) -> Pair<Rule> {
29    pair.into_inner()
30        .next()
31        .expect("expected a single child pair")
32}
33
34fn relop_from_str(s: &str) -> Option<RelOp> {
35    match s {
36        "==" => Some(RelOp::Eq),
37        "!=" => Some(RelOp::Ne),
38        "<" => Some(RelOp::Lt),
39        "<=" => Some(RelOp::Le),
40        ">" => Some(RelOp::Gt),
41        ">=" => Some(RelOp::Ge),
42        _ => None,
43    }
44}
45
46/// Parse a numeric expression (no comparison) into a `ContractExpr`.
47pub(crate) fn parse_expr_pest<'tcx>(
48    tcx: TyCtxt<'tcx>,
49    def_id: DefId,
50    text: &str,
51) -> ContractExpr<'tcx> {
52    let Ok(mut pairs) = ContractParser::parse(Rule::expr_input, text) else {
53        rap_warn!(
54            "contract expression not supported by grammar: {text} (in {})",
55            tcx.def_path_str(def_id)
56        );
57        return ContractExpr::Unknown;
58    };
59    conv_expr(tcx, def_id, only_child(pairs.next().expect("expr input")))
60}
61
62/// Parse a predicate (comparison / `!x.is_empty()` / bare expr) into a
63/// `NumericPredicate`.
64pub(crate) fn parse_predicate_pest<'tcx>(
65    tcx: TyCtxt<'tcx>,
66    def_id: DefId,
67    text: &str,
68) -> Option<NumericPredicate<'tcx>> {
69    let Ok(mut pairs) = ContractParser::parse(Rule::expr_input, text) else {
70        rap_warn!(
71            "contract predicate not supported by grammar: {text} (in {})",
72            tcx.def_path_str(def_id)
73        );
74        return None;
75    };
76    conv_predicate(tcx, def_id, only_child(pairs.next().expect("expr input")))
77}
78
79fn conv_expr<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
80    match pair.as_rule() {
81        Rule::expr => conv_expr(tcx, def_id, only_child(pair)),
82        Rule::if_expr => conv_if(tcx, def_id, pair),
83        Rule::cmp => {
84            let mut inner = pair.into_inner();
85            let lhs = conv_bit_or(tcx, def_id, inner.next().expect("cmp lhs"));
86            if inner.next().is_some() {
87                ContractExpr::Unknown
88            } else {
89                lhs
90            }
91        }
92        Rule::bit_or | Rule::bit_xor | Rule::bit_and | Rule::additive | Rule::multiplicative => {
93            conv_bit_or(tcx, def_id, pair)
94        }
95        Rule::unary => conv_unary(tcx, def_id, pair),
96        Rule::primary => conv_primary(tcx, def_id, pair),
97        Rule::call => conv_call(tcx, def_id, pair),
98        Rule::place => conv_place_bridge(tcx, def_id, pair),
99        Rule::const_path => conv_const_path(tcx, def_id, pair),
100        Rule::int => ContractExpr::Const(pair.as_str().parse::<u128>().unwrap_or(0)),
101        _ => ContractExpr::Unknown,
102    }
103}
104
105fn conv_predicate<'tcx>(
106    tcx: TyCtxt<'tcx>,
107    def_id: DefId,
108    pair: Pair<Rule>,
109) -> Option<NumericPredicate<'tcx>> {
110    match pair.as_rule() {
111        Rule::expr | Rule::cond => conv_predicate(tcx, def_id, only_child(pair)),
112        Rule::cmp => {
113            let mut inner = pair.into_inner();
114            let lhs = conv_bit_or(tcx, def_id, inner.next()?);
115            match inner.next() {
116                Some(relop_pair) => {
117                    let op = relop_from_str(relop_pair.as_str())?;
118                    let rhs = conv_bit_or(tcx, def_id, inner.next()?);
119                    Some(NumericPredicate::new(lhs, op, rhs))
120                }
121                None => None,
122            }
123        }
124        Rule::not_is_empty => {
125            let mut inner = pair.into_inner();
126            let base_text = inner.next()?.as_str().to_string();
127            Some(NumericPredicate::new(
128                super::resolve::parse_is_empty_call(tcx, def_id, &base_text, "pest"),
129                RelOp::Eq,
130                ContractExpr::Const(0),
131            ))
132        }
133        _ => None,
134    }
135}
136
137fn conv_if<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
138    let mut inner = pair.into_inner();
139    let cond_pair = inner.next().expect("if cond");
140    let then_pair = inner.next().expect("if then");
141    let else_pair = inner.next().expect("if else");
142    let Some(cond) = conv_predicate(tcx, def_id, cond_pair) else {
143        return ContractExpr::Unknown;
144    };
145    let then_expr = conv_expr(tcx, def_id, then_pair);
146    let else_expr = conv_expr(tcx, def_id, else_pair);
147    ContractExpr::If {
148        cond: Box::new(cond),
149        then_expr: Box::new(then_expr),
150        else_expr: Box::new(else_expr),
151    }
152}
153
154fn op_from_str(op: &str) -> Option<BinOp> {
155    match op {
156        "+" => Some(BinOp::Add),
157        "-" => Some(BinOp::Sub),
158        "*" => Some(BinOp::Mul),
159        "/" => Some(BinOp::Div),
160        "%" => Some(BinOp::Rem),
161        "&" => Some(BinOp::BitAnd),
162        "|" => Some(BinOp::BitOr),
163        "^" => Some(BinOp::BitXor),
164        _ => None,
165    }
166}
167
168fn conv_left_assoc<'tcx>(
169    tcx: TyCtxt<'tcx>,
170    def_id: DefId,
171    pair: Pair<Rule>,
172    operand: impl Fn(TyCtxt<'tcx>, DefId, Pair<Rule>) -> ContractExpr<'tcx>,
173) -> ContractExpr<'tcx> {
174    let mut inner = pair.into_inner();
175    let mut acc = operand(tcx, def_id, inner.next().expect("first operand"));
176    while let Some(op_pair) = inner.next() {
177        let Some(op) = op_from_str(op_pair.as_str()) else {
178            return ContractExpr::Unknown;
179        };
180        let rhs = operand(tcx, def_id, inner.next().expect("rhs operand"));
181        acc = ContractExpr::Binary {
182            op,
183            lhs: Box::new(acc),
184            rhs: Box::new(rhs),
185        };
186    }
187    acc
188}
189
190fn conv_bit_or<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
191    match pair.as_rule() {
192        Rule::bit_or => conv_left_assoc(tcx, def_id, pair, conv_bit_xor),
193        _ => conv_bit_xor(tcx, def_id, pair),
194    }
195}
196
197fn conv_bit_xor<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
198    match pair.as_rule() {
199        Rule::bit_xor => conv_left_assoc(tcx, def_id, pair, conv_bit_and),
200        _ => conv_bit_and(tcx, def_id, pair),
201    }
202}
203
204fn conv_bit_and<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
205    match pair.as_rule() {
206        Rule::bit_and => conv_left_assoc(tcx, def_id, pair, conv_additive),
207        _ => conv_additive(tcx, def_id, pair),
208    }
209}
210
211fn conv_additive<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
212    match pair.as_rule() {
213        Rule::additive => conv_left_assoc(tcx, def_id, pair, conv_multiplicative),
214        _ => conv_multiplicative(tcx, def_id, pair),
215    }
216}
217
218fn conv_multiplicative<'tcx>(
219    tcx: TyCtxt<'tcx>,
220    def_id: DefId,
221    pair: Pair<Rule>,
222) -> ContractExpr<'tcx> {
223    match pair.as_rule() {
224        Rule::multiplicative => conv_left_assoc(tcx, def_id, pair, conv_unary),
225        _ => conv_unary(tcx, def_id, pair),
226    }
227}
228
229fn conv_unary<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
230    let mut inner = pair.into_inner();
231    let first = inner.next().expect("unary operand");
232    match first.as_rule() {
233        Rule::unop => {
234            let op = match first.as_str() {
235                "!" => UnaryOp::Not,
236                "-" => UnaryOp::Neg,
237                _ => return ContractExpr::Unknown,
238            };
239            let operand = conv_unary(tcx, def_id, inner.next().expect("unary inner"));
240            ContractExpr::Unary {
241                op,
242                expr: Box::new(operand),
243            }
244        }
245        _ => conv_primary(tcx, def_id, first),
246    }
247}
248
249fn conv_primary<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
250    let inner = only_child(pair);
251    match inner.as_rule() {
252        Rule::int => inner
253            .as_str()
254            .parse::<u128>()
255            .map(ContractExpr::Const)
256            .unwrap_or(ContractExpr::Unknown),
257        Rule::call => conv_call(tcx, def_id, inner),
258        Rule::size_of_call => conv_size_of_call(tcx, def_id, inner),
259        Rule::const_path => conv_const_path(tcx, def_id, inner),
260        Rule::place => conv_place_bridge(tcx, def_id, inner),
261        Rule::expr => conv_expr(tcx, def_id, inner),
262        _ => ContractExpr::Unknown,
263    }
264}
265
266/// Convert `size_of::<T>()` / `align_of::<T>()` (optionally `std::mem::` /
267/// `core::mem::` prefixed) into `SizeOf` / `AlignOf`.
268fn conv_size_of_call<'tcx>(
269    tcx: TyCtxt<'tcx>,
270    def_id: DefId,
271    pair: Pair<Rule>,
272) -> ContractExpr<'tcx> {
273    let text = pair.as_str();
274    let (kind, rest) = if text.contains("align_of") {
275        ("align_of", text.split("align_of").nth(1).unwrap_or(""))
276    } else {
277        ("size_of", text.split("size_of").nth(1).unwrap_or(""))
278    };
279    let ty_name = rest
280        .find('<')
281        .and_then(|lt| {
282            rest[lt + 1..]
283                .find('>')
284                .map(|gt| rest[lt + 1..lt + 1 + gt].trim().to_string())
285        })
286        .unwrap_or_default();
287    let Some(ty) = match_ty_with_ident(tcx, def_id, ty_name) else {
288        return ContractExpr::Unknown;
289    };
290    match kind {
291        "size_of" => ContractExpr::SizeOf(ty),
292        _ => ContractExpr::AlignOf(ty),
293    }
294}
295
296fn conv_call<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
297    let mut inner = pair.into_inner();
298    let builtin = inner.next().expect("builtin").as_str().to_string();
299    let args: Vec<Pair<Rule>> = match inner.next() {
300        Some(arg_list) => arg_list.into_inner().collect(),
301        None => Vec::new(),
302    };
303    match builtin.as_str() {
304        "size_of" | "align_of" => {
305            let ty_name = args
306                .first()
307                .map(|a| a.as_str().trim().to_string())
308                .unwrap_or_default();
309            let Some(ty) = match_ty_with_ident(tcx, def_id, ty_name) else {
310                return ContractExpr::Unknown;
311            };
312            match builtin.as_str() {
313                "size_of" => ContractExpr::SizeOf(ty),
314                _ => ContractExpr::AlignOf(ty),
315            }
316        }
317        "len" => {
318            let [arg] = args.as_slice() else {
319                return ContractExpr::Unknown;
320            };
321            let Ok(receiver) = syn::parse_str::<syn::Expr>(arg.as_str()) else {
322                return ContractExpr::Unknown;
323            };
324            super::resolve::parse_len_call(tcx, def_id, &receiver, "pest")
325        }
326        "min" | "max" => {
327            if args.len() != 2 {
328                return ContractExpr::Unknown;
329            }
330            let a = conv_arg_expr(tcx, def_id, args[0].clone());
331            let b = conv_arg_expr(tcx, def_id, args[1].clone());
332            let op = if builtin == "min" {
333                BinOp::Min
334            } else {
335                BinOp::Max
336            };
337            ContractExpr::Binary {
338                op,
339                lhs: Box::new(a),
340                rhs: Box::new(b),
341            }
342        }
343        _ => ContractExpr::Unknown,
344    }
345}
346
347fn conv_arg_expr<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, arg: Pair<Rule>) -> ContractExpr<'tcx> {
348    let inner = only_child(arg);
349    match inner.as_rule() {
350        Rule::expr => conv_expr(tcx, def_id, inner),
351        _ => ContractExpr::Unknown,
352    }
353}
354
355fn conv_const_path<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, pair: Pair<Rule>) -> ContractExpr<'tcx> {
356    let text = pair.as_str();
357    let Some((ty_name, which)) = text.rsplit_once("::") else {
358        return ContractExpr::Unknown;
359    };
360    let ty_name = ty_name.trim();
361    let which = which.trim();
362    let Some(ty) = super::resolve::resolve_type_name(tcx, def_id, ty_name) else {
363        return ContractExpr::Unknown;
364    };
365    // `T::BITS` is the bit width, i.e. `size_of::<T>() * 8`.
366    if which == "BITS" {
367        return ContractExpr::Binary {
368            op: BinOp::Mul,
369            lhs: Box::new(ContractExpr::SizeOf(ty)),
370            rhs: Box::new(ContractExpr::Const(8)),
371        };
372    }
373    let Some((min, max)) = super::resolve::int_type_min_max(tcx, ty) else {
374        return ContractExpr::Unknown;
375    };
376    match which {
377        "MAX" => ContractExpr::Const(max),
378        "MIN" => {
379            // Signed integers: `int_type_min_max` returns the negated magnitude
380            // (`-(MIN) == 2^(bits-1)`) as a `u128` because it cannot represent
381            // the negative `MIN`. Emit an explicit negation so `i32::MIN`
382            // resolves to `-2147483648` rather than `+2147483648`.
383            if let rustc_middle::ty::TyKind::Int(_) = ty.kind() {
384                ContractExpr::Unary {
385                    op: UnaryOp::Neg,
386                    expr: Box::new(ContractExpr::Const(min)),
387                }
388            } else {
389                ContractExpr::Const(min)
390            }
391        }
392        _ => ContractExpr::Unknown,
393    }
394}
395
396/// Bridge a place through the syn-based parser for field and method projections.
397fn conv_place_bridge<'tcx>(
398    tcx: TyCtxt<'tcx>,
399    def_id: DefId,
400    pair: Pair<Rule>,
401) -> ContractExpr<'tcx> {
402    let text = pair.as_str();
403    let Ok(expr) = syn::parse_str::<syn::Expr>(text) else {
404        rap_warn!(
405            "contract place not parseable: {text} (in {})",
406            tcx.def_path_str(def_id)
407        );
408        return ContractExpr::Unknown;
409    };
410    super::resolve::parse_contract_expr(tcx, def_id, &expr, "pest")
411}
412
413// ── Compound-body conversion (`pred!` / `def_body`) ─────────────────────────
414
415/// Parse a compound-property body into a DNF tree.  `||` binds looser than `&&`.
416pub(crate) fn parse_compound_body(body: &str, params: &[String]) -> Option<CompoundBody> {
417    let mut pairs = ContractParser::parse(Rule::def_body, body).ok()?;
418    let def_body = pairs.next()?;
419    let or_expr = def_body.into_inner().next()?;
420    Some(conv_compound_or(or_expr, params))
421}
422
423fn conv_compound_or(pair: Pair<Rule>, params: &[String]) -> CompoundBody {
424    let parts: Vec<CompoundBody> = pair
425        .into_inner()
426        .map(|p| conv_compound_and(p, params))
427        .collect();
428    singleton_or_wrap(parts, CompoundBody::Or)
429}
430
431fn conv_compound_and(pair: Pair<Rule>, params: &[String]) -> CompoundBody {
432    let parts: Vec<CompoundBody> = pair
433        .into_inner()
434        .map(|p| conv_compound_leaf(p, params))
435        .collect();
436    singleton_or_wrap(parts, CompoundBody::And)
437}
438
439/// Unwrap a single-element list, otherwise wrap it with `wrap`.
440fn singleton_or_wrap(
441    parts: Vec<CompoundBody>,
442    wrap: fn(Vec<CompoundBody>) -> CompoundBody,
443) -> CompoundBody {
444    if parts.len() == 1 {
445        parts.into_iter().next().unwrap()
446    } else {
447        wrap(parts)
448    }
449}
450
451fn conv_compound_leaf(pair: Pair<Rule>, params: &[String]) -> CompoundBody {
452    match pair.into_inner().next() {
453        Some(inner) => match inner.as_rule() {
454            Rule::tag_call => conv_compound_call(inner, params),
455            Rule::or_expr => conv_compound_or(inner, params),
456            _ => CompoundBody::Call {
457                tag: String::new(),
458                args: Vec::new(),
459            },
460        },
461        None => CompoundBody::Call {
462            tag: String::new(),
463            args: Vec::new(),
464        },
465    }
466}
467
468fn conv_compound_call(pair: Pair<Rule>, params: &[String]) -> CompoundBody {
469    let mut inner = pair.into_inner();
470    let Some(tag) = inner.next() else {
471        return CompoundBody::Call {
472            tag: String::new(),
473            args: Vec::new(),
474        };
475    };
476    let tag = tag.as_str().to_string();
477    let args = match inner.next() {
478        Some(arg_list) => arg_list
479            .into_inner()
480            .map(|arg| {
481                let text = arg.as_str().trim().to_string();
482                match params.iter().position(|n| n == &text) {
483                    Some(i) => CompoundArg::Param(i),
484                    None => CompoundArg::Lit(text),
485                }
486            })
487            .collect(),
488        None => Vec::new(),
489    };
490    CompoundBody::Call { tag, args }
491}
492
493#[cfg(test)]
494mod tests {
495    use super::{ContractParser, Rule, only_child};
496    use pest::Parser;
497
498    #[test]
499    fn length_spellings_are_supported() {
500        assert!(ContractParser::parse(Rule::expr_input, "b.len()").is_ok());
501        assert!(ContractParser::parse(Rule::expr_input, "self_.len()").is_ok());
502        assert!(ContractParser::parse(Rule::expr_input, "self_.0").is_ok());
503        assert!(ContractParser::parse(Rule::expr_input, "return.0").is_ok());
504        assert!(ContractParser::parse(Rule::expr_input, "Arg_2.size").is_ok());
505        assert!(ContractParser::parse(Rule::expr_input, "len(b)").is_ok());
506        assert!(ContractParser::parse(Rule::expr_input, "len(b) + 1").is_ok());
507    }
508
509    #[test]
510    fn spaced_is_empty_is_a_predicate() {
511        let input = ContractParser::parse(Rule::expr_input, "! self . is_empty ()")
512            .unwrap()
513            .next()
514            .unwrap();
515        let expr = only_child(input);
516        assert_eq!(only_child(expr).as_rule(), Rule::not_is_empty);
517    }
518}