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