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