1 //! Clippy wrappers around rustc's diagnostic functions.
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
9 //! ~The `INTERNAL_METADATA_COLLECTOR` lint
11 use rustc_errors::{emitter::MAX_SUGGESTION_HIGHLIGHT_LINES, Applicability, Diagnostic};
13 use rustc_lint::{LateContext, Lint, LintContext};
14 use rustc_span::source_map::{MultiSpan, Span};
17 fn docs_link(diag: &mut Diagnostic, lint: &'static Lint) {
18 if env::var("CLIPPY_DISABLE_DOCS_LINKS").is_err() {
19 if let Some(lint) = lint.name_lower().strip_prefix("clippy::") {
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.rsplit_once('.').unwrap().1)
32 /// Emit a basic lint message with a `msg` and a `span`.
34 /// This is the most primitive of our lint emission methods and can
35 /// be a good way to get a new lint started.
37 /// Usually it's nicer to provide more context for lint messages.
38 /// Be sure the output is understandable when you use this method.
43 /// error: usage of mem::forget on Drop type
44 /// --> $DIR/mem_forget.rs:17:5
46 /// 17 | std::mem::forget(seven);
47 /// | ^^^^^^^^^^^^^^^^^^^^^^^
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);
57 /// Same as `span_lint` but with an extra `help` message.
59 /// Use this if you want to provide some general help but
60 /// can't provide a specific machine applicable suggestion.
62 /// The `help` message can be optionally attached to a `Span`.
64 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
69 /// error: constant division of 0.0 with 0.0 will always result in NaN
70 /// --> $DIR/zero_div_zero.rs:6:25
72 /// 6 | let other_f64_nan = 0.0f64 / 0.0;
75 /// = help: consider using `f64::NAN` if you would like a constant representing NaN
77 pub fn span_lint_and_help<'a, T: LintContext>(
82 help_span: Option<Span>,
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);
92 docs_link(&mut diag, lint);
97 /// Like `span_lint` but with a `note` section instead of a `help` message.
99 /// The `note` message is presented separately from the main lint message
100 /// and is attached to a specific span:
102 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
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
110 /// 10 | forget(&SomeStruct);
111 /// | ^^^^^^^^^^^^^^^^^^^
113 /// = note: `-D clippy::forget-ref` implied by `-D warnings`
114 /// note: argument has type &SomeStruct
115 /// --> $DIR/drop_forget_ref.rs:10:12
117 /// 10 | forget(&SomeStruct);
120 pub fn span_lint_and_note<'a, T: LintContext>(
123 span: impl Into<MultiSpan>,
125 note_span: Option<Span>,
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);
135 docs_link(&mut diag, lint);
140 /// Like `span_lint` but allows to add notes, help and suggestions using a closure.
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)
148 F: FnOnce(&mut Diagnostic),
150 cx.struct_span_lint(lint, sp, |diag| {
151 let mut diag = diag.build(msg);
153 docs_link(&mut diag, lint);
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);
166 pub fn span_lint_hir_and_then(
167 cx: &LateContext<'_>,
170 sp: impl Into<MultiSpan>,
172 f: impl FnOnce(&mut Diagnostic),
174 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |diag| {
175 let mut diag = diag.build(msg);
177 docs_link(&mut diag, lint);
182 /// Add a span lint with a suggestion on how to fix it.
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 >
188 /// If you change the signature, remember to update the internal lint `CollapsibleCalls`
193 /// error: This `.fold` can be more succinctly expressed as `.any`
194 /// --> $DIR/methods.rs:390:13
196 /// 390 | let _ = (0..3).fold(false, |acc, x| acc || x > 2);
197 /// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `.any(|x| x > 2)`
199 /// = note: `-D fold-any` implied by `-D warnings`
201 #[cfg_attr(feature = "internal", allow(clippy::collapsible_span_lint_calls))]
202 pub fn span_lint_and_sugg<'a, T: LintContext>(
209 applicability: Applicability,
211 span_lint_and_then(cx, lint, sp, msg, |diag| {
212 diag.span_suggestion(sp, help, sugg, applicability);
216 /// Like [`span_lint_and_sugg`] with a focus on the edges. The output will either
217 /// emit single span or multispan suggestion depending on the number of its lines.
219 /// If the given suggestion string has more lines than the maximum display length defined by
220 /// [`MAX_SUGGESTION_HIGHLIGHT_LINES`][`rustc_errors::emitter::MAX_SUGGESTION_HIGHLIGHT_LINES`],
221 /// this function will split the suggestion and span to showcase the change for the top and
222 /// bottom edge of the code. For normal suggestions, in one display window, the help message
223 /// will be combined with a colon.
225 /// Multipart suggestions like the one being created here currently cannot be
226 /// applied by rustfix (See [rustfix#141](https://github.com/rust-lang/rustfix/issues/141)).
227 /// Testing rustfix with this lint emission function might require a file with
228 /// suggestions that can be fixed and those that can't. See
229 /// [clippy#8520](https://github.com/rust-lang/rust-clippy/pull/8520/files) for
230 /// an example and of this.
232 /// # Example for a long suggestion
235 /// error: called `map(..).flatten()` on `Option`
236 /// --> $DIR/map_flatten.rs:8:10
240 /// LL | | if x <= 5 {
245 /// LL | | .flatten();
246 /// | |__________________^
248 /// = note: `-D clippy::map-flatten` implied by `-D warnings`
249 /// help: try replacing `map` with `and_then`
251 /// LL ~ .and_then(|x| {
255 /// help: and remove the `.flatten()`
262 pub fn span_lint_and_sugg_for_edges(
263 cx: &LateContext<'_>,
269 applicability: Applicability,
271 span_lint_and_then(cx, lint, sp, msg, |diag| {
272 let sugg_lines_count = sugg.lines().count();
273 if sugg_lines_count > MAX_SUGGESTION_HIGHLIGHT_LINES {
274 let sm = cx.sess().source_map();
275 if let (Ok(line_upper), Ok(line_bottom)) = (sm.lookup_line(sp.lo()), sm.lookup_line(sp.hi())) {
276 let split_idx = MAX_SUGGESTION_HIGHLIGHT_LINES / 2;
277 let span_upper = sm.span_until_char(sp.with_hi(line_upper.sf.lines[line_upper.line + split_idx]), '\n');
278 let span_bottom = sp.with_lo(line_bottom.sf.lines[line_bottom.line - split_idx]);
280 let sugg_lines_vec = sugg.lines().collect::<Vec<&str>>();
281 let sugg_upper = sugg_lines_vec[..split_idx].join("\n");
282 let sugg_bottom = sugg_lines_vec[sugg_lines_count - split_idx..].join("\n");
284 diag.span_suggestion(span_upper, helps[0], sugg_upper, applicability);
285 diag.span_suggestion(span_bottom, helps[1], sugg_bottom, applicability);
290 diag.span_suggestion_with_style(
295 rustc_errors::SuggestionStyle::ShowAlways,
300 /// Create a suggestion made from several `span → replacement`.
302 /// Note: in the JSON format (used by `compiletest_rs`), the help message will
304 /// replacement. In human-readable format though, it only appears once before
305 /// the whole suggestion.
306 pub fn multispan_sugg<I>(diag: &mut Diagnostic, help_msg: &str, sugg: I)
308 I: IntoIterator<Item = (Span, String)>,
310 multispan_sugg_with_applicability(diag, help_msg, Applicability::Unspecified, sugg);
313 /// Create a suggestion made from several `span → replacement`.
315 /// rustfix currently doesn't support the automatic application of suggestions with
316 /// multiple spans. This is tracked in issue [rustfix#141](https://github.com/rust-lang/rustfix/issues/141).
317 /// Suggestions with multiple spans will be silently ignored.
318 pub fn multispan_sugg_with_applicability<I>(
319 diag: &mut Diagnostic,
321 applicability: Applicability,
324 I: IntoIterator<Item = (Span, String)>,
326 diag.multipart_suggestion(help_msg, sugg.into_iter().collect(), applicability);