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