]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Auto merge of #4634 - m-ober:feature/2320-map-or, r=llogiq
[rust.git] / clippy_lints / src / doc.rs
1 use crate::utils::{match_type, paths, return_ty, span_lint};
2 use itertools::Itertools;
3 use rustc::hir;
4 use rustc::impl_lint_pass;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_session::declare_tool_lint;
8 use std::ops::Range;
9 use syntax::ast::{AttrKind, Attribute};
10 use syntax::source_map::{BytePos, MultiSpan, Span};
11 use syntax_pos::Pos;
12 use url::Url;
13
14 declare_clippy_lint! {
15     /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
16     /// outside ticks in documentation.
17     ///
18     /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
19     /// camel-case probably indicates some code which should be included between
20     /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
21     /// consider that.
22     ///
23     /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
24     /// for is limited, and there are still false positives.
25     ///
26     /// **Examples:**
27     /// ```rust
28     /// /// Do something with the foo_bar parameter. See also
29     /// /// that::other::module::foo.
30     /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
31     /// fn doit(foo_bar: usize) {}
32     /// ```
33     pub DOC_MARKDOWN,
34     pedantic,
35     "presence of `_`, `::` or camel-case outside backticks in documentation"
36 }
37
38 declare_clippy_lint! {
39     /// **What it does:** Checks for the doc comments of publicly visible
40     /// unsafe functions and warns if there is no `# Safety` section.
41     ///
42     /// **Why is this bad?** Unsafe functions should document their safety
43     /// preconditions, so that users can be sure they are using them safely.
44     ///
45     /// **Known problems:** None.
46     ///
47     /// **Examples:**
48     /// ```rust
49     ///# type Universe = ();
50     /// /// This function should really be documented
51     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
52     ///     unimplemented!();
53     /// }
54     /// ```
55     ///
56     /// At least write a line about safety:
57     ///
58     /// ```rust
59     ///# type Universe = ();
60     /// /// # Safety
61     /// ///
62     /// /// This function should not be called before the horsemen are ready.
63     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
64     ///     unimplemented!();
65     /// }
66     /// ```
67     pub MISSING_SAFETY_DOC,
68     style,
69     "`pub unsafe fn` without `# Safety` docs"
70 }
71
72 declare_clippy_lint! {
73     /// **What it does:** Checks the doc comments of publicly visible functions that
74     /// return a `Result` type and warns if there is no `# Errors` section.
75     ///
76     /// **Why is this bad?** Documenting the type of errors that can be returned from a
77     /// function can help callers write code to handle the errors appropriately.
78     ///
79     /// **Known problems:** None.
80     ///
81     /// **Examples:**
82     ///
83     /// Since the following function returns a `Result` it has an `# Errors` section in
84     /// its doc comment:
85     ///
86     /// ```rust
87     ///# use std::io;
88     /// /// # Errors
89     /// ///
90     /// /// Will return `Err` if `filename` does not exist or the user does not have
91     /// /// permission to read it.
92     /// pub fn read(filename: String) -> io::Result<String> {
93     ///     unimplemented!();
94     /// }
95     /// ```
96     pub MISSING_ERRORS_DOC,
97     pedantic,
98     "`pub fn` returns `Result` without `# Errors` in doc comment"
99 }
100
101 declare_clippy_lint! {
102     /// **What it does:** Checks for `fn main() { .. }` in doctests
103     ///
104     /// **Why is this bad?** The test can be shorter (and likely more readable)
105     /// if the `fn main()` is left implicit.
106     ///
107     /// **Known problems:** None.
108     ///
109     /// **Examples:**
110     /// ``````rust
111     /// /// An example of a doctest with a `main()` function
112     /// ///
113     /// /// # Examples
114     /// ///
115     /// /// ```
116     /// /// fn main() {
117     /// ///     // this needs not be in an `fn`
118     /// /// }
119     /// /// ```
120     /// fn needless_main() {
121     ///     unimplemented!();
122     /// }
123     /// ``````
124     pub NEEDLESS_DOCTEST_MAIN,
125     style,
126     "presence of `fn main() {` in code examples"
127 }
128
129 #[allow(clippy::module_name_repetitions)]
130 #[derive(Clone)]
131 pub struct DocMarkdown {
132     valid_idents: FxHashSet<String>,
133     in_trait_impl: bool,
134 }
135
136 impl DocMarkdown {
137     pub fn new(valid_idents: FxHashSet<String>) -> Self {
138         Self {
139             valid_idents,
140             in_trait_impl: false,
141         }
142     }
143 }
144
145 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
146
147 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown {
148     fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate<'_>) {
149         check_attrs(cx, &self.valid_idents, &krate.attrs);
150     }
151
152     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
153         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
154         match item.kind {
155             hir::ItemKind::Fn(ref sig, ..) => {
156                 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
157             },
158             hir::ItemKind::Impl(_, _, _, _, ref trait_ref, ..) => {
159                 self.in_trait_impl = trait_ref.is_some();
160             },
161             _ => {},
162         }
163     }
164
165     fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
166         if let hir::ItemKind::Impl(..) = item.kind {
167             self.in_trait_impl = false;
168         }
169     }
170
171     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
172         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
173         if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
174             lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
175         }
176     }
177
178     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
179         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
180         if self.in_trait_impl {
181             return;
182         }
183         if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
184             lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
185         }
186     }
187 }
188
189 fn lint_for_missing_headers<'a, 'tcx>(
190     cx: &LateContext<'a, 'tcx>,
191     hir_id: hir::HirId,
192     span: impl Into<MultiSpan> + Copy,
193     sig: &hir::FnSig<'_>,
194     headers: DocHeaders,
195 ) {
196     if !cx.access_levels.is_exported(hir_id) {
197         return; // Private functions do not require doc comments
198     }
199     if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
200         span_lint(
201             cx,
202             MISSING_SAFETY_DOC,
203             span,
204             "unsafe function's docs miss `# Safety` section",
205         );
206     }
207     if !headers.errors && match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
208         span_lint(
209             cx,
210             MISSING_ERRORS_DOC,
211             span,
212             "docs for function returning `Result` missing `# Errors` section",
213         );
214     }
215 }
216
217 /// Cleanup documentation decoration (`///` and such).
218 ///
219 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
220 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
221 /// need to keep track of
222 /// the spans but this function is inspired from the later.
223 #[allow(clippy::cast_possible_truncation)]
224 #[must_use]
225 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
226     // one-line comments lose their prefix
227     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
228     for prefix in ONELINERS {
229         if comment.starts_with(*prefix) {
230             let doc = &comment[prefix.len()..];
231             let mut doc = doc.to_owned();
232             doc.push('\n');
233             return (
234                 doc.to_owned(),
235                 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
236             );
237         }
238     }
239
240     if comment.starts_with("/*") {
241         let doc = &comment[3..comment.len() - 2];
242         let mut sizes = vec![];
243         let mut contains_initial_stars = false;
244         for line in doc.lines() {
245             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
246             debug_assert_eq!(offset as u32 as usize, offset);
247             contains_initial_stars |= line.trim_start().starts_with('*');
248             // +1 for the newline
249             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
250         }
251         if !contains_initial_stars {
252             return (doc.to_string(), sizes);
253         }
254         // remove the initial '*'s if any
255         let mut no_stars = String::with_capacity(doc.len());
256         for line in doc.lines() {
257             let mut chars = line.chars();
258             while let Some(c) = chars.next() {
259                 if c.is_whitespace() {
260                     no_stars.push(c);
261                 } else {
262                     no_stars.push(if c == '*' { ' ' } else { c });
263                     break;
264                 }
265             }
266             no_stars.push_str(chars.as_str());
267             no_stars.push('\n');
268         }
269         return (no_stars, sizes);
270     }
271
272     panic!("not a doc-comment: {}", comment);
273 }
274
275 #[derive(Copy, Clone)]
276 struct DocHeaders {
277     safety: bool,
278     errors: bool,
279 }
280
281 fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
282     let mut doc = String::new();
283     let mut spans = vec![];
284
285     for attr in attrs {
286         if let AttrKind::DocComment(ref comment) = attr.kind {
287             let comment = comment.to_string();
288             let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
289             spans.extend_from_slice(&current_spans);
290             doc.push_str(&comment);
291         } else if attr.check_name(sym!(doc)) {
292             // ignore mix of sugared and non-sugared doc
293             // don't trigger the safety or errors check
294             return DocHeaders {
295                 safety: true,
296                 errors: true,
297             };
298         }
299     }
300
301     let mut current = 0;
302     for &mut (ref mut offset, _) in &mut spans {
303         let offset_copy = *offset;
304         *offset = current;
305         current += offset_copy;
306     }
307
308     if doc.is_empty() {
309         return DocHeaders {
310             safety: false,
311             errors: false,
312         };
313     }
314
315     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
316     // Iterate over all `Events` and combine consecutive events into one
317     let events = parser.coalesce(|previous, current| {
318         use pulldown_cmark::Event::*;
319
320         let previous_range = previous.1;
321         let current_range = current.1;
322
323         match (previous.0, current.0) {
324             (Text(previous), Text(current)) => {
325                 let mut previous = previous.to_string();
326                 previous.push_str(&current);
327                 Ok((Text(previous.into()), previous_range))
328             },
329             (previous, current) => Err(((previous, previous_range), (current, current_range))),
330         }
331     });
332     check_doc(cx, valid_idents, events, &spans)
333 }
334
335 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
336     cx: &LateContext<'_, '_>,
337     valid_idents: &FxHashSet<String>,
338     events: Events,
339     spans: &[(usize, Span)],
340 ) -> DocHeaders {
341     // true if a safety header was found
342     use pulldown_cmark::Event::*;
343     use pulldown_cmark::Tag::*;
344
345     let mut headers = DocHeaders {
346         safety: false,
347         errors: false,
348     };
349     let mut in_code = false;
350     let mut in_link = None;
351     let mut in_heading = false;
352
353     for (event, range) in events {
354         match event {
355             Start(CodeBlock(_)) => in_code = true,
356             End(CodeBlock(_)) => in_code = false,
357             Start(Link(_, url, _)) => in_link = Some(url),
358             End(Link(..)) => in_link = None,
359             Start(Heading(_)) => in_heading = true,
360             End(Heading(_)) => in_heading = false,
361             Start(_tag) | End(_tag) => (), // We don't care about other tags
362             Html(_html) => (),             // HTML is weird, just ignore it
363             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
364             FootnoteReference(text) | Text(text) => {
365                 if Some(&text) == in_link.as_ref() {
366                     // Probably a link of the form `<http://example.com>`
367                     // Which are represented as a link to "http://example.com" with
368                     // text "http://example.com" by pulldown-cmark
369                     continue;
370                 }
371                 headers.safety |= in_heading && text.trim() == "Safety";
372                 headers.errors |= in_heading && text.trim() == "Errors";
373                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
374                     Ok(o) => o,
375                     Err(e) => e - 1,
376                 };
377                 let (begin, span) = spans[index];
378                 if in_code {
379                     check_code(cx, &text, span);
380                 } else {
381                     // Adjust for the beginning of the current `Event`
382                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
383
384                     check_text(cx, valid_idents, &text, span);
385                 }
386             },
387         }
388     }
389     headers
390 }
391
392 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
393
394 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
395     if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
396         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
397     }
398 }
399
400 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
401     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
402         // Trim punctuation as in `some comment (see foo::bar).`
403         //                                                   ^^
404         // Or even as in `_foo bar_` which is emphasized.
405         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
406
407         if valid_idents.contains(word) {
408             continue;
409         }
410
411         // Adjust for the current word
412         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
413         let span = Span::new(
414             span.lo() + BytePos::from_usize(offset),
415             span.lo() + BytePos::from_usize(offset + word.len()),
416             span.ctxt(),
417         );
418
419         check_word(cx, word, span);
420     }
421 }
422
423 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
424     /// Checks if a string is camel-case, i.e., contains at least two uppercase
425     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
426     /// Plurals are also excluded (`IDs` is ok).
427     fn is_camel_case(s: &str) -> bool {
428         if s.starts_with(|c: char| c.is_digit(10)) {
429             return false;
430         }
431
432         let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
433
434         s.chars().all(char::is_alphanumeric)
435             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
436             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
437     }
438
439     fn has_underscore(s: &str) -> bool {
440         s != "_" && !s.contains("\\_") && s.contains('_')
441     }
442
443     fn has_hyphen(s: &str) -> bool {
444         s != "-" && s.contains('-')
445     }
446
447     if let Ok(url) = Url::parse(word) {
448         // try to get around the fact that `foo::bar` parses as a valid URL
449         if !url.cannot_be_a_base() {
450             span_lint(
451                 cx,
452                 DOC_MARKDOWN,
453                 span,
454                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
455             );
456
457             return;
458         }
459     }
460
461     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
462     if has_underscore(word) && has_hyphen(word) {
463         return;
464     }
465
466     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
467         span_lint(
468             cx,
469             DOC_MARKDOWN,
470             span,
471             &format!("you should put `{}` between ticks in the documentation", word),
472         );
473     }
474 }