]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_utils/src/diagnostics.rs
New upstream version 1.64.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};
04454e1e 14use rustc_span::source_map::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
XL
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
c295e0f8 24 format!("rust-{}", n.rsplit_once('.').unwrap().1)
cdc7bbd5
XL
25 }),
26 lint
27 ));
28 }
f20569fa
XL
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/// ```
49pub 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///
94222f64 68/// ```text
f20569fa
XL
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/// |
3c0e092e 75/// = help: consider using `f64::NAN` if you would like a constant representing NaN
f20569fa
XL
76/// ```
77pub fn span_lint_and_help<'a, T: LintContext>(
78 cx: &'a T,
79 lint: &'static Lint,
923072b8 80 span: impl Into<MultiSpan>,
f20569fa
XL
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///
94222f64 106/// ```text
f20569fa
XL
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/// ```
120pub 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`
cdc7bbd5 144pub fn span_lint_and_then<C, S, F>(cx: &C, lint: &'static Lint, sp: S, msg: &str, f: F)
f20569fa 145where
cdc7bbd5
XL
146 C: LintContext,
147 S: Into<MultiSpan>,
5e7ed085 148 F: FnOnce(&mut Diagnostic),
f20569fa
XL
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
04454e1e
FG
158pub fn span_lint_hir(
159 cx: &LateContext<'_>,
160 lint: &'static Lint,
161 hir_id: HirId,
162 sp: Span,
163 msg: &str,
164) {
f20569fa
XL
165 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |diag| {
166 let mut diag = diag.build(msg);
167 docs_link(&mut diag, lint);
168 diag.emit();
169 });
170}
171
172pub fn span_lint_hir_and_then(
173 cx: &LateContext<'_>,
174 lint: &'static Lint,
175 hir_id: HirId,
17df50a5 176 sp: impl Into<MultiSpan>,
f20569fa 177 msg: &str,
5e7ed085 178 f: impl FnOnce(&mut Diagnostic),
f20569fa
XL
179) {
180 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |diag| {
181 let mut diag = diag.build(msg);
182 f(&mut diag);
183 docs_link(&mut diag, lint);
184 diag.emit();
185 });
186}
187
188/// Add a span lint with a suggestion on how to fix it.
189///
190/// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
191/// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
192/// 2)"`.
193///
194/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
195///
196/// # Example
197///
94222f64 198/// ```text
f20569fa
XL
199/// error: This `.fold` can be more succinctly expressed as `.any`
200/// --> $DIR/methods.rs:390:13
201/// |
202/// 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2);
203/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
204/// |
205/// = note: `-D fold-any` implied by `-D warnings`
206/// ```
5099ac24 207#[cfg_attr(feature = "internal", allow(clippy::collapsible_span_lint_calls))]
f20569fa
XL
208pub fn span_lint_and_sugg<'a, T: LintContext>(
209 cx: &'a T,
210 lint: &'static Lint,
211 sp: Span,
212 msg: &str,
213 help: &str,
214 sugg: String,
215 applicability: Applicability,
216) {
217 span_lint_and_then(cx, lint, sp, msg, |diag| {
218 diag.span_suggestion(sp, help, sugg, applicability);
219 });
220}
221
222/// Create a suggestion made from several `span → replacement`.
223///
224/// Note: in the JSON format (used by `compiletest_rs`), the help message will
225/// appear once per
226/// replacement. In human-readable format though, it only appears once before
227/// the whole suggestion.
5e7ed085 228pub fn multispan_sugg<I>(diag: &mut Diagnostic, help_msg: &str, sugg: I)
f20569fa
XL
229where
230 I: IntoIterator<Item = (Span, String)>,
231{
17df50a5 232 multispan_sugg_with_applicability(diag, help_msg, Applicability::Unspecified, sugg);
f20569fa
XL
233}
234
cdc7bbd5
XL
235/// Create a suggestion made from several `span → replacement`.
236///
237/// rustfix currently doesn't support the automatic application of suggestions with
238/// multiple spans. This is tracked in issue [rustfix#141](https://github.com/rust-lang/rustfix/issues/141).
239/// Suggestions with multiple spans will be silently ignored.
f20569fa 240pub fn multispan_sugg_with_applicability<I>(
5e7ed085 241 diag: &mut Diagnostic,
f20569fa
XL
242 help_msg: &str,
243 applicability: Applicability,
244 sugg: I,
245) where
246 I: IntoIterator<Item = (Span, String)>,
247{
248 diag.multipart_suggestion(help_msg, sugg.into_iter().collect(), applicability);
249}