]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/non_fmt_panic.rs
b86097a4bfc4a9c6a7368c7d3a70c120d3f10796
[rust.git] / compiler / rustc_lint / src / non_fmt_panic.rs
1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
3 use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused};
4 use crate::{LateContext, LateLintPass, LintContext};
5 use rustc_ast as ast;
6 use rustc_errors::{fluent, Applicability};
7 use rustc_hir as hir;
8 use rustc_infer::infer::TyCtxtInferExt;
9 use rustc_middle::lint::in_external_macro;
10 use rustc_middle::ty;
11 use rustc_parse_format::{ParseMode, Parser, Piece};
12 use rustc_session::lint::FutureIncompatibilityReason;
13 use rustc_span::edition::Edition;
14 use rustc_span::{hygiene, sym, symbol::kw, InnerSpan, Span, Symbol};
15 use rustc_trait_selection::infer::InferCtxtExt;
16
17 declare_lint! {
18     /// The `non_fmt_panics` lint detects `panic!(..)` invocations where the first
19     /// argument is not a formatting string.
20     ///
21     /// ### Example
22     ///
23     /// ```rust,no_run,edition2018
24     /// panic!("{}");
25     /// panic!(123);
26     /// ```
27     ///
28     /// {{produces}}
29     ///
30     /// ### Explanation
31     ///
32     /// In Rust 2018 and earlier, `panic!(x)` directly uses `x` as the message.
33     /// That means that `panic!("{}")` panics with the message `"{}"` instead
34     /// of using it as a formatting string, and `panic!(123)` will panic with
35     /// an `i32` as message.
36     ///
37     /// Rust 2021 always interprets the first argument as format string.
38     NON_FMT_PANICS,
39     Warn,
40     "detect single-argument panic!() invocations in which the argument is not a format string",
41     @future_incompatible = FutureIncompatibleInfo {
42         reason: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2021),
43         explain_reason: false,
44     };
45     report_in_external_macro
46 }
47
48 declare_lint_pass!(NonPanicFmt => [NON_FMT_PANICS]);
49
50 impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
51     fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
52         if let hir::ExprKind::Call(f, [arg]) = &expr.kind {
53             if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
54                 let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id);
55
56                 if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
57                     || Some(def_id) == cx.tcx.lang_items().panic_fn()
58                     || f_diagnostic_name == Some(sym::panic_str)
59                 {
60                     if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
61                         if matches!(
62                             cx.tcx.get_diagnostic_name(id),
63                             Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro)
64                         ) {
65                             check_panic(cx, f, arg);
66                         }
67                     }
68                 } else if f_diagnostic_name == Some(sym::unreachable_display) {
69                     if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
70                         if cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id) {
71                             check_panic(
72                                 cx,
73                                 f,
74                                 // This is safe because we checked above that the callee is indeed
75                                 // unreachable_display
76                                 match &arg.kind {
77                                     // Get the borrowed arg not the borrow
78                                     hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg,
79                                     _ => bug!("call to unreachable_display without borrow"),
80                                 },
81                             );
82                         }
83                     }
84                 }
85             }
86         }
87     }
88 }
89
90 fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
91     if let hir::ExprKind::Lit(lit) = &arg.kind {
92         if let ast::LitKind::Str(sym, _) = lit.node {
93             // The argument is a string literal.
94             check_panic_str(cx, f, arg, sym.as_str());
95             return;
96         }
97     }
98
99     // The argument is *not* a string literal.
100
101     let (span, panic, symbol) = panic_call(cx, f);
102
103     if in_external_macro(cx.sess(), span) {
104         // Nothing that can be done about it in the current crate.
105         return;
106     }
107
108     // Find the span of the argument to `panic!()` or `unreachable!`, before expansion in the
109     // case of `panic!(some_macro!())` or `unreachable!(some_macro!())`.
110     // We don't use source_callsite(), because this `panic!(..)` might itself
111     // be expanded from another macro, in which case we want to stop at that
112     // expansion.
113     let mut arg_span = arg.span;
114     let mut arg_macro = None;
115     while !span.contains(arg_span) {
116         let expn = arg_span.ctxt().outer_expn_data();
117         if expn.is_root() {
118             break;
119         }
120         arg_macro = expn.macro_def_id;
121         arg_span = expn.call_site;
122     }
123
124     #[allow(rustc::diagnostic_outside_of_impl)]
125     cx.struct_span_lint(NON_FMT_PANICS, arg_span, fluent::lint_non_fmt_panic, |lint| {
126         lint.set_arg("name", symbol);
127         lint.note(fluent::note);
128         lint.note(fluent::more_info_note);
129         if !is_arg_inside_call(arg_span, span) {
130             // No clue where this argument is coming from.
131             return lint;
132         }
133         if arg_macro.map_or(false, |id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
134             // A case of `panic!(format!(..))`.
135             lint.note(fluent::supports_fmt_note);
136             if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
137                 lint.multipart_suggestion(
138                     fluent::supports_fmt_suggestion,
139                     vec![
140                         (arg_span.until(open.shrink_to_hi()), "".into()),
141                         (close.until(arg_span.shrink_to_hi()), "".into()),
142                     ],
143                     Applicability::MachineApplicable,
144                 );
145             }
146         } else {
147             let ty = cx.typeck_results().expr_ty(arg);
148             // If this is a &str or String, we can confidently give the `"{}", ` suggestion.
149             let is_str = matches!(
150                 ty.kind(),
151                 ty::Ref(_, r, _) if *r.kind() == ty::Str,
152             ) || matches!(
153                 ty.ty_adt_def(),
154                 Some(ty_def) if Some(ty_def.did()) == cx.tcx.lang_items().string(),
155             );
156
157             let infcx = cx.tcx.infer_ctxt().build();
158             let suggest_display = is_str
159                 || cx
160                     .tcx
161                     .get_diagnostic_item(sym::Display)
162                     .map(|t| infcx.type_implements_trait(t, [ty], cx.param_env).may_apply())
163                     == Some(true);
164             let suggest_debug = !suggest_display
165                 && cx
166                     .tcx
167                     .get_diagnostic_item(sym::Debug)
168                     .map(|t| infcx.type_implements_trait(t, [ty], cx.param_env).may_apply())
169                     == Some(true);
170
171             let suggest_panic_any = !is_str && panic == sym::std_panic_macro;
172
173             let fmt_applicability = if suggest_panic_any {
174                 // If we can use panic_any, use that as the MachineApplicable suggestion.
175                 Applicability::MaybeIncorrect
176             } else {
177                 // If we don't suggest panic_any, using a format string is our best bet.
178                 Applicability::MachineApplicable
179             };
180
181             if suggest_display {
182                 lint.span_suggestion_verbose(
183                     arg_span.shrink_to_lo(),
184                     fluent::display_suggestion,
185                     "\"{}\", ",
186                     fmt_applicability,
187                 );
188             } else if suggest_debug {
189                 lint.set_arg("ty", ty);
190                 lint.span_suggestion_verbose(
191                     arg_span.shrink_to_lo(),
192                     fluent::debug_suggestion,
193                     "\"{:?}\", ",
194                     fmt_applicability,
195                 );
196             }
197
198             if suggest_panic_any {
199                 if let Some((open, close, del)) = find_delimiters(cx, span) {
200                     lint.set_arg("already_suggested", suggest_display || suggest_debug);
201                     lint.multipart_suggestion(
202                         fluent::panic_suggestion,
203                         if del == '(' {
204                             vec![(span.until(open), "std::panic::panic_any".into())]
205                         } else {
206                             vec![
207                                 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
208                                 (close, ")".into()),
209                             ]
210                         },
211                         Applicability::MachineApplicable,
212                     );
213                 }
214             }
215         }
216         lint
217     });
218 }
219
220 fn check_panic_str<'tcx>(
221     cx: &LateContext<'tcx>,
222     f: &'tcx hir::Expr<'tcx>,
223     arg: &'tcx hir::Expr<'tcx>,
224     fmt: &str,
225 ) {
226     if !fmt.contains(&['{', '}']) {
227         // No brace, no problem.
228         return;
229     }
230
231     let (span, _, _) = panic_call(cx, f);
232
233     if in_external_macro(cx.sess(), span) && in_external_macro(cx.sess(), arg.span) {
234         // Nothing that can be done about it in the current crate.
235         return;
236     }
237
238     let fmt_span = arg.span.source_callsite();
239
240     let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
241         Ok(snippet) => {
242             // Count the number of `#`s between the `r` and `"`.
243             let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
244             (Some(snippet), style)
245         }
246         Err(_) => (None, None),
247     };
248
249     let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
250     let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
251
252     if n_arguments > 0 && fmt_parser.errors.is_empty() {
253         let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
254             [] => vec![fmt_span],
255             v => v
256                 .iter()
257                 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
258                 .collect(),
259         };
260         cx.emit_spanned_lint(
261             NON_FMT_PANICS,
262             arg_spans,
263             NonFmtPanicUnused {
264                 count: n_arguments,
265                 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span),
266             },
267         );
268     } else {
269         let brace_spans: Option<Vec<_>> =
270             snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
271                 s.char_indices()
272                     .filter(|&(_, c)| c == '{' || c == '}')
273                     .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
274                     .collect()
275             });
276         let count = brace_spans.as_ref().map(|v| v.len()).unwrap_or(/* any number >1 */ 2);
277         cx.emit_spanned_lint(
278             NON_FMT_PANICS,
279             brace_spans.unwrap_or_else(|| vec![span]),
280             NonFmtPanicBraces {
281                 count,
282                 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span.shrink_to_lo()),
283             },
284         );
285     }
286 }
287
288 /// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
289 /// and the type of (opening) delimiter used.
290 fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> {
291     let snippet = cx.sess().parse_sess.source_map().span_to_snippet(span).ok()?;
292     let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
293     let close = snippet.rfind(|c| ")]}".contains(c))?;
294     Some((
295         span.from_inner(InnerSpan { start: open, end: open + 1 }),
296         span.from_inner(InnerSpan { start: close, end: close + 1 }),
297         open_ch,
298     ))
299 }
300
301 fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, Symbol) {
302     let mut expn = f.span.ctxt().outer_expn_data();
303
304     let mut panic_macro = kw::Empty;
305
306     // Unwrap more levels of macro expansion, as panic_2015!()
307     // was likely expanded from panic!() and possibly from
308     // [debug_]assert!().
309     loop {
310         let parent = expn.call_site.ctxt().outer_expn_data();
311         let Some(id) = parent.macro_def_id else { break };
312         let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
313         if !matches!(
314             name,
315             sym::core_panic_macro
316                 | sym::std_panic_macro
317                 | sym::assert_macro
318                 | sym::debug_assert_macro
319                 | sym::unreachable_macro
320         ) {
321             break;
322         }
323         expn = parent;
324         panic_macro = name;
325     }
326
327     let macro_symbol =
328         if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
329     (expn.call_site, panic_macro, macro_symbol)
330 }
331
332 fn is_arg_inside_call(arg: Span, call: Span) -> bool {
333     // We only add suggestions if the argument we're looking at appears inside the
334     // panic call in the source file, to avoid invalid suggestions when macros are involved.
335     // We specifically check for the spans to not be identical, as that happens sometimes when
336     // proc_macros lie about spans and apply the same span to all the tokens they produce.
337     call.contains(arg) && !call.source_equal(arg)
338 }