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