]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/non_fmt_panic.rs
Merge commit 'b40ea209e7f14c8193ddfc98143967b6a2f4f5c9' into clippyup
[rust.git] / compiler / rustc_lint / src / non_fmt_panic.rs
1 use crate::{LateContext, LateLintPass, LintContext};
2 use rustc_ast as ast;
3 use rustc_errors::{pluralize, Applicability};
4 use rustc_hir as hir;
5 use rustc_middle::ty;
6 use rustc_parse_format::{ParseMode, Parser, Piece};
7 use rustc_span::{sym, symbol::kw, InnerSpan, Span, Symbol};
8
9 declare_lint! {
10     /// The `non_fmt_panic` lint detects `panic!(..)` invocations where the first
11     /// argument is not a formatting string.
12     ///
13     /// ### Example
14     ///
15     /// ```rust,no_run
16     /// panic!("{}");
17     /// panic!(123);
18     /// ```
19     ///
20     /// {{produces}}
21     ///
22     /// ### Explanation
23     ///
24     /// In Rust 2018 and earlier, `panic!(x)` directly uses `x` as the message.
25     /// That means that `panic!("{}")` panics with the message `"{}"` instead
26     /// of using it as a formatting string, and `panic!(123)` will panic with
27     /// an `i32` as message.
28     ///
29     /// Rust 2021 always interprets the first argument as format string.
30     NON_FMT_PANIC,
31     Warn,
32     "detect single-argument panic!() invocations in which the argument is not a format string",
33     report_in_external_macro
34 }
35
36 declare_lint_pass!(NonPanicFmt => [NON_FMT_PANIC]);
37
38 impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
39     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
40         if let hir::ExprKind::Call(f, [arg]) = &expr.kind {
41             if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
42                 if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
43                     || Some(def_id) == cx.tcx.lang_items().panic_fn()
44                     || Some(def_id) == cx.tcx.lang_items().panic_str()
45                 {
46                     if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
47                         if cx.tcx.is_diagnostic_item(sym::std_panic_2015_macro, id)
48                             || cx.tcx.is_diagnostic_item(sym::core_panic_2015_macro, id)
49                         {
50                             check_panic(cx, f, arg);
51                         }
52                     }
53                 }
54             }
55         }
56     }
57 }
58
59 fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
60     if let hir::ExprKind::Lit(lit) = &arg.kind {
61         if let ast::LitKind::Str(sym, _) = lit.node {
62             // The argument is a string literal.
63             check_panic_str(cx, f, arg, &sym.as_str());
64             return;
65         }
66     }
67
68     // The argument is *not* a string literal.
69
70     let (span, panic) = panic_call(cx, f);
71
72     // Find the span of the argument to `panic!()`, before expansion in the
73     // case of `panic!(some_macro!())`.
74     // We don't use source_callsite(), because this `panic!(..)` might itself
75     // be expanded from another macro, in which case we want to stop at that
76     // expansion.
77     let mut arg_span = arg.span;
78     let mut arg_macro = None;
79     while !span.contains(arg_span) {
80         let expn = arg_span.ctxt().outer_expn_data();
81         if expn.is_root() {
82             break;
83         }
84         arg_macro = expn.macro_def_id;
85         arg_span = expn.call_site;
86     }
87
88     cx.struct_span_lint(NON_FMT_PANIC, arg_span, |lint| {
89         let mut l = lint.build("panic message is not a string literal");
90         l.note("this is no longer accepted in Rust 2021");
91         if !span.contains(arg_span) {
92             // No clue where this argument is coming from.
93             l.emit();
94             return;
95         }
96         if arg_macro.map_or(false, |id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
97             // A case of `panic!(format!(..))`.
98             l.note("the panic!() macro supports formatting, so there's no need for the format!() macro here");
99             if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
100                 l.multipart_suggestion(
101                     "remove the `format!(..)` macro call",
102                     vec![
103                         (arg_span.until(open.shrink_to_hi()), "".into()),
104                         (close.until(arg_span.shrink_to_hi()), "".into()),
105                     ],
106                     Applicability::MachineApplicable,
107                 );
108             }
109         } else {
110             l.span_suggestion_verbose(
111                 arg_span.shrink_to_lo(),
112                 "add a \"{}\" format string to Display the message",
113                 "\"{}\", ".into(),
114                 Applicability::MaybeIncorrect,
115             );
116             if panic == sym::std_panic_macro {
117                 if let Some((open, close, del)) = find_delimiters(cx, span) {
118                     l.multipart_suggestion(
119                         "or use std::panic::panic_any instead",
120                         if del == '(' {
121                             vec![(span.until(open), "std::panic::panic_any".into())]
122                         } else {
123                             vec![
124                                 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
125                                 (close, ")".into()),
126                             ]
127                         },
128                         Applicability::MachineApplicable,
129                     );
130                 }
131             }
132         }
133         l.emit();
134     });
135 }
136
137 fn check_panic_str<'tcx>(
138     cx: &LateContext<'tcx>,
139     f: &'tcx hir::Expr<'tcx>,
140     arg: &'tcx hir::Expr<'tcx>,
141     fmt: &str,
142 ) {
143     if !fmt.contains(&['{', '}'][..]) {
144         // No brace, no problem.
145         return;
146     }
147
148     let fmt_span = arg.span.source_callsite();
149
150     let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
151         Ok(snippet) => {
152             // Count the number of `#`s between the `r` and `"`.
153             let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
154             (Some(snippet), style)
155         }
156         Err(_) => (None, None),
157     };
158
159     let mut fmt_parser =
160         Parser::new(fmt.as_ref(), style, snippet.clone(), false, ParseMode::Format);
161     let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
162
163     let (span, _) = panic_call(cx, f);
164
165     if n_arguments > 0 && fmt_parser.errors.is_empty() {
166         let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
167             [] => vec![fmt_span],
168             v => v.iter().map(|span| fmt_span.from_inner(*span)).collect(),
169         };
170         cx.struct_span_lint(NON_FMT_PANIC, arg_spans, |lint| {
171             let mut l = lint.build(match n_arguments {
172                 1 => "panic message contains an unused formatting placeholder",
173                 _ => "panic message contains unused formatting placeholders",
174             });
175             l.note("this message is not used as a format string when given without arguments, but will be in Rust 2021");
176             if span.contains(arg.span) {
177                 l.span_suggestion(
178                     arg.span.shrink_to_hi(),
179                     &format!("add the missing argument{}", pluralize!(n_arguments)),
180                     ", ...".into(),
181                     Applicability::HasPlaceholders,
182                 );
183                 l.span_suggestion(
184                     arg.span.shrink_to_lo(),
185                     "or add a \"{}\" format string to use the message literally",
186                     "\"{}\", ".into(),
187                     Applicability::MachineApplicable,
188                 );
189             }
190             l.emit();
191         });
192     } else {
193         let brace_spans: Option<Vec<_>> =
194             snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
195                 s.char_indices()
196                     .filter(|&(_, c)| c == '{' || c == '}')
197                     .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
198                     .collect()
199             });
200         let msg = match &brace_spans {
201             Some(v) if v.len() == 1 => "panic message contains a brace",
202             _ => "panic message contains braces",
203         };
204         cx.struct_span_lint(NON_FMT_PANIC, brace_spans.unwrap_or_else(|| vec![span]), |lint| {
205             let mut l = lint.build(msg);
206             l.note("this message is not used as a format string, but will be in Rust 2021");
207             if span.contains(arg.span) {
208                 l.span_suggestion(
209                     arg.span.shrink_to_lo(),
210                     "add a \"{}\" format string to use the message literally",
211                     "\"{}\", ".into(),
212                     Applicability::MachineApplicable,
213                 );
214             }
215             l.emit();
216         });
217     }
218 }
219
220 /// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
221 /// and the type of (opening) delimiter used.
222 fn find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Span, char)> {
223     let snippet = cx.sess().parse_sess.source_map().span_to_snippet(span).ok()?;
224     let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
225     let close = snippet.rfind(|c| ")]}".contains(c))?;
226     Some((
227         span.from_inner(InnerSpan { start: open, end: open + 1 }),
228         span.from_inner(InnerSpan { start: close, end: close + 1 }),
229         open_ch,
230     ))
231 }
232
233 fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol) {
234     let mut expn = f.span.ctxt().outer_expn_data();
235
236     let mut panic_macro = kw::Empty;
237
238     // Unwrap more levels of macro expansion, as panic_2015!()
239     // was likely expanded from panic!() and possibly from
240     // [debug_]assert!().
241     for &i in
242         &[sym::std_panic_macro, sym::core_panic_macro, sym::assert_macro, sym::debug_assert_macro]
243     {
244         let parent = expn.call_site.ctxt().outer_expn_data();
245         if parent.macro_def_id.map_or(false, |id| cx.tcx.is_diagnostic_item(i, id)) {
246             expn = parent;
247             panic_macro = i;
248         }
249     }
250
251     (expn.call_site, panic_macro)
252 }