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