]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/diagnostics.rs
Auto merge of #8487 - dswij:8478, r=giraffate
[rust.git] / clippy_utils / src / diagnostics.rs
1 //! Clippy wrappers around rustc's diagnostic functions.
2 //!
3 //! These functions are used by the `INTERNAL_METADATA_COLLECTOR` lint to collect the corresponding
4 //! lint applicability. Please make sure that you update the `LINT_EMISSION_FUNCTIONS` variable in
5 //! `clippy_lints::utils::internal_lints::metadata_collector` when a new function is added
6 //! or renamed.
7 //!
8 //! Thank you!
9 //! ~The `INTERNAL_METADATA_COLLECTOR` lint
10
11 use rustc_errors::{emitter::MAX_SUGGESTION_HIGHLIGHT_LINES, Applicability, Diagnostic};
12 use rustc_hir::HirId;
13 use rustc_lint::{LateContext, Lint, LintContext};
14 use rustc_span::source_map::{MultiSpan, Span};
15 use std::env;
16
17 fn docs_link(diag: &mut Diagnostic, lint: &'static Lint) {
18     if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
19         if let Some(lint) = lint.name_lower().strip_prefix("clippy::") {
20             diag.help(&format!(
21                 "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{}",
22                 &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| {
23                     // extract just major + minor version and ignore patch versions
24                     format!("rust-{}", n.rsplit_once('.').unwrap().1)
25                 }),
26                 lint
27             ));
28         }
29     }
30 }
31
32 /// Emit a basic lint message with a `msg` and a `span`.
33 ///
34 /// This is the most primitive of our lint emission methods and can
35 /// be a good way to get a new lint started.
36 ///
37 /// Usually it's nicer to provide more context for lint messages.
38 /// Be sure the output is understandable when you use this method.
39 ///
40 /// # Example
41 ///
42 /// ```ignore
43 /// error: usage of mem::forget on Drop type
44 ///   --> $DIR/mem_forget.rs:17:5
45 ///    |
46 /// 17 |     std::mem::forget(seven);
47 ///    |     ^^^^^^^^^^^^^^^^^^^^^^^
48 /// ```
49 pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: impl Into<MultiSpan>, msg: &str) {
50     cx.struct_span_lint(lint, sp, |diag| {
51         let mut diag = diag.build(msg);
52         docs_link(&mut diag, lint);
53         diag.emit();
54     });
55 }
56
57 /// Same as `span_lint` but with an extra `help` message.
58 ///
59 /// Use this if you want to provide some general help but
60 /// can't provide a specific machine applicable suggestion.
61 ///
62 /// The `help` message can be optionally attached to a `Span`.
63 ///
64 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
65 ///
66 /// # Example
67 ///
68 /// ```text
69 /// error: constant division of 0.0 with 0.0 will always result in NaN
70 ///   --> $DIR/zero_div_zero.rs:6:25
71 ///    |
72 /// 6  |     let other_f64_nan = 0.0f64 / 0.0;
73 ///    |                         ^^^^^^^^^^^^
74 ///    |
75 ///    = help: consider using `f64::NAN` if you would like a constant representing NaN
76 /// ```
77 pub fn span_lint_and_help<'a, T: LintContext>(
78     cx: &'a T,
79     lint: &'static Lint,
80     span: Span,
81     msg: &str,
82     help_span: Option<Span>,
83     help: &str,
84 ) {
85     cx.struct_span_lint(lint, span, |diag| {
86         let mut diag = diag.build(msg);
87         if let Some(help_span) = help_span {
88             diag.span_help(help_span, help);
89         } else {
90             diag.help(help);
91         }
92         docs_link(&mut diag, lint);
93         diag.emit();
94     });
95 }
96
97 /// Like `span_lint` but with a `note` section instead of a `help` message.
98 ///
99 /// The `note` message is presented separately from the main lint message
100 /// and is attached to a specific span:
101 ///
102 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
103 ///
104 /// # Example
105 ///
106 /// ```text
107 /// error: calls to `std::mem::forget` with a reference instead of an owned value. Forgetting a reference does nothing.
108 ///   --> $DIR/drop_forget_ref.rs:10:5
109 ///    |
110 /// 10 |     forget(&SomeStruct);
111 ///    |     ^^^^^^^^^^^^^^^^^^^
112 ///    |
113 ///    = note: `-D clippy::forget-ref` implied by `-D warnings`
114 /// note: argument has type &SomeStruct
115 ///   --> $DIR/drop_forget_ref.rs:10:12
116 ///    |
117 /// 10 |     forget(&SomeStruct);
118 ///    |            ^^^^^^^^^^^
119 /// ```
120 pub fn span_lint_and_note<'a, T: LintContext>(
121     cx: &'a T,
122     lint: &'static Lint,
123     span: impl Into<MultiSpan>,
124     msg: &str,
125     note_span: Option<Span>,
126     note: &str,
127 ) {
128     cx.struct_span_lint(lint, span, |diag| {
129         let mut diag = diag.build(msg);
130         if let Some(note_span) = note_span {
131             diag.span_note(note_span, note);
132         } else {
133             diag.note(note);
134         }
135         docs_link(&mut diag, lint);
136         diag.emit();
137     });
138 }
139
140 /// Like `span_lint` but allows to add notes, help and suggestions using a closure.
141 ///
142 /// If you need to customize your lint output a lot, use this function.
143 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
144 pub fn span_lint_and_then<C, S, F>(cx: &C, lint: &'static Lint, sp: S, msg: &str, f: F)
145 where
146     C: LintContext,
147     S: Into<MultiSpan>,
148     F: FnOnce(&mut Diagnostic),
149 {
150     cx.struct_span_lint(lint, sp, |diag| {
151         let mut diag = diag.build(msg);
152         f(&mut diag);
153         docs_link(&mut diag, lint);
154         diag.emit();
155     });
156 }
157
158 pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, sp: Span, msg: &str) {
159     cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |diag| {
160         let mut diag = diag.build(msg);
161         docs_link(&mut diag, lint);
162         diag.emit();
163     });
164 }
165
166 pub fn span_lint_hir_and_then(
167     cx: &LateContext<'_>,
168     lint: &'static Lint,
169     hir_id: HirId,
170     sp: impl Into<MultiSpan>,
171     msg: &str,
172     f: impl FnOnce(&mut Diagnostic),
173 ) {
174     cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |diag| {
175         let mut diag = diag.build(msg);
176         f(&mut diag);
177         docs_link(&mut diag, lint);
178         diag.emit();
179     });
180 }
181
182 /// Add a span lint with a suggestion on how to fix it.
183 ///
184 /// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
185 /// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
186 /// 2)"`.
187 ///
188 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
189 ///
190 /// # Example
191 ///
192 /// ```text
193 /// error: This `.fold` can be more succinctly expressed as `.any`
194 /// --> $DIR/methods.rs:390:13
195 ///     |
196 /// 390 |     let _ = (0..3).fold(false, |acc, x| acc || x > 2);
197 ///     |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
198 ///     |
199 ///     = note: `-D fold-any` implied by `-D warnings`
200 /// ```
201 #[cfg_attr(feature = "internal", allow(clippy::collapsible_span_lint_calls))]
202 pub fn span_lint_and_sugg<'a, T: LintContext>(
203     cx: &'a T,
204     lint: &'static Lint,
205     sp: Span,
206     msg: &str,
207     help: &str,
208     sugg: String,
209     applicability: Applicability,
210 ) {
211     span_lint_and_then(cx, lint, sp, msg, |diag| {
212         diag.span_suggestion(sp, help, sugg, applicability);
213     });
214 }
215
216 /// Like [`span_lint_and_sugg`] with a focus on the edges. The output will either
217 /// emit single span or multispan suggestion depending on the number of its lines.
218 ///
219 /// If the given suggestion string has more lines than the maximum display length defined by
220 /// [`MAX_SUGGESTION_HIGHLIGHT_LINES`][`rustc_errors::emitter::MAX_SUGGESTION_HIGHLIGHT_LINES`],
221 /// this function will split the suggestion and span to showcase the change for the top and
222 /// bottom edge of the code. For normal suggestions, in one display window, the help message
223 /// will be combined with a colon.
224 ///
225 /// Multipart suggestions like the one being created here currently cannot be
226 /// applied by rustfix (See [rustfix#141](https://github.com/rust-lang/rustfix/issues/141)).
227 /// Testing rustfix with this lint emission function might require a file with
228 /// suggestions that can be fixed and those that can't. See
229 /// [clippy#8520](https://github.com/rust-lang/rust-clippy/pull/8520/files) for
230 /// an example and of this.
231 ///
232 /// # Example for a long suggestion
233 ///
234 /// ```text
235 /// error: called `map(..).flatten()` on `Option`
236 ///   --> $DIR/map_flatten.rs:8:10
237 ///    |
238 /// LL |           .map(|x| {
239 ///    |  __________^
240 /// LL | |             if x <= 5 {
241 /// LL | |                 Some(x)
242 /// LL | |             } else {
243 /// ...  |
244 /// LL | |         })
245 /// LL | |         .flatten();
246 ///    | |__________________^
247 ///    |
248 ///   = note: `-D clippy::map-flatten` implied by `-D warnings`
249 /// help: try replacing `map` with `and_then`
250 ///    |
251 /// LL ~         .and_then(|x| {
252 /// LL +             if x <= 5 {
253 /// LL +                 Some(x)
254 ///    |
255 /// help: and remove the `.flatten()`
256 ///    |
257 /// LL +                 None
258 /// LL +             }
259 /// LL ~         });
260 ///    |
261 /// ```
262 pub fn span_lint_and_sugg_for_edges(
263     cx: &LateContext<'_>,
264     lint: &'static Lint,
265     sp: Span,
266     msg: &str,
267     helps: &[&str; 2],
268     sugg: String,
269     applicability: Applicability,
270 ) {
271     span_lint_and_then(cx, lint, sp, msg, |diag| {
272         let sugg_lines_count = sugg.lines().count();
273         if sugg_lines_count > MAX_SUGGESTION_HIGHLIGHT_LINES {
274             let sm = cx.sess().source_map();
275             if let (Ok(line_upper), Ok(line_bottom)) = (sm.lookup_line(sp.lo()), sm.lookup_line(sp.hi())) {
276                 let split_idx = MAX_SUGGESTION_HIGHLIGHT_LINES / 2;
277                 let span_upper = sm.span_until_char(sp.with_hi(line_upper.sf.lines[line_upper.line + split_idx]), '\n');
278                 let span_bottom = sp.with_lo(line_bottom.sf.lines[line_bottom.line - split_idx]);
279
280                 let sugg_lines_vec = sugg.lines().collect::<Vec<&str>>();
281                 let sugg_upper = sugg_lines_vec[..split_idx].join("\n");
282                 let sugg_bottom = sugg_lines_vec[sugg_lines_count - split_idx..].join("\n");
283
284                 diag.span_suggestion(span_upper, helps[0], sugg_upper, applicability);
285                 diag.span_suggestion(span_bottom, helps[1], sugg_bottom, applicability);
286
287                 return;
288             }
289         }
290         diag.span_suggestion_with_style(
291             sp,
292             &helps.join(", "),
293             sugg,
294             applicability,
295             rustc_errors::SuggestionStyle::ShowAlways,
296         );
297     });
298 }
299
300 /// Create a suggestion made from several `span → replacement`.
301 ///
302 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
303 /// appear once per
304 /// replacement. In human-readable format though, it only appears once before
305 /// the whole suggestion.
306 pub fn multispan_sugg<I>(diag: &mut Diagnostic, help_msg: &str, sugg: I)
307 where
308     I: IntoIterator<Item = (Span, String)>,
309 {
310     multispan_sugg_with_applicability(diag, help_msg, Applicability::Unspecified, sugg);
311 }
312
313 /// Create a suggestion made from several `span → replacement`.
314 ///
315 /// rustfix currently doesn't support the automatic application of suggestions with
316 /// multiple spans. This is tracked in issue [rustfix#141](https://github.com/rust-lang/rustfix/issues/141).
317 /// Suggestions with multiple spans will be silently ignored.
318 pub fn multispan_sugg_with_applicability<I>(
319     diag: &mut Diagnostic,
320     help_msg: &str,
321     applicability: Applicability,
322     sugg: I,
323 ) where
324     I: IntoIterator<Item = (Span, String)>,
325 {
326     diag.multipart_suggestion(help_msg, sugg.into_iter().collect(), applicability);
327 }