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