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