]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_utils/src/diagnostics.rs
New upstream version 1.75.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_utils / src / diagnostics.rs
CommitLineData
f20569fa 1//! Clippy wrappers around rustc's diagnostic functions.
17df50a5
XL
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
f20569fa 10
064997fb 11use rustc_errors::{Applicability, Diagnostic, MultiSpan};
f20569fa
XL
12use rustc_hir::HirId;
13use rustc_lint::{LateContext, Lint, LintContext};
ed00b5ec 14use rustc_span::Span;
f20569fa
XL
15use std::env;
16
5e7ed085 17fn docs_link(diag: &mut Diagnostic, lint: &'static Lint) {
f20569fa 18 if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
cdc7bbd5 19 if let Some(lint) = lint.name_lower().strip_prefix("clippy::") {
9c376795 20 diag.help(format!(
2b03887a 21 "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{lint}",
cdc7bbd5
XL
22 &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| {
23 // extract just major + minor version and ignore patch versions
c295e0f8 24 format!("rust-{}", n.rsplit_once('.').unwrap().1)
2b03887a 25 })
cdc7bbd5
XL
26 ));
27 }
f20569fa
XL
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/// ```
48pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: impl Into<MultiSpan>, msg: &str) {
fe692bf9 49 cx.struct_span_lint(lint, sp, msg.to_string(), |diag| {
2b03887a
FG
50 docs_link(diag, lint);
51 diag
f20569fa
XL
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///
94222f64 66/// ```text
f20569fa
XL
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/// |
3c0e092e 73/// = help: consider using `f64::NAN` if you would like a constant representing NaN
f20569fa 74/// ```
487cf647
FG
75pub fn span_lint_and_help<T: LintContext>(
76 cx: &T,
f20569fa 77 lint: &'static Lint,
923072b8 78 span: impl Into<MultiSpan>,
f20569fa
XL
79 msg: &str,
80 help_span: Option<Span>,
81 help: &str,
82) {
fe692bf9
FG
83 cx.struct_span_lint(lint, span, msg.to_string(), |diag| {
84 let help = help.to_string();
f20569fa 85 if let Some(help_span) = help_span {
fe692bf9 86 diag.span_help(help_span, help.to_string());
f20569fa 87 } else {
fe692bf9 88 diag.help(help.to_string());
f20569fa 89 }
2b03887a
FG
90 docs_link(diag, lint);
91 diag
f20569fa
XL
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///
94222f64 104/// ```text
f20569fa
XL
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/// ```
487cf647
FG
118pub fn span_lint_and_note<T: LintContext>(
119 cx: &T,
f20569fa
XL
120 lint: &'static Lint,
121 span: impl Into<MultiSpan>,
122 msg: &str,
123 note_span: Option<Span>,
124 note: &str,
125) {
fe692bf9
FG
126 cx.struct_span_lint(lint, span, msg.to_string(), |diag| {
127 let note = note.to_string();
f20569fa
XL
128 if let Some(note_span) = note_span {
129 diag.span_note(note_span, note);
130 } else {
131 diag.note(note);
132 }
2b03887a
FG
133 docs_link(diag, lint);
134 diag
f20569fa
XL
135 });
136}
137
138/// Like `span_lint` but allows to add notes, help and suggestions using a closure.
139///
140/// If you need to customize your lint output a lot, use this function.
141/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
cdc7bbd5 142pub fn span_lint_and_then<C, S, F>(cx: &C, lint: &'static Lint, sp: S, msg: &str, f: F)
f20569fa 143where
cdc7bbd5
XL
144 C: LintContext,
145 S: Into<MultiSpan>,
5e7ed085 146 F: FnOnce(&mut Diagnostic),
f20569fa 147{
fe692bf9 148 cx.struct_span_lint(lint, sp, msg.to_string(), |diag| {
2b03887a
FG
149 f(diag);
150 docs_link(diag, lint);
151 diag
f20569fa
XL
152 });
153}
154
f2b60f7d 155pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, sp: Span, msg: &str) {
fe692bf9 156 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg.to_string(), |diag| {
2b03887a
FG
157 docs_link(diag, lint);
158 diag
f20569fa
XL
159 });
160}
161
162pub fn span_lint_hir_and_then(
163 cx: &LateContext<'_>,
164 lint: &'static Lint,
165 hir_id: HirId,
17df50a5 166 sp: impl Into<MultiSpan>,
f20569fa 167 msg: &str,
5e7ed085 168 f: impl FnOnce(&mut Diagnostic),
f20569fa 169) {
fe692bf9 170 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg.to_string(), |diag| {
2b03887a
FG
171 f(diag);
172 docs_link(diag, lint);
173 diag
f20569fa
XL
174 });
175}
176
177/// Add a span lint with a suggestion on how to fix it.
178///
179/// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
180/// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
181/// 2)"`.
182///
183/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
184///
185/// # Example
186///
94222f64 187/// ```text
f20569fa
XL
188/// error: This `.fold` can be more succinctly expressed as `.any`
189/// --> $DIR/methods.rs:390:13
190/// |
191/// 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2);
192/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
193/// |
194/// = note: `-D fold-any` implied by `-D warnings`
195/// ```
ed00b5ec 196#[expect(clippy::collapsible_span_lint_calls)]
487cf647
FG
197pub fn span_lint_and_sugg<T: LintContext>(
198 cx: &T,
f20569fa
XL
199 lint: &'static Lint,
200 sp: Span,
201 msg: &str,
202 help: &str,
203 sugg: String,
204 applicability: Applicability,
205) {
206 span_lint_and_then(cx, lint, sp, msg, |diag| {
fe692bf9 207 diag.span_suggestion(sp, help.to_string(), sugg, applicability);
f20569fa
XL
208 });
209}
210
211/// Create a suggestion made from several `span → replacement`.
212///
213/// Note: in the JSON format (used by `compiletest_rs`), the help message will
214/// appear once per
215/// replacement. In human-readable format though, it only appears once before
216/// the whole suggestion.
5e7ed085 217pub fn multispan_sugg<I>(diag: &mut Diagnostic, help_msg: &str, sugg: I)
f20569fa
XL
218where
219 I: IntoIterator<Item = (Span, String)>,
220{
17df50a5 221 multispan_sugg_with_applicability(diag, help_msg, Applicability::Unspecified, sugg);
f20569fa
XL
222}
223
cdc7bbd5
XL
224/// Create a suggestion made from several `span → replacement`.
225///
226/// rustfix currently doesn't support the automatic application of suggestions with
227/// multiple spans. This is tracked in issue [rustfix#141](https://github.com/rust-lang/rustfix/issues/141).
228/// Suggestions with multiple spans will be silently ignored.
f20569fa 229pub fn multispan_sugg_with_applicability<I>(
5e7ed085 230 diag: &mut Diagnostic,
f20569fa
XL
231 help_msg: &str,
232 applicability: Applicability,
233 sugg: I,
234) where
235 I: IntoIterator<Item = (Span, String)>,
236{
fe692bf9 237 diag.multipart_suggestion(help_msg.to_string(), sugg.into_iter().collect(), applicability);
f20569fa 238}