clippy_utils/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
11use rustc_errors::{Applicability, Diag, DiagMessage, MultiSpan};
12#[cfg(debug_assertions)]
13use rustc_errors::{EmissionGuarantee, SubstitutionPart, Suggestions};
14use rustc_hir::HirId;
15use rustc_lint::{LateContext, Lint, LintContext};
16use rustc_span::Span;
17use std::env;
18
19fn docs_link(diag: &mut Diag<'_, ()>, lint: &'static Lint) {
20 if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err()
21 && let Some(lint) = lint.name_lower().strip_prefix("clippy::")
22 {
23 diag.help(format!(
24 "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{lint}",
25 match option_env!("CFG_RELEASE_CHANNEL") {
26 // Clippy version is 0.1.xx
27 //
28 // Always use .0 because we do not generate separate lint doc pages for rust patch releases
29 Some("stable") => concat!("rust-1.", env!("CARGO_PKG_VERSION_PATCH"), ".0"),
30 Some("beta") => "beta",
31 _ => "master",
32 }
33 ));
34 }
35}
36
37/// Makes sure that a diagnostic is well formed.
38///
39/// rustc debug asserts a few properties about spans,
40/// but the clippy repo uses a distributed rustc build with debug assertions disabled,
41/// so this has historically led to problems during subtree syncs where those debug assertions
42/// only started triggered there.
43///
44/// This function makes sure we also validate them in debug clippy builds.
45#[cfg(debug_assertions)]
46fn validate_diag(diag: &Diag<'_, impl EmissionGuarantee>) {
47 let suggestions = match &diag.suggestions {
48 Suggestions::Enabled(suggs) => &**suggs,
49 Suggestions::Sealed(suggs) => &**suggs,
50 Suggestions::Disabled => return,
51 };
52
53 for substitution in suggestions.iter().flat_map(|s| &s.substitutions) {
54 assert_eq!(
55 substitution
56 .parts
57 .iter()
58 .find(|SubstitutionPart { snippet, span }| snippet.is_empty() && span.is_empty()),
59 None,
60 "span must not be empty and have no suggestion"
61 );
62
63 assert_eq!(
64 substitution
65 .parts
66 .array_windows()
67 .find(|[a, b]| a.span.overlaps(b.span)),
68 None,
69 "suggestion must not have overlapping parts"
70 );
71 }
72}
73
74/// Emit a basic lint message with a `msg` and a `span`.
75///
76/// This is the most primitive of our lint emission methods and can
77/// be a good way to get a new lint started.
78///
79/// Usually it's nicer to provide more context for lint messages.
80/// Be sure the output is understandable when you use this method.
81///
82/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
83/// the lint level.
84/// For the `span_lint` function, the node that was passed into the `LintPass::check_*` function is
85/// used.
86///
87/// If you're emitting the lint at the span of a different node than the one provided by the
88/// `LintPass::check_*` function, consider using [`span_lint_hir`] instead.
89/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
90/// highlighted in the displayed warning.
91///
92/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
93/// where you would expect it to.
94/// If it doesn't, you likely need to use [`span_lint_hir`] instead.
95///
96/// # Example
97///
98/// ```ignore
99/// error: usage of mem::forget on Drop type
100/// --> tests/ui/mem_forget.rs:17:5
101/// |
102/// 17 | std::mem::forget(seven);
103/// | ^^^^^^^^^^^^^^^^^^^^^^^
104/// ```
105#[track_caller]
106pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: impl Into<MultiSpan>, msg: impl Into<DiagMessage>) {
107 span_lint_and_then(cx, lint, sp, msg, |_| {});
108}
109
110/// Same as [`span_lint`] but with an extra `help` message.
111///
112/// Use this if you want to provide some general help but
113/// can't provide a specific machine applicable suggestion.
114///
115/// The `help` message can be optionally attached to a `Span`.
116///
117/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
118///
119/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
120/// the lint level.
121/// For the `span_lint_and_help` function, the node that was passed into the `LintPass::check_*`
122/// function is used.
123///
124/// If you're emitting the lint at the span of a different node than the one provided by the
125/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
126/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
127/// highlighted in the displayed warning.
128///
129/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
130/// where you would expect it to.
131/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
132///
133/// # Example
134///
135/// ```text
136/// error: constant division of 0.0 with 0.0 will always result in NaN
137/// --> tests/ui/zero_div_zero.rs:6:25
138/// |
139/// 6 | let other_f64_nan = 0.0f64 / 0.0;
140/// | ^^^^^^^^^^^^
141/// |
142/// = help: consider using `f64::NAN` if you would like a constant representing NaN
143/// ```
144#[track_caller]
145pub fn span_lint_and_help<T: LintContext>(
146 cx: &T,
147 lint: &'static Lint,
148 span: impl Into<MultiSpan>,
149 msg: impl Into<DiagMessage>,
150 help_span: Option<Span>,
151 help: impl Into<DiagMessage>,
152) {
153 span_lint_and_then(cx, lint, span, msg, |diag| {
154 if let Some(help_span) = help_span {
155 diag.span_help(help_span, help.into());
156 } else {
157 diag.help(help.into());
158 }
159 });
160}
161
162/// Like [`span_lint`] but with a `note` section instead of a `help` message.
163///
164/// The `note` message is presented separately from the main lint message
165/// and is attached to a specific span:
166///
167/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
168///
169/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
170/// the lint level.
171/// For the `span_lint_and_note` function, the node that was passed into the `LintPass::check_*`
172/// function is used.
173///
174/// If you're emitting the lint at the span of a different node than the one provided by the
175/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
176/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
177/// highlighted in the displayed warning.
178///
179/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
180/// where you would expect it to.
181/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
182///
183/// # Example
184///
185/// ```text
186/// error: calls to `std::mem::forget` with a reference instead of an owned value. Forgetting a reference does nothing.
187/// --> tests/ui/drop_forget_ref.rs:10:5
188/// |
189/// 10 | forget(&SomeStruct);
190/// | ^^^^^^^^^^^^^^^^^^^
191/// |
192/// = note: `-D clippy::forget-ref` implied by `-D warnings`
193/// note: argument has type &SomeStruct
194/// --> tests/ui/drop_forget_ref.rs:10:12
195/// |
196/// 10 | forget(&SomeStruct);
197/// | ^^^^^^^^^^^
198/// ```
199#[track_caller]
200pub fn span_lint_and_note<T: LintContext>(
201 cx: &T,
202 lint: &'static Lint,
203 span: impl Into<MultiSpan>,
204 msg: impl Into<DiagMessage>,
205 note_span: Option<Span>,
206 note: impl Into<DiagMessage>,
207) {
208 span_lint_and_then(cx, lint, span, msg, |diag| {
209 if let Some(note_span) = note_span {
210 diag.span_note(note_span, note.into());
211 } else {
212 diag.note(note.into());
213 }
214 });
215}
216
217/// Like [`span_lint`] but allows to add notes, help and suggestions using a closure.
218///
219/// If you need to customize your lint output a lot, use this function.
220/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
221///
222/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
223/// the lint level.
224/// For the `span_lint_and_then` function, the node that was passed into the `LintPass::check_*`
225/// function is used.
226///
227/// If you're emitting the lint at the span of a different node than the one provided by the
228/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
229/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
230/// highlighted in the displayed warning.
231///
232/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
233/// where you would expect it to.
234/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
235#[track_caller]
236pub fn span_lint_and_then<C, S, M, F>(cx: &C, lint: &'static Lint, sp: S, msg: M, f: F)
237where
238 C: LintContext,
239 S: Into<MultiSpan>,
240 M: Into<DiagMessage>,
241 F: FnOnce(&mut Diag<'_, ()>),
242{
243 #[expect(clippy::disallowed_methods)]
244 cx.span_lint(lint, sp, |diag| {
245 diag.primary_message(msg);
246 f(diag);
247 docs_link(diag, lint);
248
249 #[cfg(debug_assertions)]
250 validate_diag(diag);
251 });
252}
253
254/// Like [`span_lint`], but emits the lint at the node identified by the given `HirId`.
255///
256/// This is in contrast to [`span_lint`], which always emits the lint at the node that was last
257/// passed to the `LintPass::check_*` function.
258///
259/// The `HirId` is used for checking lint level attributes and to fulfill lint expectations defined
260/// via the `#[expect]` attribute.
261///
262/// For example:
263/// ```ignore
264/// fn f() { /* <node_1> */
265///
266/// #[allow(clippy::some_lint)]
267/// let _x = /* <expr_1> */;
268/// }
269/// ```
270/// If `some_lint` does its analysis in `LintPass::check_fn` (at `<node_1>`) and emits a lint at
271/// `<expr_1>` using [`span_lint`], then allowing the lint at `<expr_1>` as attempted in the snippet
272/// will not work!
273/// Even though that is where the warning points at, which would be confusing to users.
274///
275/// Instead, use this function and also pass the `HirId` of `<expr_1>`, which will let
276/// the compiler check lint level attributes at the place of the expression and
277/// the `#[allow]` will work.
278#[track_caller]
279pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, sp: Span, msg: impl Into<DiagMessage>) {
280 span_lint_hir_and_then(cx, lint, hir_id, sp, msg, |_| {});
281}
282
283/// Like [`span_lint_and_then`], but emits the lint at the node identified by the given `HirId`.
284///
285/// This is in contrast to [`span_lint_and_then`], which always emits the lint at the node that was
286/// last passed to the `LintPass::check_*` function.
287///
288/// The `HirId` is used for checking lint level attributes and to fulfill lint expectations defined
289/// via the `#[expect]` attribute.
290///
291/// For example:
292/// ```ignore
293/// fn f() { /* <node_1> */
294///
295/// #[allow(clippy::some_lint)]
296/// let _x = /* <expr_1> */;
297/// }
298/// ```
299/// If `some_lint` does its analysis in `LintPass::check_fn` (at `<node_1>`) and emits a lint at
300/// `<expr_1>` using [`span_lint`], then allowing the lint at `<expr_1>` as attempted in the snippet
301/// will not work!
302/// Even though that is where the warning points at, which would be confusing to users.
303///
304/// Instead, use this function and also pass the `HirId` of `<expr_1>`, which will let
305/// the compiler check lint level attributes at the place of the expression and
306/// the `#[allow]` will work.
307#[track_caller]
308pub fn span_lint_hir_and_then(
309 cx: &LateContext<'_>,
310 lint: &'static Lint,
311 hir_id: HirId,
312 sp: impl Into<MultiSpan>,
313 msg: impl Into<DiagMessage>,
314 f: impl FnOnce(&mut Diag<'_, ()>),
315) {
316 #[expect(clippy::disallowed_methods)]
317 cx.tcx.node_span_lint(lint, hir_id, sp, |diag| {
318 diag.primary_message(msg);
319 f(diag);
320 docs_link(diag, lint);
321
322 #[cfg(debug_assertions)]
323 validate_diag(diag);
324 });
325}
326
327/// Add a span lint with a suggestion on how to fix it.
328///
329/// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
330/// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
331/// 2)"`.
332///
333/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
334///
335/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
336/// the lint level.
337/// For the `span_lint_and_sugg` function, the node that was passed into the `LintPass::check_*`
338/// function is used.
339///
340/// If you're emitting the lint at the span of a different node than the one provided by the
341/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
342/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
343/// highlighted in the displayed warning.
344///
345/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
346/// where you would expect it to.
347/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
348///
349/// # Example
350///
351/// ```text
352/// error: This `.fold` can be more succinctly expressed as `.any`
353/// --> tests/ui/methods.rs:390:13
354/// |
355/// 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2);
356/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
357/// |
358/// = note: `-D fold-any` implied by `-D warnings`
359/// ```
360#[track_caller]
361pub fn span_lint_and_sugg<T: LintContext>(
362 cx: &T,
363 lint: &'static Lint,
364 sp: Span,
365 msg: impl Into<DiagMessage>,
366 help: impl Into<DiagMessage>,
367 sugg: String,
368 applicability: Applicability,
369) {
370 span_lint_and_then(cx, lint, sp, msg.into(), |diag| {
371 diag.span_suggestion(sp, help.into(), sugg, applicability);
372
373 // This dummy construct is here to prevent the internal `clippy::collapsible_span_lint_calls`
374 // lint from triggering. We don't want to allow/expect it as internal lints might or might
375 // not be activated when linting, and we don't want an unknown lint warning either.
376 std::hint::black_box(());
377 });
378}