Skip to main content

rustc_builtin_macros/assert/
context.rs

1use rustc_ast::token::{self, Delimiter, IdentKind};
2use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree};
3use rustc_ast::{
4    BinOpKind, BorrowKind, DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, ItemKind, MacCall, Mutability,
5    Path, Stmt, StructRest, UnOp, UseTree, UseTreeAndId, UseTreeKind,
6};
7use rustc_ast_pretty::pprust;
8use rustc_data_structures::fx::FxHashSet;
9use rustc_expand::base::ExtCtxt;
10use rustc_span::{Ident, Span, Symbol, sym};
11use thin_vec::{ThinVec, thin_vec};
12
13pub(super) struct Context<'cx, 'a> {
14    // An optimization.
15    //
16    // Elements that aren't consumed (PartialEq, PartialOrd, ...) can be copied **after** the
17    // `assert!` expression fails rather than copied on-the-fly.
18    best_case_captures: Vec<Stmt>,
19    // Top-level `let captureN = Capture::new()` statements
20    capture_decls: Vec<Capture>,
21    cx: &'cx ExtCtxt<'a>,
22    // Formatting string used for debugging
23    fmt_string: String,
24    // If the current expression being visited consumes itself. Used to construct
25    // `best_case_captures`.
26    is_consumed: bool,
27    // Top-level `let __local_bindN = &expr` statements
28    local_bind_decls: Vec<Stmt>,
29    // Used to avoid capturing duplicated paths
30    //
31    // ```rust
32    // let a = 1i32;
33    // assert!(add(a, a) == 3);
34    // ```
35    paths: FxHashSet<Ident>,
36    span: Span,
37}
38
39impl<'cx, 'a> Context<'cx, 'a> {
40    pub(super) fn new(cx: &'cx ExtCtxt<'a>, span: Span) -> Self {
41        Self {
42            best_case_captures: <_>::default(),
43            capture_decls: <_>::default(),
44            cx,
45            fmt_string: <_>::default(),
46            is_consumed: true,
47            local_bind_decls: <_>::default(),
48            paths: <_>::default(),
49            span,
50        }
51    }
52
53    /// Builds the whole `assert!` expression. For example, `let elem = 1; assert!(elem == 1);` expands to:
54    ///
55    /// ```rust
56    /// let elem = 1;
57    /// {
58    ///   #[allow(unused_imports)]
59    ///   use ::core::asserting::{TryCaptureGeneric, TryCapturePrintable};
60    ///   let mut __capture0 = ::core::asserting::Capture::new();
61    ///   let __local_bind0 = &elem;
62    ///   if !(
63    ///     *{
64    ///       (&::core::asserting::Wrapper(__local_bind0)).try_capture(&mut __capture0);
65    ///       __local_bind0
66    ///     } == 1
67    ///   ) {
68    ///     panic!("Assertion failed: elem == 1\nWith captures:\n  elem = {:?}", __capture0)
69    ///   }
70    /// }
71    /// ```
72    pub(super) fn build(mut self, mut cond_expr: Box<Expr>, panic_path: Path) -> Box<Expr> {
73        let expr_str = pprust::expr_to_string(&cond_expr);
74        self.manage_cond_expr(&mut cond_expr);
75        let initial_imports = self.build_initial_imports();
76        let panic = self.build_panic(&expr_str, panic_path);
77        let cond_expr_with_unlikely = self.build_unlikely(cond_expr);
78
79        let Self { best_case_captures, capture_decls, cx, local_bind_decls, span, .. } = self;
80
81        let mut assert_then_stmts = ThinVec::with_capacity(2);
82        assert_then_stmts.extend(best_case_captures);
83        assert_then_stmts.push(self.cx.stmt_expr(panic));
84        let assert_then = self.cx.block(span, assert_then_stmts);
85
86        let mut stmts = ThinVec::with_capacity(4);
87        stmts.push(initial_imports);
88        stmts.extend(capture_decls.into_iter().map(|c| c.decl));
89        stmts.extend(local_bind_decls);
90        stmts.push(
91            cx.stmt_expr(cx.expr(span, ExprKind::If(cond_expr_with_unlikely, assert_then, None))),
92        );
93        cx.expr_block(cx.block(span, stmts))
94    }
95
96    /// Initial **trait** imports
97    ///
98    /// use ::core::asserting::{ ... };
99    fn build_initial_imports(&self) -> Stmt {
100        let nested_tree = |this: &Self, sym| UseTreeAndId {
101            inner: UseTree {
102                prefix: this.cx.path_name(this.span, sym),
103                kind: UseTreeKind::Simple(None),
104            },
105            id: DUMMY_NODE_ID,
106        };
107        self.cx.stmt_item(
108            self.span,
109            self.cx.item(
110                self.span,
111                {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self.cx.attr_nested_word(sym::allow, sym::unused_imports,
            self.span));
    vec
}thin_vec![self.cx.attr_nested_word(sym::allow, sym::unused_imports, self.span)],
112                ItemKind::Use(UseTree {
113                    prefix: self.cx.std_path(self.span, &[sym::asserting]),
114                    kind: UseTreeKind::Nested {
115                        items: {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(nested_tree(self, sym::TryCaptureGeneric));
    vec.push(nested_tree(self, sym::TryCapturePrintable));
    vec
}thin_vec![
116                            nested_tree(self, sym::TryCaptureGeneric),
117                            nested_tree(self, sym::TryCapturePrintable),
118                        ],
119                        span: self.span,
120                    },
121                }),
122            ),
123        )
124    }
125
126    /// Takes the conditional expression of `assert!` and then wraps it inside `unlikely`
127    fn build_unlikely(&self, cond_expr: Box<Expr>) -> Box<Expr> {
128        self.cx.expr_call_intrinsic(
129            self.span,
130            sym::unlikely,
131            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self.cx.expr(self.span, ExprKind::Unary(UnOp::Not, cond_expr)));
    vec
}thin_vec![self.cx.expr(self.span, ExprKind::Unary(UnOp::Not, cond_expr))],
132        )
133    }
134
135    /// The necessary custom `panic!(...)` expression.
136    ///
137    /// panic!(
138    ///     "Assertion failed: ... \n With expansion: ...",
139    ///     __capture0,
140    ///     ...
141    /// );
142    fn build_panic(&self, expr_str: &str, panic_path: Path) -> Box<Expr> {
143        let escaped_expr_str = escape_to_fmt(expr_str);
144        let initial = [
145            TokenTree::token_joint(
146                token::Literal(token::Lit {
147                    kind: token::LitKind::Str,
148                    symbol: Symbol::intern(&if self.fmt_string.is_empty() {
149                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Assertion failed: {0}",
                escaped_expr_str))
    })format!("Assertion failed: {escaped_expr_str}")
150                    } else {
151                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Assertion failed: {1}\nWith captures:\n{0}",
                self.fmt_string, escaped_expr_str))
    })format!(
152                            "Assertion failed: {escaped_expr_str}\nWith captures:\n{}",
153                            self.fmt_string
154                        )
155                    }),
156                    suffix: None,
157                }),
158                self.span,
159            ),
160            TokenTree::token_alone(token::Comma, self.span),
161        ];
162        let captures = self.capture_decls.iter().flat_map(|cap| {
163            [
164                TokenTree::token_joint(
165                    token::Ident(cap.ident.name, IdentKind::Normal),
166                    cap.ident.span,
167                ),
168                TokenTree::token_alone(token::Comma, self.span),
169            ]
170        });
171        self.cx.expr(
172            self.span,
173            ExprKind::MacCall(Box::new(MacCall {
174                path: panic_path,
175                args: Box::new(DelimArgs {
176                    dspan: DelimSpan::from_single(self.span),
177                    delim: Delimiter::Parenthesis,
178                    tokens: initial.into_iter().chain(captures).collect::<TokenStream>(),
179                }),
180            })),
181        )
182    }
183
184    /// Recursive function called until `cond_expr` and `fmt_str` are fully modified.
185    ///
186    /// See [Self::manage_initial_capture] and [Self::manage_try_capture]
187    fn manage_cond_expr(&mut self, expr: &mut Box<Expr>) {
188        match &mut expr.kind {
189            ExprKind::AddrOf(_, mutability, local_expr) => {
190                self.with_is_consumed_management(#[allow(non_exhaustive_omitted_patterns)] match mutability {
    Mutability::Mut => true,
    _ => false,
}matches!(mutability, Mutability::Mut), |this| {
191                    this.manage_cond_expr(local_expr)
192                });
193            }
194            ExprKind::Array(local_exprs) => {
195                for local_expr in local_exprs {
196                    self.manage_cond_expr(local_expr);
197                }
198            }
199            ExprKind::Binary(op, lhs, rhs) => {
200                self.with_is_consumed_management(
201                    #[allow(non_exhaustive_omitted_patterns)] match op.node {
    BinOpKind::Add | BinOpKind::And | BinOpKind::BitAnd | BinOpKind::BitOr |
        BinOpKind::BitXor | BinOpKind::Div | BinOpKind::Mul | BinOpKind::Or |
        BinOpKind::Rem | BinOpKind::Shl | BinOpKind::Shr | BinOpKind::Sub =>
        true,
    _ => false,
}matches!(
202                        op.node,
203                        BinOpKind::Add
204                            | BinOpKind::And
205                            | BinOpKind::BitAnd
206                            | BinOpKind::BitOr
207                            | BinOpKind::BitXor
208                            | BinOpKind::Div
209                            | BinOpKind::Mul
210                            | BinOpKind::Or
211                            | BinOpKind::Rem
212                            | BinOpKind::Shl
213                            | BinOpKind::Shr
214                            | BinOpKind::Sub
215                    ),
216                    |this| {
217                        this.manage_cond_expr(lhs);
218                        this.manage_cond_expr(rhs);
219                    },
220                );
221            }
222            ExprKind::Call(_, local_exprs) => {
223                for local_expr in local_exprs {
224                    self.manage_cond_expr(local_expr);
225                }
226            }
227            ExprKind::Cast(local_expr, _) => {
228                self.manage_cond_expr(local_expr);
229            }
230            ExprKind::If(local_expr, _, _) => {
231                self.manage_cond_expr(local_expr);
232            }
233            ExprKind::Index(prefix, suffix, _) => {
234                self.manage_cond_expr(prefix);
235                self.manage_cond_expr(suffix);
236            }
237            ExprKind::Let(_, local_expr, _, _) => {
238                self.manage_cond_expr(local_expr);
239            }
240            ExprKind::Match(local_expr, ..) => {
241                self.manage_cond_expr(local_expr);
242            }
243            ExprKind::MethodCall(call) => {
244                for arg in &mut call.args {
245                    self.manage_cond_expr(arg);
246                }
247            }
248            ExprKind::Move(local_expr, _) => {
249                self.manage_cond_expr(local_expr);
250            }
251            ExprKind::Path(_, Path { segments, .. }) if let [path_segment] = &segments[..] => {
252                let path_ident = path_segment.ident;
253                self.manage_initial_capture(expr, path_ident);
254            }
255            ExprKind::Paren(local_expr) => {
256                self.manage_cond_expr(local_expr);
257            }
258            ExprKind::Range(prefix, suffix, _) => {
259                if let Some(elem) = prefix {
260                    self.manage_cond_expr(elem);
261                }
262                if let Some(elem) = suffix {
263                    self.manage_cond_expr(elem);
264                }
265            }
266            ExprKind::Repeat(local_expr, elem) => {
267                self.manage_cond_expr(local_expr);
268                self.manage_cond_expr(&mut elem.value);
269            }
270            ExprKind::Struct(elem) => {
271                for field in &mut elem.fields {
272                    self.manage_cond_expr(&mut field.expr);
273                }
274                if let StructRest::Base(local_expr) = &mut elem.rest {
275                    self.manage_cond_expr(local_expr);
276                }
277            }
278            ExprKind::Tup(local_exprs) => {
279                for local_expr in local_exprs {
280                    self.manage_cond_expr(local_expr);
281                }
282            }
283            ExprKind::Unary(un_op, local_expr) => {
284                self.with_is_consumed_management(#[allow(non_exhaustive_omitted_patterns)] match un_op {
    UnOp::Neg | UnOp::Not => true,
    _ => false,
}matches!(un_op, UnOp::Neg | UnOp::Not), |this| {
285                    this.manage_cond_expr(local_expr)
286                });
287            }
288            // Expressions that are not worth or can not be captured.
289            //
290            // Full list instead of `_` to catch possible future inclusions and to
291            // sync with the `rfc-2011-nicer-assert-messages/all-expr-kinds.rs` test.
292            ExprKind::Assign(_, _, _)
293            | ExprKind::AssignOp(_, _, _)
294            | ExprKind::Gen(_, _, _, _)
295            | ExprKind::Await(_, _)
296            | ExprKind::Use(_, _)
297            | ExprKind::Block(_, _)
298            | ExprKind::Break(_, _)
299            | ExprKind::Closure(_)
300            | ExprKind::ConstBlock(_)
301            | ExprKind::Continue(_)
302            | ExprKind::Dummy
303            | ExprKind::Err(_)
304            | ExprKind::Field(_, _)
305            | ExprKind::ForLoop { .. }
306            | ExprKind::FormatArgs(_)
307            | ExprKind::IncludedBytes(..)
308            | ExprKind::InlineAsm(_)
309            | ExprKind::Lit(_)
310            | ExprKind::Loop(_, _, _)
311            | ExprKind::MacCall(_)
312            | ExprKind::OffsetOf(_, _)
313            | ExprKind::Path(_, _)
314            | ExprKind::Ret(_)
315            | ExprKind::Try(_)
316            | ExprKind::TryBlock(_, _)
317            | ExprKind::Type(_, _)
318            | ExprKind::Underscore
319            | ExprKind::While(_, _, _)
320            | ExprKind::Yeet(_)
321            | ExprKind::Become(_)
322            | ExprKind::Yield(_)
323            | ExprKind::GcaMacro(_)
324            | ExprKind::UnsafeBinderCast(..) => {}
325        }
326    }
327
328    /// Pushes the top-level declarations and modifies `expr` to try capturing variables.
329    ///
330    /// `fmt_str`, the formatting string used for debugging, is constructed to show possible
331    /// captured variables.
332    fn manage_initial_capture(&mut self, expr: &mut Box<Expr>, path_ident: Ident) {
333        if self.paths.contains(&path_ident) {
334            return;
335        } else {
336            self.fmt_string.push_str("  ");
337            self.fmt_string.push_str(path_ident.as_str());
338            self.fmt_string.push_str(" = {:?}\n");
339            let _ = self.paths.insert(path_ident);
340        }
341        let curr_capture_idx = self.capture_decls.len();
342        let capture_string = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__capture{0}", curr_capture_idx))
    })format!("__capture{curr_capture_idx}");
