]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/utils/diagnostics.rs
Rollup merge of #81588 - xfix:delete-doc-alias, r=Mark-Simulacrum
[rust.git] / src / tools / clippy / clippy_lints / src / utils / diagnostics.rs
1 //! Clippy wrappers around rustc's diagnostic functions.
2
3 use rustc_errors::{Applicability, DiagnosticBuilder};
4 use rustc_hir::HirId;
5 use rustc_lint::{LateContext, Lint, LintContext};
6 use rustc_span::source_map::{MultiSpan, Span};
7 use std::env;
8
9 fn docs_link(diag: &mut DiagnosticBuilder<'_>, lint: &'static Lint) {
10     if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
11         diag.help(&format!(
12             "for further information visit https://rust-lang.github.io/rust-clippy/{}/index.html#{}",
13             &option_env!("RUST_RELEASE_NUM").map_or("master".to_string(), |n| {
14                 // extract just major + minor version and ignore patch versions
15                 format!("rust-{}", n.rsplitn(2, '.').nth(1).unwrap())
16             }),
17             lint.name_lower().replacen("clippy::", "", 1)
18         ));
19     }
20 }
21
22 /// Emit a basic lint message with a `msg` and a `span`.
23 ///
24 /// This is the most primitive of our lint emission methods and can
25 /// be a good way to get a new lint started.
26 ///
27 /// Usually it's nicer to provide more context for lint messages.
28 /// Be sure the output is understandable when you use this method.
29 ///
30 /// # Example
31 ///
32 /// ```ignore
33 /// error: usage of mem::forget on Drop type
34 ///   --> $DIR/mem_forget.rs:17:5
35 ///    |
36 /// 17 |     std::mem::forget(seven);
37 ///    |     ^^^^^^^^^^^^^^^^^^^^^^^
38 /// ```
39 pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: impl Into<MultiSpan>, msg: &str) {
40     cx.struct_span_lint(lint, sp, |diag| {
41         let mut diag = diag.build(msg);
42         docs_link(&mut diag, lint);
43         diag.emit();
44     });
45 }
46
47 /// Same as `span_lint` but with an extra `help` message.
48 ///
49 /// Use this if you want to provide some general help but
50 /// can't provide a specific machine applicable suggestion.
51 ///
52 /// The `help` message can be optionally attached to a `Span`.
53 ///
54 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
55 ///
56 /// # Example
57 ///
58 /// ```ignore
59 /// error: constant division of 0.0 with 0.0 will always result in NaN
60 ///   --> $DIR/zero_div_zero.rs:6:25
61 ///    |
62 /// 6  |     let other_f64_nan = 0.0f64 / 0.0;
63 ///    |                         ^^^^^^^^^^^^
64 ///    |
65 ///    = help: Consider using `f64::NAN` if you would like a constant representing NaN
66 /// ```
67 pub fn span_lint_and_help<'a, T: LintContext>(
68     cx: &'a T,
69     lint: &'static Lint,
70     span: Span,
71     msg: &str,
72     help_span: Option<Span>,
73     help: &str,
74 ) {
75     cx.struct_span_lint(lint, span, |diag| {
76         let mut diag = diag.build(msg);
77         if let Some(help_span) = help_span {
78             diag.span_help(help_span, help);
79         } else {
80             diag.help(help);
81         }
82         docs_link(&mut diag, lint);
83         diag.emit();
84     });
85 }
86
87 /// Like `span_lint` but with a `note` section instead of a `help` message.
88 ///
89 /// The `note` message is presented separately from the main lint message
90 /// and is attached to a specific span:
91 ///
92 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
93 ///
94 /// # Example
95 ///
96 /// ```ignore
97 /// error: calls to `std::mem::forget` with a reference instead of an owned value. Forgetting a reference does nothing.
98 ///   --> $DIR/drop_forget_ref.rs:10:5
99 ///    |
100 /// 10 |     forget(&SomeStruct);
101 ///    |     ^^^^^^^^^^^^^^^^^^^
102 ///    |
103 ///    = note: `-D clippy::forget-ref` implied by `-D warnings`
104 /// note: argument has type &SomeStruct
105 ///   --> $DIR/drop_forget_ref.rs:10:12
106 ///    |
107 /// 10 |     forget(&SomeStruct);
108 ///    |            ^^^^^^^^^^^
109 /// ```
110 pub fn span_lint_and_note<'a, T: LintContext>(
111     cx: &'a T,
112     lint: &'static Lint,
113     span: Span,
114     msg: &str,
115     note_span: Option<Span>,
116     note: &str,
117 ) {
118     cx.struct_span_lint(lint, span, |diag| {
119         let mut diag = diag.build(msg);
120         if let Some(note_span) = note_span {
121             diag.span_note(note_span, note);
122         } else {
123             diag.note(note);
124         }
125         docs_link(&mut diag, lint);
126         diag.emit();
127     });
128 }
129
130 /// Like `span_lint` but allows to add notes, help and suggestions using a closure.
131 ///
132 /// If you need to customize your lint output a lot, use this function.
133 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
134 pub fn span_lint_and_then<'a, T: LintContext, F>(cx: &'a T, lint: &'static Lint, sp: Span, msg: &str, f: F)
135 where
136     F: for<'b> FnOnce(&mut DiagnosticBuilder<'b>),
137 {
138     cx.struct_span_lint(lint, sp, |diag| {
139         let mut diag = diag.build(msg);
140         f(&mut diag);
141         docs_link(&mut diag, lint);
142         diag.emit();
143     });
144 }
145
146 pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, sp: Span, msg: &str) {
147     cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |diag| {
148         let mut diag = diag.build(msg);
149         docs_link(&mut diag, lint);
150         diag.emit();
151     });
152 }
153
154 pub fn span_lint_hir_and_then(
155     cx: &LateContext<'_>,
156     lint: &'static Lint,
157     hir_id: HirId,
158     sp: Span,
159     msg: &str,
160     f: impl FnOnce(&mut DiagnosticBuilder<'_>),
161 ) {
162     cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |diag| {
163         let mut diag = diag.build(msg);
164         f(&mut diag);
165         docs_link(&mut diag, lint);
166         diag.emit();
167     });
168 }
169
170 /// Add a span lint with a suggestion on how to fix it.
171 ///
172 /// These suggestions can be parsed by rustfix to allow it to automatically fix your code.
173 /// In the example below, `help` is `"try"` and `sugg` is the suggested replacement `".any(|x| x >
174 /// 2)"`.
175 ///
176 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
177 ///
178 /// # Example
179 ///
180 /// ```ignore
181 /// error: This `.fold` can be more succinctly expressed as `.any`
182 /// --> $DIR/methods.rs:390:13
183 ///     |
184 /// 390 |     let _ = (0..3).fold(false, |acc, x| acc || x > 2);
185 ///     |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
186 ///     |
187 ///     = note: `-D fold-any` implied by `-D warnings`
188 /// ```
189 #[cfg_attr(feature = "internal-lints", allow(clippy::collapsible_span_lint_calls))]
190 pub fn span_lint_and_sugg<'a, T: LintContext>(
191     cx: &'a T,
192     lint: &'static Lint,
193     sp: Span,
194     msg: &str,
195     help: &str,
196     sugg: String,
197     applicability: Applicability,
198 ) {
199     span_lint_and_then(cx, lint, sp, msg, |diag| {
200         diag.span_suggestion(sp, help, sugg, applicability);
201     });
202 }
203
204 /// Create a suggestion made from several `span → replacement`.
205 ///
206 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
207 /// appear once per
208 /// replacement. In human-readable format though, it only appears once before
209 /// the whole suggestion.
210 pub fn multispan_sugg<I>(diag: &mut DiagnosticBuilder<'_>, help_msg: &str, sugg: I)
211 where
212     I: IntoIterator<Item = (Span, String)>,
213 {
214     multispan_sugg_with_applicability(diag, help_msg, Applicability::Unspecified, sugg)
215 }
216
217 pub fn multispan_sugg_with_applicability<I>(
218     diag: &mut DiagnosticBuilder<'_>,
219     help_msg: &str,
220     applicability: Applicability,
221     sugg: I,
222 ) where
223     I: IntoIterator<Item = (Span, String)>,
224 {
225     diag.multipart_suggestion(help_msg, sugg.into_iter().collect(), applicability);
226 }