]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Auto merge of #4866 - rust-lang:needful-doctest-main, r=flip1995
[rust.git] / clippy_lints / src / doc.rs
1 use crate::utils::span_lint;
2 use itertools::Itertools;
3 use pulldown_cmark;
4 use rustc::hir;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, impl_lint_pass};
7 use rustc_data_structures::fx::FxHashSet;
8 use std::ops::Range;
9 use syntax::ast::{AttrKind, Attribute};
10 use syntax::source_map::{BytePos, 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 for `fn main() { .. }` in doctests
74     ///
75     /// **Why is this bad?** The test can be shorter (and likely more readable)
76     /// if the `fn main()` is left implicit.
77     ///
78     /// **Known problems:** None.
79     ///
80     /// **Examples:**
81     /// ``````rust
82     /// /// An example of a doctest with a `main()` function
83     /// ///
84     /// /// # Examples
85     /// ///
86     /// /// ```
87     /// /// fn main() {
88     /// ///     // this needs not be in an `fn`
89     /// /// }
90     /// /// ```
91     /// fn needless_main() {
92     ///     unimplemented!();
93     /// }
94     /// ``````
95     pub NEEDLESS_DOCTEST_MAIN,
96     style,
97     "presence of `fn main() {` in code examples"
98 }
99
100 #[allow(clippy::module_name_repetitions)]
101 #[derive(Clone)]
102 pub struct DocMarkdown {
103     valid_idents: FxHashSet<String>,
104     in_trait_impl: bool,
105 }
106
107 impl DocMarkdown {
108     pub fn new(valid_idents: FxHashSet<String>) -> Self {
109         Self {
110             valid_idents,
111             in_trait_impl: false,
112         }
113     }
114 }
115
116 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, NEEDLESS_DOCTEST_MAIN]);
117
118 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown {
119     fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate) {
120         check_attrs(cx, &self.valid_idents, &krate.attrs);
121     }
122
123     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
124         if check_attrs(cx, &self.valid_idents, &item.attrs) {
125             return;
126         }
127         // no safety header
128         match item.kind {
129             hir::ItemKind::Fn(ref sig, ..) => {
130                 if cx.access_levels.is_exported(item.hir_id) && sig.header.unsafety == hir::Unsafety::Unsafe {
131                     span_lint(
132                         cx,
133                         MISSING_SAFETY_DOC,
134                         item.span,
135                         "unsafe function's docs miss `# Safety` section",
136                     );
137                 }
138             },
139             hir::ItemKind::Impl(_, _, _, _, ref trait_ref, ..) => {
140                 self.in_trait_impl = trait_ref.is_some();
141             },
142             _ => {},
143         }
144     }
145
146     fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
147         if let hir::ItemKind::Impl(..) = item.kind {
148             self.in_trait_impl = false;
149         }
150     }
151
152     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
153         if check_attrs(cx, &self.valid_idents, &item.attrs) {
154             return;
155         }
156         // no safety header
157         if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
158             if cx.access_levels.is_exported(item.hir_id) && sig.header.unsafety == hir::Unsafety::Unsafe {
159                 span_lint(
160                     cx,
161                     MISSING_SAFETY_DOC,
162                     item.span,
163                     "unsafe function's docs miss `# Safety` section",
164                 );
165             }
166         }
167     }
168
169     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
170         if check_attrs(cx, &self.valid_idents, &item.attrs) || self.in_trait_impl {
171             return;
172         }
173         // no safety header
174         if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
175             if cx.access_levels.is_exported(item.hir_id) && sig.header.unsafety == hir::Unsafety::Unsafe {
176                 span_lint(
177                     cx,
178                     MISSING_SAFETY_DOC,
179                     item.span,
180                     "unsafe function's docs miss `# Safety` section",
181                 );
182             }
183         }
184     }
185 }
186
187 /// Cleanup documentation decoration (`///` and such).
188 ///
189 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
190 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
191 /// need to keep track of
192 /// the spans but this function is inspired from the later.
193 #[allow(clippy::cast_possible_truncation)]
194 #[must_use]
195 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
196     // one-line comments lose their prefix
197     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
198     for prefix in ONELINERS {
199         if comment.starts_with(*prefix) {
200             let doc = &comment[prefix.len()..];
201             let mut doc = doc.to_owned();
202             doc.push('\n');
203             return (
204                 doc.to_owned(),
205                 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
206             );
207         }
208     }
209
210     if comment.starts_with("/*") {
211         let doc = &comment[3..comment.len() - 2];
212         let mut sizes = vec![];
213         let mut contains_initial_stars = false;
214         for line in doc.lines() {
215             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
216             debug_assert_eq!(offset as u32 as usize, offset);
217             contains_initial_stars |= line.trim_start().starts_with('*');
218             // +1 for the newline
219             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
220         }
221         if !contains_initial_stars {
222             return (doc.to_string(), sizes);
223         }
224         // remove the initial '*'s if any
225         let mut no_stars = String::with_capacity(doc.len());
226         for line in doc.lines() {
227             let mut chars = line.chars();
228             while let Some(c) = chars.next() {
229                 if c.is_whitespace() {
230                     no_stars.push(c);
231                 } else {
232                     no_stars.push(if c == '*' { ' ' } else { c });
233                     break;
234                 }
235             }
236             no_stars.push_str(chars.as_str());
237             no_stars.push('\n');
238         }
239         return (no_stars, sizes);
240     }
241
242     panic!("not a doc-comment: {}", comment);
243 }
244
245 pub fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> bool {
246     let mut doc = String::new();
247     let mut spans = vec![];
248
249     for attr in attrs {
250         if let AttrKind::DocComment(ref comment) = attr.kind {
251             let comment = comment.to_string();
252             let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
253             spans.extend_from_slice(&current_spans);
254             doc.push_str(&comment);
255         } else if attr.check_name(sym!(doc)) {
256             // ignore mix of sugared and non-sugared doc
257             return true; // don't trigger the safety check
258         }
259     }
260
261     let mut current = 0;
262     for &mut (ref mut offset, _) in &mut spans {
263         let offset_copy = *offset;
264         *offset = current;
265         current += offset_copy;
266     }
267
268     if doc.is_empty() {
269         return false;
270     }
271
272     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
273     // Iterate over all `Events` and combine consecutive events into one
274     let events = parser.coalesce(|previous, current| {
275         use pulldown_cmark::Event::*;
276
277         let previous_range = previous.1;
278         let current_range = current.1;
279
280         match (previous.0, current.0) {
281             (Text(previous), Text(current)) => {
282                 let mut previous = previous.to_string();
283                 previous.push_str(&current);
284                 Ok((Text(previous.into()), previous_range))
285             },
286             (previous, current) => Err(((previous, previous_range), (current, current_range))),
287         }
288     });
289     check_doc(cx, valid_idents, events, &spans)
290 }
291
292 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
293     cx: &LateContext<'_, '_>,
294     valid_idents: &FxHashSet<String>,
295     events: Events,
296     spans: &[(usize, Span)],
297 ) -> bool {
298     // true if a safety header was found
299     use pulldown_cmark::Event::*;
300     use pulldown_cmark::Tag::*;
301
302     let mut safety_header = false;
303     let mut in_code = false;
304     let mut in_link = None;
305     let mut in_heading = false;
306
307     for (event, range) in events {
308         match event {
309             Start(CodeBlock(_)) => in_code = true,
310             End(CodeBlock(_)) => in_code = false,
311             Start(Link(_, url, _)) => in_link = Some(url),
312             End(Link(..)) => in_link = None,
313             Start(Heading(_)) => in_heading = true,
314             End(Heading(_)) => in_heading = false,
315             Start(_tag) | End(_tag) => (), // We don't care about other tags
316             Html(_html) => (),             // HTML is weird, just ignore it
317             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
318             FootnoteReference(text) | Text(text) => {
319                 if Some(&text) == in_link.as_ref() {
320                     // Probably a link of the form `<http://example.com>`
321                     // Which are represented as a link to "http://example.com" with
322                     // text "http://example.com" by pulldown-cmark
323                     continue;
324                 }
325                 safety_header |= in_heading && text.trim() == "Safety";
326                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
327                     Ok(o) => o,
328                     Err(e) => e - 1,
329                 };
330                 let (begin, span) = spans[index];
331                 if in_code {
332                     check_code(cx, &text, span);
333                 } else {
334                     // Adjust for the beginning of the current `Event`
335                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
336
337                     check_text(cx, valid_idents, &text, span);
338                 }
339             },
340         }
341     }
342     safety_header
343 }
344
345 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
346     if text.contains("fn main() {") && !(text.contains("static") || text.contains("fn main() {}")) {
347         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
348     }
349 }
350
351 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
352     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
353         // Trim punctuation as in `some comment (see foo::bar).`
354         //                                                   ^^
355         // Or even as in `_foo bar_` which is emphasized.
356         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
357
358         if valid_idents.contains(word) {
359             continue;
360         }
361
362         // Adjust for the current word
363         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
364         let span = Span::new(
365             span.lo() + BytePos::from_usize(offset),
366             span.lo() + BytePos::from_usize(offset + word.len()),
367             span.ctxt(),
368         );
369
370         check_word(cx, word, span);
371     }
372 }
373
374 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
375     /// Checks if a string is camel-case, i.e., contains at least two uppercase
376     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
377     /// Plurals are also excluded (`IDs` is ok).
378     fn is_camel_case(s: &str) -> bool {
379         if s.starts_with(|c: char| c.is_digit(10)) {
380             return false;
381         }
382
383         let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
384
385         s.chars().all(char::is_alphanumeric)
386             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
387             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
388     }
389
390     fn has_underscore(s: &str) -> bool {
391         s != "_" && !s.contains("\\_") && s.contains('_')
392     }
393
394     fn has_hyphen(s: &str) -> bool {
395         s != "-" && s.contains('-')
396     }
397
398     if let Ok(url) = Url::parse(word) {
399         // try to get around the fact that `foo::bar` parses as a valid URL
400         if !url.cannot_be_a_base() {
401             span_lint(
402                 cx,
403                 DOC_MARKDOWN,
404                 span,
405                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
406             );
407
408             return;
409         }
410     }
411
412     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
413     if has_underscore(word) && has_hyphen(word) {
414         return;
415     }
416
417     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
418         span_lint(
419             cx,
420             DOC_MARKDOWN,
421             span,
422             &format!("you should put `{}` between ticks in the documentation", word),
423         );
424     }
425 }