]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/assert.rs
e5e422c4d9c778fd8607da94d2956b97ce7eeed9
[rust.git] / src / libsyntax_ext / assert.rs
1 use errors::{Applicability, DiagnosticBuilder};
2
3 use syntax::ast::{self, *};
4 use syntax::source_map::Spanned;
5 use syntax::ext::base::*;
6 use syntax::ext::build::AstBuilder;
7 use syntax::parse::token::{self, TokenKind};
8 use syntax::parse::parser::Parser;
9 use syntax::print::pprust;
10 use syntax::ptr::P;
11 use syntax::symbol::{sym, Symbol};
12 use syntax::tokenstream::{TokenStream, TokenTree};
13 use syntax_pos::{Span, DUMMY_SP};
14
15 pub fn expand_assert<'cx>(
16     cx: &'cx mut ExtCtxt<'_>,
17     sp: Span,
18     tts: &[TokenTree],
19 ) -> Box<dyn MacResult + 'cx> {
20     let Assert { cond_expr, custom_message } = match parse_assert(cx, sp, tts) {
21         Ok(assert) => assert,
22         Err(mut err) => {
23             err.emit();
24             return DummyResult::expr(sp);
25         }
26     };
27
28     let sp = sp.apply_mark(cx.current_expansion.mark);
29     let panic_call = Mac_ {
30         path: Path::from_ident(Ident::new(sym::panic, sp)),
31         tts: custom_message.unwrap_or_else(|| {
32             TokenStream::from(TokenTree::token(
33                 DUMMY_SP,
34                 TokenKind::lit(token::Str, Symbol::intern(&format!(
35                     "assertion failed: {}",
36                     pprust::expr_to_string(&cond_expr).escape_debug()
37                 )), None),
38             ))
39         }).into(),
40         delim: MacDelimiter::Parenthesis,
41     };
42     let if_expr = cx.expr_if(
43         sp,
44         cx.expr(sp, ExprKind::Unary(UnOp::Not, cond_expr)),
45         cx.expr(
46             sp,
47             ExprKind::Mac(Spanned {
48                 span: sp,
49                 node: panic_call,
50             }),
51         ),
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     tts: &[TokenTree]
66 ) -> Result<Assert, DiagnosticBuilder<'a>> {
67     let mut parser = cx.new_parser_from_tts(tts);
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.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 = if let token::Literal(token::Lit { kind: token::Str, .. }) = parser.token.kind {
107         let mut err = cx.struct_span_warn(parser.span, "unexpected string literal");
108         let comma_span = cx.source_map().next_point(parser.prev_span);
109         err.span_suggestion_short(
110             comma_span,
111             "try adding a comma",
112             ", ".to_string(),
113             Applicability::MaybeIncorrect
114         );
115         err.note("this is going to be an error in the future");
116         err.emit();
117
118         parse_custom_message(&mut parser)
119     } else if parser.eat(&token::Comma) {
120         parse_custom_message(&mut parser)
121     } else {
122         None
123     };
124
125     if parser.token != token::Eof {
126         parser.expect_one_of(&[], &[])?;
127         unreachable!();
128     }
129
130     Ok(Assert { cond_expr, custom_message })
131 }
132
133 fn parse_custom_message<'a>(parser: &mut Parser<'a>) -> Option<TokenStream> {
134     let ts = parser.parse_tokens();
135     if !ts.is_empty() {
136         Some(ts)
137     } else {
138         None
139     }
140 }