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