343        let ident = Ident::new(Symbol::intern(&capture_string), self.span);
344        let init_std_path = self.cx.std_path(self.span, &[sym::asserting, sym::Capture, sym::new]);
345        let init = self.cx.expr_call(self.span, self.cx.expr_path(init_std_path), ThinVec::new());
346        let capture = Capture { decl: self.cx.stmt_let(self.span, true, ident.name, init), ident };
347        self.capture_decls.push(capture);
348        self.manage_try_capture(ident, curr_capture_idx, expr);
349    }
350
351    /// Tries to copy `__local_bindN` into `__captureN`.
352    ///
353    /// *{
354    ///    (&Wrapper(__local_bindN)).try_capture(&mut __captureN);
355    ///    __local_bindN
356    /// }
357    fn manage_try_capture(
358        &mut self,
359        capture: Ident,
360        curr_capture_idx: usize,
361        expr: &mut Box<Expr>,
362    ) {
363        let local_bind_string = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("__local_bind{0}",
                curr_capture_idx))
    })format!("__local_bind{curr_capture_idx}");
364        let local_bind = Symbol::intern(&local_bind_string);
365        self.local_bind_decls.push(self.cx.stmt_let(
366            self.span,
367            false,
368            local_bind,
369            self.cx.expr_addr_of(self.span, expr.clone()),
370        ));
371        let wrapper = self.cx.expr_call(
372            self.span,
373            self.cx.expr_path(self.cx.std_path(self.span, &[sym::asserting, sym::Wrapper])),
374            {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(self.cx.expr_path(self.cx.path_name(self.span, local_bind)));
    vec
}thin_vec![self.cx.expr_path(self.cx.path_name(self.span, local_bind))],
375        );
376        let try_capture_call = self
377            .cx
378            .stmt_expr(self.cx.expr_method_call(
379                self.span,
380                self.cx.expr_paren(self.span, self.cx.expr_addr_of(self.span, wrapper)),
381                Ident::new(sym::try_capture, self.span),
382                {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(expr_addr_of_mut(self.cx, self.span,
            self.cx.expr_path(Path::from_ident(capture))));
    vec
}thin_vec![expr_addr_of_mut(
383                    self.cx,
384                    self.span,
385                    self.cx.expr_path(Path::from_ident(capture)),
386                )],
387            ))
388            .add_trailing_semicolon();
389        let local_bind_path = self.cx.expr_path(self.cx.path_name(self.span, local_bind));
390        let rslt = if self.is_consumed {
391            let ret = self.cx.stmt_expr(local_bind_path);
392            self.cx.expr_block(self.cx.block(self.span, {
    let len = [(), ()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(try_capture_call);
    vec.push(ret);
    vec
}thin_vec![try_capture_call, ret]))
393        } else {
394            self.best_case_captures.push(try_capture_call);
395            local_bind_path
396        };
397        *expr = self.cx.expr_deref(self.span, rslt);
398    }
399
400    // Calls `f` with the internal `is_consumed` set to `curr_is_consumed` and then
401    // sets the internal `is_consumed` back to its original value.
402    fn with_is_consumed_management(&mut self, curr_is_consumed: bool, f: impl FnOnce(&mut Self)) {
403        let prev_is_consumed = self.is_consumed;
404        self.is_consumed = curr_is_consumed;
405        f(self);
406        self.is_consumed = prev_is_consumed;
407    }
408}
409
410/// Information about a captured element.
411#[derive(#[automatically_derived]impl ::core::fmt::Debug for Capture {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "Capture decl ident", &self.decl, &&self.ident)
    }
}Debug)]
412struct Capture {
413    // Generated indexed `Capture` statement.
414    //
415    // `let __capture{} = Capture::new();`
416    decl: Stmt,
417    // The name of the generated indexed `Capture` variable.
418    //
419    // `__capture{}`
420    ident: Ident,
421}
422
423/// Escapes to use as a formatting string.
424fn escape_to_fmt(s: &str) -> String {
425    let mut rslt = String::with_capacity(s.len());
426    for c in s.chars() {
427        rslt.extend(c.escape_debug());
428        match c {
429            '{' | '}' => rslt.push(c),
430            _ => {}
431        }
432    }
433    rslt
434}
435
436fn expr_addr_of_mut(cx: &ExtCtxt<'_>, sp: Span, e: Box<Expr>) -> Box<Expr> {
437    cx.expr(sp, ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, e))
438}