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