]> git.lizzy.rs Git - rust.git/blob - src/librustc_builtin_macros/assert.rs
Auto merge of #67768 - wesleywiser:dnm_test_perf_65244, r=Mark-Simulacrum
[rust.git] / src / librustc_builtin_macros / assert.rs
1 use errors::{Applicability, DiagnosticBuilder};
2
3 use rustc_expand::base::*;
4 use rustc_parse::parser::Parser;
5 use rustc_span::{Span, DUMMY_SP};
6 use syntax::ast::{self, *};
7 use syntax::print::pprust;
8 use syntax::ptr::P;
9 use syntax::symbol::{sym, Symbol};
10 use syntax::token::{self, TokenKind};
11 use syntax::tokenstream::{DelimSpan, TokenStream, TokenTree};
12
13 pub fn expand_assert<'cx>(
14     cx: &'cx mut ExtCtxt<'_>,
15     sp: Span,
16     tts: TokenStream,
17 ) -> Box<dyn MacResult + 'cx> {
18     let Assert { cond_expr, custom_message } = match parse_assert(cx, sp, tts) {
19         Ok(assert) => assert,
20         Err(mut err) => {
21             err.emit();
22             return DummyResult::any(sp);
23         }
24     };
25
26     // `core::panic` and `std::panic` are different macros, so we use call-site
27     // context to pick up whichever is currently in scope.
28     let sp = cx.with_call_site_ctxt(sp);
29     let tokens = custom_message.unwrap_or_else(|| {
30         TokenStream::from(TokenTree::token(
31             TokenKind::lit(
32                 token::Str,
33                 Symbol::intern(&format!(
34                     "assertion failed: {}",
35                     pprust::expr_to_string(&cond_expr).escape_debug()
36                 )),
37                 None,
38             ),
39             DUMMY_SP,
40         ))
41     });
42     let args = P(MacArgs::Delimited(DelimSpan::from_single(sp), MacDelimiter::Parenthesis, tokens));
43     let panic_call = Mac {
44         path: Path::from_ident(Ident::new(sym::panic, sp)),
45         args,
46         prior_type_ascription: None,
47     };
48     let if_expr = cx.expr_if(
49         sp,
50         cx.expr(sp, ExprKind::Unary(UnOp::Not, cond_expr)),
51         cx.expr(sp, ExprKind::Mac(panic_call)),
52         None,
53     );
54     MacEager::expr(if_expr)
55 }
56
57 struct Assert {
58     cond_expr: P<ast::Expr>,
59     custom_message: Option<TokenStream>,
60 }
61
62 fn parse_assert<'a>(
63     cx: &mut ExtCtxt<'a>,
64     sp: Span,
65     stream: TokenStream,
66 ) -> Result<Assert, DiagnosticBuilder<'a>> {
67     let mut parser = cx.new_parser_from_tts(stream);
68
69     if parser.token == token::Eof {
70         let mut err = cx.struct_span_err(sp, "macro requires a boolean expression as an argument");
71         err.span_label(sp, "boolean expression required");
72         return Err(err);
73     }
74
75     let cond_expr = parser.parse_expr()?;
76
77     // Some crates use the `assert!` macro in the following form (note extra semicolon):
78     //
79     // assert!(
80     //     my_function();
81     // );
82     //
83     // Warn about semicolon and suggest removing it. Eventually, this should be turned into an
84     // error.
85     if parser.token == token::Semi {
86         let mut err = cx.struct_span_warn(sp, "macro requires an expression as an argument");
87         err.span_suggestion(
88             parser.token.span,
89             "try removing semicolon",
90             String::new(),
91             Applicability::MaybeIncorrect,
92         );
93         err.note("this is going to be an error in the future");
94         err.emit();
95
96         parser.bump();
97     }
98
99     // Some crates use the `assert!` macro in the following form (note missing comma before
100     // message):
101     //
102     // assert!(true "error message");
103     //
104     // Parse this as an actual message, and suggest inserting a comma. Eventually, this should be
105     // turned into an error.
106     let custom_message =
107         if let token::Literal(token::Lit { kind: token::Str, .. }) = parser.token.kind {
108             let mut err = cx.struct_span_warn(parser.token.span, "unexpected string literal");
109             let comma_span = cx.source_map().next_point(parser.prev_span);
110             err.span_suggestion_short(
111                 comma_span,
112                 "try adding a comma",
113                 ", ".to_string(),
114                 Applicability::MaybeIncorrect,
115             );
116             err.note("this is going to be an error in the future");
117             err.emit();
118
119             parse_custom_message(&mut parser)
120         } else if parser.eat(&token::Comma) {
121             parse_custom_message(&mut parser)
122         } else {
123             None
124         };
125
126     if parser.token != token::Eof {
127         parser.expect_one_of(&[], &[])?;
128         unreachable!();
129     }
130
131     Ok(Assert { cond_expr, custom_message })
132 }
133
134 fn parse_custom_message(parser: &mut Parser<'_>) -> Option<TokenStream> {
135     let ts = parser.parse_tokens();
136     if !ts.is_empty() { Some(ts) } else { None }
137 }