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