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_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, symbol::SymbolStr, 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 {
check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>)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                 if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
53                     || Some(def_id) == cx.tcx.lang_items().panic_fn()
54                     || Some(def_id) == cx.tcx.lang_items().panic_str()
55                 {
56                     if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
57                         if matches!(
58                             cx.tcx.get_diagnostic_name(id),
59                             Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro)
60                         ) {
61                             check_panic(cx, f, arg);
62                         }
63                     }
64                 }
65             }
66         }
67     }
68 }
69 
check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>)70 fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
71     if let hir::ExprKind::Lit(lit) = &arg.kind {
72         if let ast::LitKind::Str(sym, _) = lit.node {
73             // The argument is a string literal.
74             check_panic_str(cx, f, arg, &sym.as_str());
75             return;
76         }
77     }
78 
79     // The argument is *not* a string literal.
80 
81     let (span, panic, symbol_str) = panic_call(cx, f);
82 
83     if in_external_macro(cx.sess(), span) {
84         // Nothing that can be done about it in the current crate.
85         return;
86     }
87 
88     // Find the span of the argument to `panic!()`, before expansion in the
89     // case of `panic!(some_macro!())`.
90     // We don't use source_callsite(), because this `panic!(..)` might itself
91     // be expanded from another macro, in which case we want to stop at that
92     // expansion.
93     let mut arg_span = arg.span;
94     let mut arg_macro = None;
95     while !span.contains(arg_span) {
96         let expn = arg_span.ctxt().outer_expn_data();
97         if expn.is_root() {
98             break;
99         }
100         arg_macro = expn.macro_def_id;
101         arg_span = expn.call_site;
102     }
103 
104     cx.struct_span_lint(NON_FMT_PANICS, arg_span, |lint| {
105         let mut l = lint.build("panic message is not a string literal");
106         l.note(&format!("this usage of {}!() is deprecated; it will be a hard error in Rust 2021", symbol_str));
107         l.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/panic-macro-consistency.html>");
108         if !is_arg_inside_call(arg_span, span) {
109             // No clue where this argument is coming from.
110             l.emit();
111             return;
112         }
113         if arg_macro.map_or(false, |id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
114             // A case of `panic!(format!(..))`.
115             l.note(format!("the {}!() macro supports formatting, so there's no need for the format!() macro here", symbol_str).as_str());
116             if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
117                 l.multipart_suggestion(
118                     "remove the `format!(..)` macro call",
119                     vec![
120                         (arg_span.until(open.shrink_to_hi()), "".into()),
121                         (close.until(arg_span.shrink_to_hi()), "".into()),
122                     ],
123                     Applicability::MachineApplicable,
124                 );
125             }
126         } else {
127             let ty = cx.typeck_results().expr_ty(arg);
128             // If this is a &str or String, we can confidently give the `"{}", ` suggestion.
129             let is_str = matches!(
130                 ty.kind(),
131                 ty::Ref(_, r, _) if *r.kind() == ty::Str,
132             ) || matches!(
133                 ty.ty_adt_def(),
134                 Some(ty_def) if cx.tcx.is_diagnostic_item(sym::String, ty_def.did),
135             );
136 
137             let (suggest_display, suggest_debug) = cx.tcx.infer_ctxt().enter(|infcx| {
138                 let display = is_str || cx.tcx.get_diagnostic_item(sym::Display).map(|t| {
139                     infcx.type_implements_trait(t, ty, InternalSubsts::empty(), cx.param_env).may_apply()
140                 }) == Some(true);
141                 let debug = !display && cx.tcx.get_diagnostic_item(sym::Debug).map(|t| {
142                     infcx.type_implements_trait(t, ty, InternalSubsts::empty(), cx.param_env).may_apply()
143                 }) == Some(true);
144                 (display, debug)
145             });
146 
147             let suggest_panic_any = !is_str && panic == sym::std_panic_macro;
148 
149             let fmt_applicability = if suggest_panic_any {
150                 // If we can use panic_any, use that as the MachineApplicable suggestion.
151                 Applicability::MaybeIncorrect
152             } else {
153                 // If we don't suggest panic_any, using a format string is our best bet.
154                 Applicability::MachineApplicable
155             };
156 
157             if suggest_display {
158                 l.span_suggestion_verbose(
159                     arg_span.shrink_to_lo(),
160                     "add a \"{}\" format string to Display the message",
161                     "\"{}\", ".into(),
162                     fmt_applicability,
163                 );
164             } else if suggest_debug {
165                 l.span_suggestion_verbose(
166                     arg_span.shrink_to_lo(),
167                     &format!(
168                         "add a \"{{:?}}\" format string to use the Debug implementation of `{}`",
169                         ty,
170                     ),
171                     "\"{:?}\", ".into(),
172                     fmt_applicability,
173                 );
174             }
175 
176             if suggest_panic_any {
177                 if let Some((open, close, del)) = find_delimiters(cx, span) {
178                     l.multipart_suggestion(
179                         &format!(
180                             "{}use std::panic::panic_any instead",
181                             if suggest_display || suggest_debug {
182                                 "or "
183                             } else {
184                                 ""
185                             },
186                         ),
187                         if del == '(' {
188                             vec![(span.until(open), "std::panic::panic_any".into())]
189                         } else {
190                             vec![
191                                 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
192                                 (close, ")".into()),
193                             ]
194                         },
195                         Applicability::MachineApplicable,
196                     );
197                 }
198             }
199         }
200         l.emit();
201     });
202 }
203 
check_panic_str<'tcx>( cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>, fmt: &str, )204 fn check_panic_str<'tcx>(
205     cx: &LateContext<'tcx>,
206     f: &'tcx hir::Expr<'tcx>,
207     arg: &'tcx hir::Expr<'tcx>,
208     fmt: &str,
209 ) {
210     if !fmt.contains(&['{', '}'][..]) {
211         // No brace, no problem.
212         return;
213     }
214 
215     let (span, _, _) = panic_call(cx, f);
216 
217     if in_external_macro(cx.sess(), span) && in_external_macro(cx.sess(), arg.span) {
218         // Nothing that can be done about it in the current crate.
219         return;
220     }
221 
222     let fmt_span = arg.span.source_callsite();
223 
224     let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
225         Ok(snippet) => {
226             // Count the number of `#`s between the `r` and `"`.
227             let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
228             (Some(snippet), style)
229         }
230         Err(_) => (None, None),
231     };
232 
233     let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
234     let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
235 
236     if n_arguments > 0 && fmt_parser.errors.is_empty() {
237         let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
238             [] => vec![fmt_span],
239             v => v.iter().map(|span| fmt_span.from_inner(*span)).collect(),
240         };
241         cx.struct_span_lint(NON_FMT_PANICS, arg_spans, |lint| {
242             let mut l = lint.build(match n_arguments {
243                 1 => "panic message contains an unused formatting placeholder",
244                 _ => "panic message contains unused formatting placeholders",
245             });
246             l.note("this message is not used as a format string when given without arguments, but will be in Rust 2021");
247             if is_arg_inside_call(arg.span, span) {
248                 l.span_suggestion(
249                     arg.span.shrink_to_hi(),
250                     &format!("add the missing argument{}", pluralize!(n_arguments)),
251                     ", ...".into(),
252                     Applicability::HasPlaceholders,
253                 );
254                 l.span_suggestion(
255                     arg.span.shrink_to_lo(),
256                     "or add a \"{}\" format string to use the message literally",
257                     "\"{}\", ".into(),
258                     Applicability::MachineApplicable,
259                 );
260             }
261             l.emit();
262         });
263     } else {
264         let brace_spans: Option<Vec<_>> =
265             snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
266                 s.char_indices()
267                     .filter(|&(_, c)| c == '{' || c == '}')
268                     .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
269                     .collect()
270             });
271         let msg = match &brace_spans {
272             Some(v) if v.len() == 1 => "panic message contains a brace",
273             _ => "panic message contains braces",
274         };
275         cx.struct_span_lint(NON_FMT_PANICS, brace_spans.unwrap_or_else(|| vec![span]), |lint| {
276             let mut l = lint.build(msg);
277             l.note("this message is not used as a format string, but will be in Rust 2021");
278             if is_arg_inside_call(arg.span, span) {
279                 l.span_suggestion(
280                     arg.span.shrink_to_lo(),
281                     "add a \"{}\" format string to use the message literally",
282                     "\"{}\", ".into(),
283                     Applicability::MachineApplicable,
284                 );
285             }
286             l.emit();
287         });
288     }
289 }
290 
291 /// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
292 /// and the type of (opening) delimiter used.
find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Span, char)>293 fn find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Span, char)> {
294     let snippet = cx.sess().parse_sess.source_map().span_to_snippet(span).ok()?;
295     let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
296     let close = snippet.rfind(|c| ")]}".contains(c))?;
297     Some((
298         span.from_inner(InnerSpan { start: open, end: open + 1 }),
299         span.from_inner(InnerSpan { start: close, end: close + 1 }),
300         open_ch,
301     ))
302 }
303 
panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, SymbolStr)304 fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, SymbolStr) {
305     let mut expn = f.span.ctxt().outer_expn_data();
306 
307     let mut panic_macro = kw::Empty;
308 
309     // Unwrap more levels of macro expansion, as panic_2015!()
310     // was likely expanded from panic!() and possibly from
311     // [debug_]assert!().
312     for &i in
313         &[sym::std_panic_macro, sym::core_panic_macro, sym::assert_macro, sym::debug_assert_macro]
314     {
315         let parent = expn.call_site.ctxt().outer_expn_data();
316         if parent.macro_def_id.map_or(false, |id| cx.tcx.is_diagnostic_item(i, id)) {
317             expn = parent;
318             panic_macro = i;
319         }
320     }
321 
322     let macro_symbol =
323         if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
324     (expn.call_site, panic_macro, macro_symbol.as_str())
325 }
326 
is_arg_inside_call(arg: Span, call: Span) -> bool327 fn is_arg_inside_call(arg: Span, call: Span) -> bool {
328     // We only add suggestions if the argument we're looking at appears inside the
329     // panic call in the source file, to avoid invalid suggestions when macros are involved.
330     // We specifically check for the spans to not be identical, as that happens sometimes when
331     // proc_macros lie about spans and apply the same span to all the tokens they produce.
332     call.contains(arg) && !call.source_equal(&arg)
333 }
334