]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / doc.rs
1 use crate::utils::{implements_trait, is_entrypoint_fn, is_type_diagnostic_item, return_ty, span_lint};
2 use if_chain::if_chain;
3 use itertools::Itertools;
4 use rustc_ast::ast::{Async, AttrKind, Attribute, FnRetTy, ItemKind};
5 use rustc_ast::token::CommentKind;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_data_structures::sync::Lrc;
8 use rustc_errors::emitter::EmitterWriter;
9 use rustc_errors::Handler;
10 use rustc_hir as hir;
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_middle::ty;
14 use rustc_parse::maybe_new_parser_from_source_str;
15 use rustc_parse::parser::ForceCollect;
16 use rustc_session::parse::ParseSess;
17 use rustc_session::{declare_tool_lint, impl_lint_pass};
18 use rustc_span::edition::Edition;
19 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
20 use rustc_span::{sym, FileName, Pos};
21 use std::io;
22 use std::ops::Range;
23 use url::Url;
24
25 declare_clippy_lint! {
26     /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
27     /// outside ticks in documentation.
28     ///
29     /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
30     /// camel-case probably indicates some code which should be included between
31     /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
32     /// consider that.
33     ///
34     /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
35     /// for is limited, and there are still false positives.
36     ///
37     /// In addition, when writing documentation comments, including `[]` brackets
38     /// inside a link text would trip the parser. Therfore, documenting link with
39     /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
40     /// would fail.
41     ///
42     /// **Examples:**
43     /// ```rust
44     /// /// Do something with the foo_bar parameter. See also
45     /// /// that::other::module::foo.
46     /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
47     /// fn doit(foo_bar: usize) {}
48     /// ```
49     ///
50     /// ```rust
51     /// // Link text with `[]` brackets should be written as following:
52     /// /// Consume the array and return the inner
53     /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
54     /// /// [SmallVec]: SmallVec
55     /// fn main() {}
56     /// ```
57     pub DOC_MARKDOWN,
58     pedantic,
59     "presence of `_`, `::` or camel-case outside backticks in documentation"
60 }
61
62 declare_clippy_lint! {
63     /// **What it does:** Checks for the doc comments of publicly visible
64     /// unsafe functions and warns if there is no `# Safety` section.
65     ///
66     /// **Why is this bad?** Unsafe functions should document their safety
67     /// preconditions, so that users can be sure they are using them safely.
68     ///
69     /// **Known problems:** None.
70     ///
71     /// **Examples:**
72     /// ```rust
73     ///# type Universe = ();
74     /// /// This function should really be documented
75     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
76     ///     unimplemented!();
77     /// }
78     /// ```
79     ///
80     /// At least write a line about safety:
81     ///
82     /// ```rust
83     ///# type Universe = ();
84     /// /// # Safety
85     /// ///
86     /// /// This function should not be called before the horsemen are ready.
87     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
88     ///     unimplemented!();
89     /// }
90     /// ```
91     pub MISSING_SAFETY_DOC,
92     style,
93     "`pub unsafe fn` without `# Safety` docs"
94 }
95
96 declare_clippy_lint! {
97     /// **What it does:** Checks the doc comments of publicly visible functions that
98     /// return a `Result` type and warns if there is no `# Errors` section.
99     ///
100     /// **Why is this bad?** Documenting the type of errors that can be returned from a
101     /// function can help callers write code to handle the errors appropriately.
102     ///
103     /// **Known problems:** None.
104     ///
105     /// **Examples:**
106     ///
107     /// Since the following function returns a `Result` it has an `# Errors` section in
108     /// its doc comment:
109     ///
110     /// ```rust
111     ///# use std::io;
112     /// /// # Errors
113     /// ///
114     /// /// Will return `Err` if `filename` does not exist or the user does not have
115     /// /// permission to read it.
116     /// pub fn read(filename: String) -> io::Result<String> {
117     ///     unimplemented!();
118     /// }
119     /// ```
120     pub MISSING_ERRORS_DOC,
121     pedantic,
122     "`pub fn` returns `Result` without `# Errors` in doc comment"
123 }
124
125 declare_clippy_lint! {
126     /// **What it does:** Checks for `fn main() { .. }` in doctests
127     ///
128     /// **Why is this bad?** The test can be shorter (and likely more readable)
129     /// if the `fn main()` is left implicit.
130     ///
131     /// **Known problems:** None.
132     ///
133     /// **Examples:**
134     /// ``````rust
135     /// /// An example of a doctest with a `main()` function
136     /// ///
137     /// /// # Examples
138     /// ///
139     /// /// ```
140     /// /// fn main() {
141     /// ///     // this needs not be in an `fn`
142     /// /// }
143     /// /// ```
144     /// fn needless_main() {
145     ///     unimplemented!();
146     /// }
147     /// ``````
148     pub NEEDLESS_DOCTEST_MAIN,
149     style,
150     "presence of `fn main() {` in code examples"
151 }
152
153 #[allow(clippy::module_name_repetitions)]
154 #[derive(Clone)]
155 pub struct DocMarkdown {
156     valid_idents: FxHashSet<String>,
157     in_trait_impl: bool,
158 }
159
160 impl DocMarkdown {
161     pub fn new(valid_idents: FxHashSet<String>) -> Self {
162         Self {
163             valid_idents,
164             in_trait_impl: false,
165         }
166     }
167 }
168
169 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
170
171 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
172     fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) {
173         check_attrs(cx, &self.valid_idents, &krate.item.attrs);
174     }
175
176     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
177         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
178         match item.kind {
179             hir::ItemKind::Fn(ref sig, _, body_id) => {
180                 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id).to_def_id())
181                     || in_external_macro(cx.tcx.sess, item.span))
182                 {
183                     lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
184                 }
185             },
186             hir::ItemKind::Impl(ref impl_) => {
187                 self.in_trait_impl = impl_.of_trait.is_some();
188             },
189             _ => {},
190         }
191     }
192
193     fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
194         if let hir::ItemKind::Impl { .. } = item.kind {
195             self.in_trait_impl = false;
196         }
197     }
198
199     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
200         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
201         if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
202             if !in_external_macro(cx.tcx.sess, item.span) {
203                 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
204             }
205         }
206     }
207
208     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
209         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
210         if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
211             return;
212         }
213         if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
214             lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
215         }
216     }
217 }
218
219 fn lint_for_missing_headers<'tcx>(
220     cx: &LateContext<'tcx>,
221     hir_id: hir::HirId,
222     span: impl Into<MultiSpan> + Copy,
223     sig: &hir::FnSig<'_>,
224     headers: DocHeaders,
225     body_id: Option<hir::BodyId>,
226 ) {
227     if !cx.access_levels.is_exported(hir_id) {
228         return; // Private functions do not require doc comments
229     }
230     if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
231         span_lint(
232             cx,
233             MISSING_SAFETY_DOC,
234             span,
235             "unsafe function's docs miss `# Safety` section",
236         );
237     }
238     if !headers.errors {
239         if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
240             span_lint(
241                 cx,
242                 MISSING_ERRORS_DOC,
243                 span,
244                 "docs for function returning `Result` missing `# Errors` section",
245             );
246         } else {
247             if_chain! {
248                 if let Some(body_id) = body_id;
249                 if let Some(future) = cx.tcx.lang_items().future_trait();
250                 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
251                 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
252                 let ret_ty = mir.return_ty();
253                 if implements_trait(cx, ret_ty, future, &[]);
254                 if let ty::Opaque(_, subs) = ret_ty.kind();
255                 if let Some(gen) = subs.types().next();
256                 if let ty::Generator(_, subs, _) = gen.kind();
257                 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
258                 then {
259                     span_lint(
260                         cx,
261                         MISSING_ERRORS_DOC,
262                         span,
263                         "docs for function returning `Result` missing `# Errors` section",
264                     );
265                 }
266             }
267         }
268     }
269 }
270
271 /// Cleanup documentation decoration.
272 ///
273 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
274 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
275 /// need to keep track of
276 /// the spans but this function is inspired from the later.
277 #[allow(clippy::cast_possible_truncation)]
278 #[must_use]
279 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
280     // one-line comments lose their prefix
281     if comment_kind == CommentKind::Line {
282         let mut doc = doc.to_owned();
283         doc.push('\n');
284         let len = doc.len();
285         // +3 skips the opening delimiter
286         return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
287     }
288
289     let mut sizes = vec![];
290     let mut contains_initial_stars = false;
291     for line in doc.lines() {
292         let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
293         debug_assert_eq!(offset as u32 as usize, offset);
294         contains_initial_stars |= line.trim_start().starts_with('*');
295         // +1 adds the newline, +3 skips the opening delimiter
296         sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
297     }
298     if !contains_initial_stars {
299         return (doc.to_string(), sizes);
300     }
301     // remove the initial '*'s if any
302     let mut no_stars = String::with_capacity(doc.len());
303     for line in doc.lines() {
304         let mut chars = line.chars();
305         while let Some(c) = chars.next() {
306             if c.is_whitespace() {
307                 no_stars.push(c);
308             } else {
309                 no_stars.push(if c == '*' { ' ' } else { c });
310                 break;
311             }
312         }
313         no_stars.push_str(chars.as_str());
314         no_stars.push('\n');
315     }
316
317     (no_stars, sizes)
318 }
319
320 #[derive(Copy, Clone)]
321 struct DocHeaders {
322     safety: bool,
323     errors: bool,
324 }
325
326 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
327     let mut doc = String::new();
328     let mut spans = vec![];
329
330     for attr in attrs {
331         if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
332             let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
333             spans.extend_from_slice(&current_spans);
334             doc.push_str(&comment);
335         } else if attr.has_name(sym::doc) {
336             // ignore mix of sugared and non-sugared doc
337             // don't trigger the safety or errors check
338             return DocHeaders {
339                 safety: true,
340                 errors: true,
341             };
342         }
343     }
344
345     let mut current = 0;
346     for &mut (ref mut offset, _) in &mut spans {
347         let offset_copy = *offset;
348         *offset = current;
349         current += offset_copy;
350     }
351
352     if doc.is_empty() {
353         return DocHeaders {
354             safety: false,
355             errors: false,
356         };
357     }
358
359     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
360     // Iterate over all `Events` and combine consecutive events into one
361     let events = parser.coalesce(|previous, current| {
362         use pulldown_cmark::Event::Text;
363
364         let previous_range = previous.1;
365         let current_range = current.1;
366
367         match (previous.0, current.0) {
368             (Text(previous), Text(current)) => {
369                 let mut previous = previous.to_string();
370                 previous.push_str(&current);
371                 Ok((Text(previous.into()), previous_range))
372             },
373             (previous, current) => Err(((previous, previous_range), (current, current_range))),
374         }
375     });
376     check_doc(cx, valid_idents, events, &spans)
377 }
378
379 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
380
381 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
382     cx: &LateContext<'_>,
383     valid_idents: &FxHashSet<String>,
384     events: Events,
385     spans: &[(usize, Span)],
386 ) -> DocHeaders {
387     // true if a safety header was found
388     use pulldown_cmark::CodeBlockKind;
389     use pulldown_cmark::Event::{
390         Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
391     };
392     use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
393
394     let mut headers = DocHeaders {
395         safety: false,
396         errors: false,
397     };
398     let mut in_code = false;
399     let mut in_link = None;
400     let mut in_heading = false;
401     let mut is_rust = false;
402     let mut edition = None;
403     for (event, range) in events {
404         match event {
405             Start(CodeBlock(ref kind)) => {
406                 in_code = true;
407                 if let CodeBlockKind::Fenced(lang) = kind {
408                     for item in lang.split(',') {
409                         if item == "ignore" {
410                             is_rust = false;
411                             break;
412                         }
413                         if let Some(stripped) = item.strip_prefix("edition") {
414                             is_rust = true;
415                             edition = stripped.parse::<Edition>().ok();
416                         } else if item.is_empty() || RUST_CODE.contains(&item) {
417                             is_rust = true;
418                         }
419                     }
420                 }
421             },
422             End(CodeBlock(_)) => {
423                 in_code = false;
424                 is_rust = false;
425             },
426             Start(Link(_, url, _)) => in_link = Some(url),
427             End(Link(..)) => in_link = None,
428             Start(Heading(_)) => in_heading = true,
429             End(Heading(_)) => in_heading = false,
430             Start(_tag) | End(_tag) => (), // We don't care about other tags
431             Html(_html) => (),             // HTML is weird, just ignore it
432             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
433             FootnoteReference(text) | Text(text) => {
434                 if Some(&text) == in_link.as_ref() {
435                     // Probably a link of the form `<http://example.com>`
436                     // Which are represented as a link to "http://example.com" with
437                     // text "http://example.com" by pulldown-cmark
438                     continue;
439                 }
440                 headers.safety |= in_heading && text.trim() == "Safety";
441                 headers.errors |= in_heading && text.trim() == "Errors";
442                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
443                     Ok(o) => o,
444                     Err(e) => e - 1,
445                 };
446                 let (begin, span) = spans[index];
447                 if in_code {
448                     if is_rust {
449                         let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
450                         check_code(cx, &text, edition, span);
451                     }
452                 } else {
453                     // Adjust for the beginning of the current `Event`
454                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
455
456                     check_text(cx, valid_idents, &text, span);
457                 }
458             },
459         }
460     }
461     headers
462 }
463
464 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
465     fn has_needless_main(code: &str, edition: Edition) -> bool {
466         rustc_driver::catch_fatal_errors(|| {
467             rustc_span::with_session_globals(edition, || {
468                 let filename = FileName::anon_source_code(code);
469
470                 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
471                 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
472                 let handler = Handler::with_emitter(false, None, box emitter);
473                 let sess = ParseSess::with_span_handler(handler, sm);
474
475                 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
476                     Ok(p) => p,
477                     Err(errs) => {
478                         for mut err in errs {
479                             err.cancel();
480                         }
481                         return false;
482                     },
483                 };
484
485                 let mut relevant_main_found = false;
486                 loop {
487                     match parser.parse_item(ForceCollect::No) {
488                         Ok(Some(item)) => match &item.kind {
489                             // Tests with one of these items are ignored
490                             ItemKind::Static(..)
491                             | ItemKind::Const(..)
492                             | ItemKind::ExternCrate(..)
493                             | ItemKind::ForeignMod(..) => return false,
494                             // We found a main function ...
495                             ItemKind::Fn(_, sig, _, Some(block)) if item.ident.name == sym::main => {
496                                 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
497                                 let returns_nothing = match &sig.decl.output {
498                                     FnRetTy::Default(..) => true,
499                                     FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
500                                     _ => false,
501                                 };
502
503                                 if returns_nothing && !is_async && !block.stmts.is_empty() {
504                                     // This main function should be linted, but only if there are no other functions
505                                     relevant_main_found = true;
506                                 } else {
507                                     // This main function should not be linted, we're done
508                                     return false;
509                                 }
510                             },
511                             // Another function was found; this case is ignored too
512                             ItemKind::Fn(..) => return false,
513                             _ => {},
514                         },
515                         Ok(None) => break,
516                         Err(mut e) => {
517                             e.cancel();
518                             return false;
519                         },
520                     }
521                 }
522
523                 relevant_main_found
524             })
525         })
526         .ok()
527         .unwrap_or_default()
528     }
529
530     if has_needless_main(text, edition) {
531         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
532     }
533 }
534
535 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
536     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
537         // Trim punctuation as in `some comment (see foo::bar).`
538         //                                                   ^^
539         // Or even as in `_foo bar_` which is emphasized.
540         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
541
542         if valid_idents.contains(word) {
543             continue;
544         }
545
546         // Adjust for the current word
547         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
548         let span = Span::new(
549             span.lo() + BytePos::from_usize(offset),
550             span.lo() + BytePos::from_usize(offset + word.len()),
551             span.ctxt(),
552         );
553
554         check_word(cx, word, span);
555     }
556 }
557
558 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
559     /// Checks if a string is camel-case, i.e., contains at least two uppercase
560     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
561     /// Plurals are also excluded (`IDs` is ok).
562     fn is_camel_case(s: &str) -> bool {
563         if s.starts_with(|c: char| c.is_digit(10)) {
564             return false;
565         }
566
567         let s = s.strip_suffix('s').unwrap_or(s);
568
569         s.chars().all(char::is_alphanumeric)
570             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
571             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
572     }
573
574     fn has_underscore(s: &str) -> bool {
575         s != "_" && !s.contains("\\_") && s.contains('_')
576     }
577
578     fn has_hyphen(s: &str) -> bool {
579         s != "-" && s.contains('-')
580     }
581
582     if let Ok(url) = Url::parse(word) {
583         // try to get around the fact that `foo::bar` parses as a valid URL
584         if !url.cannot_be_a_base() {
585             span_lint(
586                 cx,
587                 DOC_MARKDOWN,
588                 span,
589                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
590             );
591
592             return;
593         }
594     }
595
596     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
597     if has_underscore(word) && has_hyphen(word) {
598         return;
599     }
600
601     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
602         span_lint(
603             cx,
604             DOC_MARKDOWN,
605             span,
606             &format!("you should put `{}` between ticks in the documentation", word),
607         );
608     }
609 }