]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/diagnostics.rs
Rollup merge of #102500 - compiler-errors:parse-sess-cleanup, r=cjgillot
[rust.git] / src / tools / clippy / 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::{Applicability, Diagnostic, MultiSpan};
12 use rustc_hir::HirId;
13 use rustc_lint::{LateContext, Lint, LintContext};
14 use rustc_span::source_map::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, msg, |diag| {
51         docs_link(diag, lint);
52         diag
53     });
54 }
55
56 /// Same as `span_lint` but with an extra `help` message.
57 ///
58 /// Use this if you want to provide some general help but
59 /// can't provide a specific machine applicable suggestion.
60 ///
61 /// The `help` message can be optionally attached to a `Span`.
62 ///
63 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
64 ///
65 /// # Example
66 ///
67 /// ```text
68 /// error: constant division of 0.0 with 0.0 will always result in NaN
69 ///   --> $DIR/zero_div_zero.rs:6:25
70 ///    |
71 /// 6  |     let other_f64_nan = 0.0f64 / 0.0;
72 ///    |                         ^^^^^^^^^^^^
73 ///    |
74 ///    = help: consider using `f64::NAN` if you would like a constant representing NaN
75 /// ```
76 pub fn span_lint_and_help<'a, T: LintContext>(
77     cx: &'a T,
78     lint: &'static Lint,
79     span: impl Into<MultiSpan>,
80     msg: &str,
81     help_span: Option<Span>,
82     help: &str,
83 ) {
84     cx.struct_span_lint(lint, span, msg, |diag| {
85         if let Some(help_span) = help_span {
86             diag.span_help(help_span, help);
87         } else {
88             diag.help(help);
89         }
90         docs_link(diag, lint);
91         diag
92     });
93 }
94
95 /// Like `span_lint` but with a `note` section instead of a `help` message.
96 ///
97 /// The `note` message is presented separately from the main lint message
98 /// and is attached to a specific span:
99 ///
100 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
101 ///
102 /// # Example
103 ///
104 /// ```text
105 /// error: calls to `std::mem::forget` with a reference instead of an owned value. Forgetting a reference does nothing.
106 ///   --> $DIR/drop_forget_ref.rs:10:5
107 ///    |
108 /// 10 |     forget(&SomeStruct);
109 ///    |     ^^^^^^^^^^^^^^^^^^^
110 ///    |
111 ///    = note: `-D clippy::forget-ref` implied by `-D warnings`
112 /// note: argument has type &SomeStruct
113 ///   --> $DIR/drop_forget_ref.rs:10:12
114 ///    |
115 /// 10 |     forget(&SomeStruct);
116 ///    |            ^^^^^^^^^^^
117 /// ```
118 pub fn span_lint_and_note<'a, T: LintContext>(
119     cx: &'a T,
120     lint: &'static Lint,
121     span: impl Into<MultiSpan>,
122     msg: &str,
123     note_span: Option<Span>,
124     note: &str,
125 ) {
126     cx.struct_span_lint(lint, span, msg, |diag| {
127         if let Some(note_span) = note_span {
128             diag.span_note(note_span, note);
129         } else {
130             diag.note(note);
131         }
132         docs_link(diag, lint);
133         diag
134     });
135 }
136
137 /// Like `span_lint` but allows to add notes, help and suggestions using a closure.
138 ///
139 /// If you need to customize your lint output a lot, use this function.
140 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
141 pub fn span_lint_and_then<C, S, F>(cx: &C, lint: &'static Lint, sp: S, msg: &str, f: F)
142 where
143     C: LintContext,
144     S: Into<MultiSpan>,
145     F: FnOnce(&mut Diagnostic),
146 {
147     cx.struct_span_lint(lint, sp, msg, |diag| {
148         f(diag);
149         docs_link(diag, lint);
150         diag
151     });
152 }
153
154 pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, sp: Span, msg: &str) {
155     cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg, |diag| {
156         docs_link(diag, lint);
157         diag
158     });
159 }
160
161 pub fn span_lint_hir_and_then(
162     cx: &LateContext<'_>,
163     lint: &'static Lint,
164     hir_id: HirId,
165     sp: impl Into<MultiSpan>,
166     msg: &str,
167     f: impl FnOnce(&mut Diagnostic),
168 ) {
169     cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg, |diag| {
170         f(diag);
171         docs_link(diag, lint);
172         diag
173     });
174 }
175
176 /// Add a span lint with a suggestion on how to fix it.
177 ///
178 /// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
179 /// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
180 /// 2)"`.
181 ///
182 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
183 ///
184 /// # Example
185 ///
186 /// ```text
187 /// error: This `.fold` can be more succinctly expressed as `.any`
188 /// --> $DIR/methods.rs:390:13
189 ///     |
190 /// 390 |     let _ = (0..3).fold(false, |acc, x| acc || x > 2);
191 ///     |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
192 ///     |
193 ///     = note: `-D fold-any` implied by `-D warnings`
194 /// ```
195 #[cfg_attr(feature = "internal", allow(clippy::collapsible_span_lint_calls))]
196 pub fn span_lint_and_sugg<'a, T: LintContext>(
197     cx: &'a T,
198     lint: &'static Lint,
199     sp: Span,
200     msg: &str,
201     help: &str,
202     sugg: String,
203     applicability: Applicability,
204 ) {
205     span_lint_and_then(cx, lint, sp, msg, |diag| {
206         diag.span_suggestion(sp, help, sugg, applicability);
207     });
208 }
209
210 /// Create a suggestion made from several `span → replacement`.
211 ///
212 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
213 /// appear once per
214 /// replacement. In human-readable format though, it only appears once before
215 /// the whole suggestion.
216 pub fn multispan_sugg<I>(diag: &mut Diagnostic, help_msg: &str, sugg: I)
217 where
218     I: IntoIterator<Item = (Span, String)>,
219 {
220     multispan_sugg_with_applicability(diag, help_msg, Applicability::Unspecified, sugg);
221 }
222
223 /// Create a suggestion made from several `span → replacement`.
224 ///
225 /// rustfix currently doesn't support the automatic application of suggestions with
226 /// multiple spans. This is tracked in issue [rustfix#141](https://github.com/rust-lang/rustfix/issues/141).
227 /// Suggestions with multiple spans will be silently ignored.
228 pub fn multispan_sugg_with_applicability<I>(
229     diag: &mut Diagnostic,
230     help_msg: &str,
231     applicability: Applicability,
232     sugg: I,
233 ) where
234     I: IntoIterator<Item = (Span, String)>,
235 {
236     diag.multipart_suggestion(help_msg, sugg.into_iter().collect(), applicability);
237 }