rust/compiler/rustc_builtin_macros/src/assert.rs

164 lines
5.4 KiB
Rust
Raw Normal View History

2022-06-02 12:00:04 +00:00
mod context;
use crate::edition_panic::use_panic_2021;
use crate::errors;
use rustc_ast::ptr::P;
use rustc_ast::token;
use rustc_ast::token::Delimiter;
use rustc_ast::tokenstream::{DelimSpan, TokenStream};
use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp};
use rustc_ast_pretty::pprust;
use rustc_errors::PResult;
use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult};
use rustc_parse::parser::Parser;
2020-04-19 11:00:18 +00:00
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::{Span, DUMMY_SP};
use thin_vec::thin_vec;
pub fn expand_assert<'cx>(
2019-02-04 12:49:54 +00:00
cx: &'cx mut ExtCtxt<'_>,
span: Span,
tts: TokenStream,
) -> MacroExpanderResult<'cx> {
let Assert { cond_expr, custom_message } = match parse_assert(cx, span, tts) {
Ok(assert) => assert,
Make `DiagnosticBuilder::emit` consuming. This works for most of its call sites. This is nice, because `emit` very much makes sense as a consuming operation -- indeed, `DiagnosticBuilderState` exists to ensure no diagnostic is emitted twice, but it uses runtime checks. For the small number of call sites where a consuming emit doesn't work, the commit adds `DiagnosticBuilder::emit_without_consuming`. (This will be removed in subsequent commits.) Likewise, `emit_unless` becomes consuming. And `delay_as_bug` becomes consuming, while `delay_as_bug_without_consuming` is added (which will also be removed in subsequent commits.) All this requires significant changes to `DiagnosticBuilder`'s chaining methods. Currently `DiagnosticBuilder` method chaining uses a non-consuming `&mut self -> &mut Self` style, which allows chaining to be used when the chain ends in `emit()`, like so: ``` struct_err(msg).span(span).emit(); ``` But it doesn't work when producing a `DiagnosticBuilder` value, requiring this: ``` let mut err = self.struct_err(msg); err.span(span); err ``` This style of chaining won't work with consuming `emit` though. For that, we need to use to a `self -> Self` style. That also would allow `DiagnosticBuilder` production to be chained, e.g.: ``` self.struct_err(msg).span(span) ``` However, removing the `&mut self -> &mut Self` style would require that individual modifications of a `DiagnosticBuilder` go from this: ``` err.span(span); ``` to this: ``` err = err.span(span); ``` There are *many* such places. I have a high tolerance for tedious refactorings, but even I gave up after a long time trying to convert them all. Instead, this commit has it both ways: the existing `&mut self -> Self` chaining methods are kept, and new `self -> Self` chaining methods are added, all of which have a `_mv` suffix (short for "move"). Changes to the existing `forward!` macro lets this happen with very little additional boilerplate code. I chose to add the suffix to the new chaining methods rather than the existing ones, because the number of changes required is much smaller that way. This doubled chainging is a bit clumsy, but I think it is worthwhile because it allows a *lot* of good things to subsequently happen. In this commit, there are many `mut` qualifiers removed in places where diagnostics are emitted without being modified. In subsequent commits: - chaining can be used more, making the code more concise; - more use of chaining also permits the removal of redundant diagnostic APIs like `struct_err_with_code`, which can be replaced easily with `struct_err` + `code_mv`; - `emit_without_diagnostic` can be removed, which simplifies a lot of machinery, removing the need for `DiagnosticBuilderState`.
2024-01-03 01:17:35 +00:00
Err(err) => {
let guar = err.emit();
return ExpandResult::Ready(DummyResult::any(span, guar));
}
};
2019-09-14 20:17:11 +00:00
// `core::panic` and `std::panic` are different macros, so we use call-site
// context to pick up whichever is currently in scope.
2022-06-02 12:00:04 +00:00
let call_site_span = cx.with_call_site_ctxt(span);
2022-06-02 12:00:04 +00:00
let panic_path = || {
if use_panic_2021(span) {
// On edition 2021, we always call `$crate::panic::panic_2021!()`.
Path {
2022-06-02 12:00:04 +00:00
span: call_site_span,
segments: cx
.std_path(&[sym::panic, sym::panic_2021])
.into_iter()
.map(|ident| PathSegment::from_ident(ident))
.collect(),
tokens: None,
}
} else {
// Before edition 2021, we call `panic!()` unqualified,
// such that it calls either `std::panic!()` or `core::panic!()`.
2022-06-02 12:00:04 +00:00
Path::from_ident(Ident::new(sym::panic, call_site_span))
}
};
// Simply uses the user provided message instead of generating custom outputs
let expr = if let Some(tokens) = custom_message {
let then = cx.expr(
call_site_span,
2022-08-12 02:20:10 +00:00
ExprKind::MacCall(P(MacCall {
2022-06-02 12:00:04 +00:00
path: panic_path(),
args: P(DelimArgs {
dspan: DelimSpan::from_single(call_site_span),
delim: Delimiter::Parenthesis,
tokens,
}),
2022-08-12 02:20:10 +00:00
})),
2022-06-02 12:00:04 +00:00
);
expr_if_not(cx, call_site_span, cond_expr, then, None)
}
// If `generic_assert` is enabled, generates rich captured outputs
//
// FIXME(c410-f3r) See https://github.com/rust-lang/rust/issues/96949
else if cx.ecfg.features.generic_assert {
2022-06-02 12:00:04 +00:00
context::Context::new(cx, call_site_span).build(cond_expr, panic_path())
}
// If `generic_assert` is not enabled, only outputs a literal "assertion failed: ..."
// string
else {
// Pass our own message directly to $crate::panicking::panic(),
// because it might contain `{` and `}` that should always be
// passed literally.
2022-06-02 12:00:04 +00:00
let then = cx.expr_call_global(
call_site_span,
cx.std_path(&[sym::panicking, sym::panic]),
thin_vec![cx.expr_str(
DUMMY_SP,
Symbol::intern(&format!(
"assertion failed: {}",
Don't `escape_debug` the condition of `assert!`. The assertion in `assert-long-condition.rs` used to be fail like this, all on one line: ``` thread 'main' panicked at 'assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18\n + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0', tests/ui/macros/assert-long-condition.rs:7:5 ``` The `\n` and subsequent indent is because the condition is pretty-printed, and the pretty-printer inserts a newline. Printing the newline in this way is arguably reasonable given that the message appears within single quotes, which is very similar to a string literal. However, after the assertion printing improvements that were released in 1.73, the assertion now fails like this: ``` thread 'main' panicked at tests/ui/macros/assert-long-condition.rs:7:5: assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18\n + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0 ``` Now that there are no single quotes around the pretty-printed condition, the `\n` is quite strange. This commit gets rid of the `\n`, by removing the `escape_debug` done on the pretty-printed message. This results in the following: ``` thread 'main' panicked at tests/ui/macros/assert-long-condition.rs:7:5: assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0 ``` The overly-large indent is still strange, but that's a separate pretty-printing issue. This change helps with #108341.
2023-10-09 02:32:17 +00:00
pprust::expr_to_string(&cond_expr)
)),
)],
2022-06-02 12:00:04 +00:00
);
expr_if_not(cx, call_site_span, cond_expr, then, None)
};
2022-06-02 12:00:04 +00:00
ExpandResult::Ready(MacEager::expr(expr))
}
struct Assert {
2022-06-02 12:00:04 +00:00
cond_expr: P<Expr>,
custom_message: Option<TokenStream>,
}
2022-06-02 12:00:04 +00:00
// if !{ ... } { ... } else { ... }
fn expr_if_not(
cx: &ExtCtxt<'_>,
span: Span,
cond: P<Expr>,
then: P<Expr>,
els: Option<P<Expr>>,
) -> P<Expr> {
cx.expr_if(span, cx.expr(span, ExprKind::Unary(UnOp::Not, cond)), then, els)
}
fn parse_assert<'a>(cx: &mut ExtCtxt<'a>, sp: Span, stream: TokenStream) -> PResult<'a, Assert> {
let mut parser = cx.new_parser_from_tts(stream);
if parser.token == token::Eof {
return Err(cx.dcx().create_err(errors::AssertRequiresBoolean { span: sp }));
}
2019-04-24 22:44:28 +00:00
let cond_expr = parser.parse_expr()?;
// Some crates use the `assert!` macro in the following form (note extra semicolon):
//
// assert!(
// my_function();
// );
//
// Emit an error about semicolon and suggest removing it.
2019-04-24 22:44:28 +00:00
if parser.token == token::Semi {
cx.dcx().emit_err(errors::AssertRequiresExpression { span: sp, token: parser.token.span });
2019-04-24 22:44:28 +00:00
parser.bump();
}
// Some crates use the `assert!` macro in the following form (note missing comma before
// message):
//
// assert!(true "error message");
//
// Emit an error and suggest inserting a comma.
2019-12-22 22:42:04 +00:00
let custom_message =
if let token::Literal(token::Lit { kind: token::Str, .. }) = parser.token.kind {
let comma = parser.prev_token.span.shrink_to_hi();
cx.dcx().emit_err(errors::AssertMissingComma { span: parser.token.span, comma });
2019-04-24 22:44:28 +00:00
2019-12-22 22:42:04 +00:00
parse_custom_message(&mut parser)
} else if parser.eat(&token::Comma) {
parse_custom_message(&mut parser)
} else {
None
};
if parser.token != token::Eof {
parser.unexpected()?;
}
2019-04-24 22:44:28 +00:00
Ok(Assert { cond_expr, custom_message })
}
2019-06-21 21:49:03 +00:00
fn parse_custom_message(parser: &mut Parser<'_>) -> Option<TokenStream> {
2019-04-24 22:44:28 +00:00
let ts = parser.parse_tokens();
2019-12-22 22:42:04 +00:00
if !ts.is_empty() { Some(ts) } else { None }
}