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, Diagnostic, DiagCtxtHandle, DiagMessage, Level, 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 struct ClippyDiag<F: FnOnce(&mut Diag<'_, ()>)>(F);
244
245 impl<'a, F: FnOnce(&mut Diag<'_, ()>)> Diagnostic<'a, ()> for ClippyDiag<F> {
246 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
247 let mut lint = Diag::new(dcx, level, "");
248 (self.0)(&mut lint);
249 lint
250 }
251 }
252
253 let sp = sp.into();
254 #[expect(clippy::disallowed_methods)]
255 cx.emit_span_lint(lint, sp.clone(), ClippyDiag(|diag: &mut Diag<'_, ()>| {
256 diag.primary_message(msg);
257 diag.span(sp);
258 f(diag);
259 docs_link(diag, lint);
260
261 #[cfg(debug_assertions)]
262 validate_diag(diag);
263 }));
264}
265
266/// Like [`span_lint`], but emits the lint at the node identified by the given `HirId`.
267///
268/// This is in contrast to [`span_lint`], which always emits the lint at the node that was last
269/// passed to the `LintPass::check_*` function.
270///
271/// The `HirId` is used for checking lint level attributes and to fulfill lint expectations defined
272/// via the `#[expect]` attribute.
273///
274/// For example:
275/// ```ignore
276/// fn f() { /* <node_1> */
277///
278/// #[allow(clippy::some_lint)]
279/// let _x = /* <expr_1> */;
280/// }
281/// ```
282/// If `some_lint` does its analysis in `LintPass::check_fn` (at `<node_1>`) and emits a lint at
283/// `<expr_1>` using [`span_lint`], then allowing the lint at `<expr_1>` as attempted in the snippet
284/// will not work!
285/// Even though that is where the warning points at, which would be confusing to users.
286///
287/// Instead, use this function and also pass the `HirId` of `<expr_1>`, which will let
288/// the compiler check lint level attributes at the place of the expression and
289/// the `#[allow]` will work.
290#[track_caller]
291pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, sp: Span, msg: impl Into<DiagMessage>) {
292 span_lint_hir_and_then(cx, lint, hir_id, sp, msg, |_| {});
293}
294
295/// Like [`span_lint_and_then`], but emits the lint at the node identified by the given `HirId`.
296///
297/// This is in contrast to [`span_lint_and_then`], which always emits the lint at the node that was
298/// last passed to the `LintPass::check_*` function.
299///
300/// The `HirId` is used for checking lint level attributes and to fulfill lint expectations defined
301/// via the `#[expect]` attribute.
302///
303/// For example:
304/// ```ignore
305/// fn f() { /* <node_1> */
306///
307/// #[allow(clippy::some_lint)]
308/// let _x = /* <expr_1> */;
309/// }
310/// ```
311/// If `some_lint` does its analysis in `LintPass::check_fn` (at `<node_1>`) and emits a lint at
312/// `<expr_1>` using [`span_lint`], then allowing the lint at `<expr_1>` as attempted in the snippet
313/// will not work!
314/// Even though that is where the warning points at, which would be confusing to users.
315///
316/// Instead, use this function and also pass the `HirId` of `<expr_1>`, which will let
317/// the compiler check lint level attributes at the place of the expression and
318/// the `#[allow]` will work.
319#[track_caller]
320pub fn span_lint_hir_and_then(
321 cx: &LateContext<'_>,
322 lint: &'static Lint,
323 hir_id: HirId,
324 sp: impl Into<MultiSpan>,
325 msg: impl Into<DiagMessage>,
326 f: impl FnOnce(&mut Diag<'_, ()>),
327) {
328 #[expect(clippy::disallowed_methods)]
329 cx.tcx.node_span_lint(lint, hir_id, sp, |diag| {
330 diag.primary_message(msg);
331 f(diag);
332 docs_link(diag, lint);
333
334 #[cfg(debug_assertions)]
335 validate_diag(diag);
336 });
337}
338
339/// Add a span lint with a suggestion on how to fix it.
340///
341/// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
342/// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
343/// 2)"`.
344///
345/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
346///
347/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
348/// the lint level.
349/// For the `span_lint_and_sugg` function, the node that was passed into the `LintPass::check_*`
350/// function is used.
351///
352/// If you're emitting the lint at the span of a different node than the one provided by the
353/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
354/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
355/// highlighted in the displayed warning.
356///
357/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
358/// where you would expect it to.
359/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
360///
361/// # Example
362///
363/// ```text
364/// error: This `.fold` can be more succinctly expressed as `.any`
365/// --> tests/ui/methods.rs:390:13
366/// |
367/// 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2);
368/// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
369/// |
370/// = note: `-D fold-any` implied by `-D warnings`
371/// ```
372#[track_caller]
373pub fn span_lint_and_sugg<T: LintContext>(
374 cx: &T,
375 lint: &'static Lint,
376 sp: Span,
377 msg: impl Into<DiagMessage>,
378 help: impl Into<DiagMessage>,
379 sugg: String,
380 applicability: Applicability,
381) {
382 span_lint_and_then(cx, lint, sp, msg.into(), |diag| {
383 diag.span_suggestion(sp, help.into(), sugg, applicability);
384
385 // This dummy construct is here to prevent the internal `clippy::collapsible_span_lint_calls`
386 // lint from triggering. We don't want to allow/expect it as internal lints might or might
387 // not be activated when linting, and we don't want an unknown lint warning either.
388 std::hint::black_box(());
389 });
390}