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