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