Skip to main content

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