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, SubdiagMessage};
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    #[expect(clippy::disallowed_methods)]
108    cx.span_lint(lint, sp, |diag| {
109        diag.primary_message(msg);
110        docs_link(diag, lint);
111
112        #[cfg(debug_assertions)]
113        validate_diag(diag);
114    });
115}
116
117/// Same as [`span_lint`] but with an extra `help` message.
118///
119/// Use this if you want to provide some general help but
120/// can't provide a specific machine applicable suggestion.
121///
122/// The `help` message can be optionally attached to a `Span`.
123///
124/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
125///
126/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
127/// the lint level.
128/// For the `span_lint_and_help` function, the node that was passed into the `LintPass::check_*`
129/// function is used.
130///
131/// If you're emitting the lint at the span of a different node than the one provided by the
132/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
133/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
134/// highlighted in the displayed warning.
135///
136/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
137/// where you would expect it to.
138/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
139///
140/// # Example
141///
142/// ```text
143/// error: constant division of 0.0 with 0.0 will always result in NaN
144///   --> tests/ui/zero_div_zero.rs:6:25
145///    |
146/// 6  |     let other_f64_nan = 0.0f64 / 0.0;
147///    |                         ^^^^^^^^^^^^
148///    |
149///    = help: consider using `f64::NAN` if you would like a constant representing NaN
150/// ```
151#[track_caller]
152pub fn span_lint_and_help<T: LintContext>(
153    cx: &T,
154    lint: &'static Lint,
155    span: impl Into<MultiSpan>,
156    msg: impl Into<DiagMessage>,
157    help_span: Option<Span>,
158    help: impl Into<SubdiagMessage>,
159) {
160    #[expect(clippy::disallowed_methods)]
161    cx.span_lint(lint, span, |diag| {
162        diag.primary_message(msg);
163        if let Some(help_span) = help_span {
164            diag.span_help(help_span, help.into());
165        } else {
166            diag.help(help.into());
167        }
168        docs_link(diag, lint);
169
170        #[cfg(debug_assertions)]
171        validate_diag(diag);
172    });
173}
174
175/// Like [`span_lint`] but with a `note` section instead of a `help` message.
176///
177/// The `note` message is presented separately from the main lint message
178/// and is attached to a specific span:
179///
180/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
181///
182/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
183/// the lint level.
184/// For the `span_lint_and_note` function, the node that was passed into the `LintPass::check_*`
185/// function is used.
186///
187/// If you're emitting the lint at the span of a different node than the one provided by the
188/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
189/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
190/// highlighted in the displayed warning.
191///
192/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
193/// where you would expect it to.
194/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
195///
196/// # Example
197///
198/// ```text
199/// error: calls to `std::mem::forget` with a reference instead of an owned value. Forgetting a reference does nothing.
200///   --> tests/ui/drop_forget_ref.rs:10:5
201///    |
202/// 10 |     forget(&SomeStruct);
203///    |     ^^^^^^^^^^^^^^^^^^^
204///    |
205///    = note: `-D clippy::forget-ref` implied by `-D warnings`
206/// note: argument has type &SomeStruct
207///   --> tests/ui/drop_forget_ref.rs:10:12
208///    |
209/// 10 |     forget(&SomeStruct);
210///    |            ^^^^^^^^^^^
211/// ```
212#[track_caller]
213pub fn span_lint_and_note<T: LintContext>(
214    cx: &T,
215    lint: &'static Lint,
216    span: impl Into<MultiSpan>,
217    msg: impl Into<DiagMessage>,
218    note_span: Option<Span>,
219    note: impl Into<SubdiagMessage>,
220) {
221    #[expect(clippy::disallowed_methods)]
222    cx.span_lint(lint, span, |diag| {
223        diag.primary_message(msg);
224        if let Some(note_span) = note_span {
225            diag.span_note(note_span, note.into());
226        } else {
227            diag.note(note.into());
228        }
229        docs_link(diag, lint);
230
231        #[cfg(debug_assertions)]
232        validate_diag(diag);
233    });
234}
235
236/// Like [`span_lint`] but allows to add notes, help and suggestions using a closure.
237///
238/// If you need to customize your lint output a lot, use this function.
239/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
240///
241/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
242/// the lint level.
243/// For the `span_lint_and_then` function, the node that was passed into the `LintPass::check_*`
244/// function is used.
245///
246/// If you're emitting the lint at the span of a different node than the one provided by the
247/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
248/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
249/// highlighted in the displayed warning.
250///
251/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
252/// where you would expect it to.
253/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
254#[track_caller]
255pub fn span_lint_and_then<C, S, M, F>(cx: &C, lint: &'static Lint, sp: S, msg: M, f: F)
256where
257    C: LintContext,
258    S: Into<MultiSpan>,
259    M: Into<DiagMessage>,
260    F: FnOnce(&mut Diag<'_, ()>),
261{
262    #[expect(clippy::disallowed_methods)]
263    cx.span_lint(lint, sp, |diag| {
264        diag.primary_message(msg);
265        f(diag);
266        docs_link(diag, lint);
267
268        #[cfg(debug_assertions)]
269        validate_diag(diag);
270    });
271}
272
273/// Like [`span_lint`], but emits the lint at the node identified by the given `HirId`.
274///
275/// This is in contrast to [`span_lint`], which always emits the lint at the node that was last
276/// passed to the `LintPass::check_*` function.
277///
278/// The `HirId` is used for checking lint level attributes and to fulfill lint expectations defined
279/// via the `#[expect]` attribute.
280///
281/// For example:
282/// ```ignore
283/// fn f() { /* <node_1> */
284///
285///     #[allow(clippy::some_lint)]
286///     let _x = /* <expr_1> */;
287/// }
288/// ```
289/// If `some_lint` does its analysis in `LintPass::check_fn` (at `<node_1>`) and emits a lint at
290/// `<expr_1>` using [`span_lint`], then allowing the lint at `<expr_1>` as attempted in the snippet
291/// will not work!
292/// Even though that is where the warning points at, which would be confusing to users.
293///
294/// Instead, use this function and also pass the `HirId` of `<expr_1>`, which will let
295/// the compiler check lint level attributes at the place of the expression and
296/// the `#[allow]` will work.
297#[track_caller]
298pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, sp: Span, msg: impl Into<DiagMessage>) {
299    #[expect(clippy::disallowed_methods)]
300    cx.tcx.node_span_lint(lint, hir_id, sp, |diag| {
301        diag.primary_message(msg);
302        docs_link(diag, lint);
303
304        #[cfg(debug_assertions)]
305        validate_diag(diag);
306    });
307}
308
309/// Like [`span_lint_and_then`], but emits the lint at the node identified by the given `HirId`.
310///
311/// This is in contrast to [`span_lint_and_then`], which always emits the lint at the node that was
312/// last passed to the `LintPass::check_*` function.
313///
314/// The `HirId` is used for checking lint level attributes and to fulfill lint expectations defined
315/// via the `#[expect]` attribute.
316///
317/// For example:
318/// ```ignore
319/// fn f() { /* <node_1> */
320///
321///     #[allow(clippy::some_lint)]
322///     let _x = /* <expr_1> */;
323/// }
324/// ```
325/// If `some_lint` does its analysis in `LintPass::check_fn` (at `<node_1>`) and emits a lint at
326/// `<expr_1>` using [`span_lint`], then allowing the lint at `<expr_1>` as attempted in the snippet
327/// will not work!
328/// Even though that is where the warning points at, which would be confusing to users.
329///
330/// Instead, use this function and also pass the `HirId` of `<expr_1>`, which will let
331/// the compiler check lint level attributes at the place of the expression and
332/// the `#[allow]` will work.
333#[track_caller]
334pub fn span_lint_hir_and_then(
335    cx: &LateContext<'_>,
336    lint: &'static Lint,
337    hir_id: HirId,
338    sp: impl Into<MultiSpan>,
339    msg: impl Into<DiagMessage>,
340    f: impl FnOnce(&mut Diag<'_, ()>),
341) {
342    #[expect(clippy::disallowed_methods)]
343    cx.tcx.node_span_lint(lint, hir_id, sp, |diag| {
344        diag.primary_message(msg);
345        f(diag);
346        docs_link(diag, lint);
347
348        #[cfg(debug_assertions)]
349        validate_diag(diag);
350    });
351}
352
353/// Add a span lint with a suggestion on how to fix it.
354///
355/// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
356/// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
357/// 2)"`.
358///
359/// If you change the signature, remember to update the internal lint `CollapsibleCalls`
360///
361/// NOTE: Lint emissions are always bound to a node in the HIR, which is used to determine
362/// the lint level.
363/// For the `span_lint_and_sugg` function, the node that was passed into the `LintPass::check_*`
364/// function is used.
365///
366/// If you're emitting the lint at the span of a different node than the one provided by the
367/// `LintPass::check_*` function, consider using [`span_lint_hir_and_then`] instead.
368/// This is needed for `#[allow]` and `#[expect]` attributes to work on the node
369/// highlighted in the displayed warning.
370///
371/// If you're unsure which function you should use, you can test if the `#[expect]` attribute works
372/// where you would expect it to.
373/// If it doesn't, you likely need to use [`span_lint_hir_and_then`] instead.
374///
375/// # Example
376///
377/// ```text
378/// error: This `.fold` can be more succinctly expressed as `.any`
379/// --> tests/ui/methods.rs:390:13
380///     |
381/// 390 |     let _ = (0..3).fold(false, |acc, x| acc || x > 2);
382///     |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
383///     |
384///     = note: `-D fold-any` implied by `-D warnings`
385/// ```
386#[cfg_attr(not(debug_assertions), expect(clippy::collapsible_span_lint_calls))]
387#[track_caller]
388pub fn span_lint_and_sugg<T: LintContext>(
389    cx: &T,
390    lint: &'static Lint,
391    sp: Span,
392    msg: impl Into<DiagMessage>,
393    help: impl Into<SubdiagMessage>,
394    sugg: String,
395    applicability: Applicability,
396) {
397    span_lint_and_then(cx, lint, sp, msg.into(), |diag| {
398        diag.span_suggestion(sp, help.into(), sugg, applicability);
399
400        #[cfg(debug_assertions)]
401        validate_diag(diag);
402    });
403}