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