]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_lint/src/non_fmt_panic.rs
Auto merge of #100966 - compiler-errors:revert-remove-deferred-sized-checks, r=pnkfelix
[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, |lint| {
123         let mut l = lint.build(fluent::lint::non_fmt_panic);
124         l.set_arg("name", symbol);
125         l.note(fluent::lint::note);
126         l.note(fluent::lint::more_info_note);
127         if !is_arg_inside_call(arg_span, span) {
128             // No clue where this argument is coming from.
129             l.emit();
130             return;
131         }
132         if arg_macro.map_or(false, |id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
133             // A case of `panic!(format!(..))`.
134             l.note(fluent::lint::supports_fmt_note);
135             if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
136                 l.multipart_suggestion(
137                     fluent::lint::supports_fmt_suggestion,
138                     vec![
139                         (arg_span.until(open.shrink_to_hi()), "".into()),
140                         (close.until(arg_span.shrink_to_hi()), "".into()),
141                     ],
142                     Applicability::MachineApplicable,
143                 );
144             }
145         } else {
146             let ty = cx.typeck_results().expr_ty(arg);
147             // If this is a &str or String, we can confidently give the `"{}", ` suggestion.
148             let is_str = matches!(
149                 ty.kind(),
150                 ty::Ref(_, r, _) if *r.kind() == ty::Str,
151             ) || matches!(
152                 ty.ty_adt_def(),
153                 Some(ty_def) if cx.tcx.is_diagnostic_item(sym::String, ty_def.did()),
154             );
155
156             let (suggest_display, suggest_debug) = cx.tcx.infer_ctxt().enter(|infcx| {
157                 let display = is_str
158                     || cx.tcx.get_diagnostic_item(sym::Display).map(|t| {
159                         infcx
160                             .type_implements_trait(t, ty, InternalSubsts::empty(), cx.param_env)
161                             .may_apply()
162                     }) == Some(true);
163                 let debug = !display
164                     && cx.tcx.get_diagnostic_item(sym::Debug).map(|t| {
165                         infcx
166                             .type_implements_trait(t, ty, InternalSubsts::empty(), cx.param_env)
167                             .may_apply()
168                     }) == Some(true);
169                 (display, debug)
170             });
171
172             let suggest_panic_any = !is_str && panic == sym::std_panic_macro;
173
174             let fmt_applicability = if suggest_panic_any {
175                 // If we can use panic_any, use that as the MachineApplicable suggestion.
176                 Applicability::MaybeIncorrect
177             } else {
178                 // If we don't suggest panic_any, using a format string is our best bet.
179                 Applicability::MachineApplicable
180             };
181
182             if suggest_display {
183                 l.span_suggestion_verbose(
184                     arg_span.shrink_to_lo(),
185                     fluent::lint::display_suggestion,
186                     "\"{}\", ",
187                     fmt_applicability,
188                 );
189             } else if suggest_debug {
190                 l.set_arg("ty", ty);
191                 l.span_suggestion_verbose(
192                     arg_span.shrink_to_lo(),
193                     fluent::lint::debug_suggestion,
194                     "\"{:?}\", ",
195                     fmt_applicability,
196                 );
197             }
198
199             if suggest_panic_any {
200                 if let Some((open, close, del)) = find_delimiters(cx, span) {
201                     l.set_arg("already_suggested", suggest_display || suggest_debug);
202                     l.multipart_suggestion(
203                         fluent::lint::panic_suggestion,
204                         if del == '(' {
205                             vec![(span.until(open), "std::panic::panic_any".into())]
206                         } else {
207                             vec![
208                                 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
209                                 (close, ")".into()),
210                             ]
211                         },
212                         Applicability::MachineApplicable,
213                     );
214                 }
215             }
216         }
217         l.emit();
218     });
219 }
220
221 fn check_panic_str<'tcx>(
222     cx: &LateContext<'tcx>,
223     f: &'tcx hir::Expr<'tcx>,
224     arg: &'tcx hir::Expr<'tcx>,
225     fmt: &str,
226 ) {
227     if !fmt.contains(&['{', '}']) {
228         // No brace, no problem.
229         return;
230     }
231
232     let (span, _, _) = panic_call(cx, f);
233
234     if in_external_macro(cx.sess(), span) && in_external_macro(cx.sess(), arg.span) {
235         // Nothing that can be done about it in the current crate.
236         return;
237     }
238
239     let fmt_span = arg.span.source_callsite();
240
241     let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
242         Ok(snippet) => {
243             // Count the number of `#`s between the `r` and `"`.
244             let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
245             (Some(snippet), style)
246         }
247         Err(_) => (None, None),
248     };
249
250     let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
251     let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
252
253     if n_arguments > 0 && fmt_parser.errors.is_empty() {
254         let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
255             [] => vec![fmt_span],
256             v => v
257                 .iter()
258                 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
259                 .collect(),
260         };
261         cx.struct_span_lint(NON_FMT_PANICS, arg_spans, |lint| {
262             let mut l = lint.build(fluent::lint::non_fmt_panic_unused);
263             l.set_arg("count", n_arguments);
264             l.note(fluent::lint::note);
265             if is_arg_inside_call(arg.span, span) {
266                 l.span_suggestion(
267                     arg.span.shrink_to_hi(),
268                     fluent::lint::add_args_suggestion,
269                     ", ...",
270                     Applicability::HasPlaceholders,
271                 );
272                 l.span_suggestion(
273                     arg.span.shrink_to_lo(),
274                     fluent::lint::add_fmt_suggestion,
275                     "\"{}\", ",
276                     Applicability::MachineApplicable,
277                 );
278             }
279             l.emit();
280         });
281     } else {
282         let brace_spans: Option<Vec<_>> =
283             snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
284                 s.char_indices()
285                     .filter(|&(_, c)| c == '{' || c == '}')
286                     .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
287                     .collect()
288             });
289         let count = brace_spans.as_ref().map(|v| v.len()).unwrap_or(/* any number >1 */ 2);
290         cx.struct_span_lint(NON_FMT_PANICS, brace_spans.unwrap_or_else(|| vec![span]), |lint| {
291             let mut l = lint.build(fluent::lint::non_fmt_panic_braces);
292             l.set_arg("count", count);
293             l.note(fluent::lint::note);
294             if is_arg_inside_call(arg.span, span) {
295                 l.span_suggestion(
296                     arg.span.shrink_to_lo(),
297                     fluent::lint::suggestion,
298                     "\"{}\", ",
299                     Applicability::MachineApplicable,
300                 );
301             }
302             l.emit();
303         });
304     }
305 }
306
307 /// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
308 /// and the type of (opening) delimiter used.
309 fn find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Span, char)> {
310     let snippet = cx.sess().parse_sess.source_map().span_to_snippet(span).ok()?;
311     let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
312     let close = snippet.rfind(|c| ")]}".contains(c))?;
313     Some((
314         span.from_inner(InnerSpan { start: open, end: open + 1 }),
315         span.from_inner(InnerSpan { start: close, end: close + 1 }),
316         open_ch,
317     ))
318 }
319
320 fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, Symbol) {
321     let mut expn = f.span.ctxt().outer_expn_data();
322
323     let mut panic_macro = kw::Empty;
324
325     // Unwrap more levels of macro expansion, as panic_2015!()
326     // was likely expanded from panic!() and possibly from
327     // [debug_]assert!().
328     loop {
329         let parent = expn.call_site.ctxt().outer_expn_data();
330         let Some(id) = parent.macro_def_id else { break };
331         let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
332         if !matches!(
333             name,
334             sym::core_panic_macro
335                 | sym::std_panic_macro
336                 | sym::assert_macro
337                 | sym::debug_assert_macro
338                 | sym::unreachable_macro
339         ) {
340             break;
341         }
342         expn = parent;
343         panic_macro = name;
344     }
345
346     let macro_symbol =
347         if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
348     (expn.call_site, panic_macro, macro_symbol)
349 }
350
351 fn is_arg_inside_call(arg: Span, call: Span) -> bool {
352     // We only add suggestions if the argument we're looking at appears inside the
353     // panic call in the source file, to avoid invalid suggestions when macros are involved.
354     // We specifically check for the spans to not be identical, as that happens sometimes when
355     // proc_macros lie about spans and apply the same span to all the tokens they produce.
356     call.contains(arg) && !call.source_equal(arg)
357 }