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