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