]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Remove PredicateKind::Atom
[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(ref impl_) => {
186                 self.in_trait_impl = impl_.of_trait.is_some();
187             },
188             _ => {},
189         }
190     }
191
192     fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
193         if let hir::ItemKind::Impl { .. } = item.kind {
194             self.in_trait_impl = false;
195         }
196     }
197
198     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
199         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
200         if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
201             if !in_external_macro(cx.tcx.sess, item.span) {
202                 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
203             }
204         }
205     }
206
207     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
208         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
209         if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
210             return;
211         }
212         if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
213             lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
214         }
215     }
216 }
217
218 fn lint_for_missing_headers<'tcx>(
219     cx: &LateContext<'tcx>,
220     hir_id: hir::HirId,
221     span: impl Into<MultiSpan> + Copy,
222     sig: &hir::FnSig<'_>,
223     headers: DocHeaders,
224     body_id: Option<hir::BodyId>,
225 ) {
226     if !cx.access_levels.is_exported(hir_id) {
227         return; // Private functions do not require doc comments
228     }
229     if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
230         span_lint(
231             cx,
232             MISSING_SAFETY_DOC,
233             span,
234             "unsafe function's docs miss `# Safety` section",
235         );
236     }
237     if !headers.errors {
238         if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
239             span_lint(
240                 cx,
241                 MISSING_ERRORS_DOC,
242                 span,
243                 "docs for function returning `Result` missing `# Errors` section",
244             );
245         } else {
246             if_chain! {
247                 if let Some(body_id) = body_id;
248                 if let Some(future) = cx.tcx.lang_items().future_trait();
249                 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
250                 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
251                 let ret_ty = mir.return_ty();
252                 if implements_trait(cx, ret_ty, future, &[]);
253                 if let ty::Opaque(_, subs) = ret_ty.kind();
254                 if let Some(gen) = subs.types().next();
255                 if let ty::Generator(_, subs, _) = gen.kind();
256                 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
257                 then {
258                     span_lint(
259                         cx,
260                         MISSING_ERRORS_DOC,
261                         span,
262                         "docs for function returning `Result` missing `# Errors` section",
263                     );
264                 }
265             }
266         }
267     }
268 }
269
270 /// Cleanup documentation decoration.
271 ///
272 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
273 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
274 /// need to keep track of
275 /// the spans but this function is inspired from the later.
276 #[allow(clippy::cast_possible_truncation)]
277 #[must_use]
278 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
279     // one-line comments lose their prefix
280     if comment_kind == CommentKind::Line {
281         let mut doc = doc.to_owned();
282         doc.push('\n');
283         let len = doc.len();
284         // +3 skips the opening delimiter
285         return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
286     }
287
288     let mut sizes = vec![];
289     let mut contains_initial_stars = false;
290     for line in doc.lines() {
291         let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
292         debug_assert_eq!(offset as u32 as usize, offset);
293         contains_initial_stars |= line.trim_start().starts_with('*');
294         // +1 adds the newline, +3 skips the opening delimiter
295         sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
296     }
297     if !contains_initial_stars {
298         return (doc.to_string(), sizes);
299     }
300     // remove the initial '*'s if any
301     let mut no_stars = String::with_capacity(doc.len());
302     for line in doc.lines() {
303         let mut chars = line.chars();
304         while let Some(c) = chars.next() {
305             if c.is_whitespace() {
306                 no_stars.push(c);
307             } else {
308                 no_stars.push(if c == '*' { ' ' } else { c });
309                 break;
310             }
311         }
312         no_stars.push_str(chars.as_str());
313         no_stars.push('\n');
314     }
315
316     (no_stars, sizes)
317 }
318
319 #[derive(Copy, Clone)]
320 struct DocHeaders {
321     safety: bool,
322     errors: bool,
323 }
324
325 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
326     let mut doc = String::new();
327     let mut spans = vec![];
328
329     for attr in attrs {
330         if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
331             let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
332             spans.extend_from_slice(&current_spans);
333             doc.push_str(&comment);
334         } else if attr.has_name(sym::doc) {
335             // ignore mix of sugared and non-sugared doc
336             // don't trigger the safety or errors check
337             return DocHeaders {
338                 safety: true,
339                 errors: true,
340             };
341         }
342     }
343
344     let mut current = 0;
345     for &mut (ref mut offset, _) in &mut spans {
346         let offset_copy = *offset;
347         *offset = current;
348         current += offset_copy;
349     }
350
351     if doc.is_empty() {
352         return DocHeaders {
353             safety: false,
354             errors: false,
355         };
356     }
357
358     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
359     // Iterate over all `Events` and combine consecutive events into one
360     let events = parser.coalesce(|previous, current| {
361         use pulldown_cmark::Event::Text;
362
363         let previous_range = previous.1;
364         let current_range = current.1;
365
366         match (previous.0, current.0) {
367             (Text(previous), Text(current)) => {
368                 let mut previous = previous.to_string();
369                 previous.push_str(&current);
370                 Ok((Text(previous.into()), previous_range))
371             },
372             (previous, current) => Err(((previous, previous_range), (current, current_range))),
373         }
374     });
375     check_doc(cx, valid_idents, events, &spans)
376 }
377
378 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
379
380 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
381     cx: &LateContext<'_>,
382     valid_idents: &FxHashSet<String>,
383     events: Events,
384     spans: &[(usize, Span)],
385 ) -> DocHeaders {
386     // true if a safety header was found
387     use pulldown_cmark::CodeBlockKind;
388     use pulldown_cmark::Event::{
389         Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
390     };
391     use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
392
393     let mut headers = DocHeaders {
394         safety: false,
395         errors: false,
396     };
397     let mut in_code = false;
398     let mut in_link = None;
399     let mut in_heading = false;
400     let mut is_rust = false;
401     let mut edition = None;
402     for (event, range) in events {
403         match event {
404             Start(CodeBlock(ref kind)) => {
405                 in_code = true;
406                 if let CodeBlockKind::Fenced(lang) = kind {
407                     for item in lang.split(',') {
408                         if item == "ignore" {
409                             is_rust = false;
410                             break;
411                         }
412                         if let Some(stripped) = item.strip_prefix("edition") {
413                             is_rust = true;
414                             edition = stripped.parse::<Edition>().ok();
415                         } else if item.is_empty() || RUST_CODE.contains(&item) {
416                             is_rust = true;
417                         }
418                     }
419                 }
420             },
421             End(CodeBlock(_)) => {
422                 in_code = false;
423                 is_rust = false;
424             },
425             Start(Link(_, url, _)) => in_link = Some(url),
426             End(Link(..)) => in_link = None,
427             Start(Heading(_)) => in_heading = true,
428             End(Heading(_)) => in_heading = false,
429             Start(_tag) | End(_tag) => (), // We don't care about other tags
430             Html(_html) => (),             // HTML is weird, just ignore it
431             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
432             FootnoteReference(text) | Text(text) => {
433                 if Some(&text) == in_link.as_ref() {
434                     // Probably a link of the form `<http://example.com>`
435                     // Which are represented as a link to "http://example.com" with
436                     // text "http://example.com" by pulldown-cmark
437                     continue;
438                 }
439                 headers.safety |= in_heading && text.trim() == "Safety";
440                 headers.errors |= in_heading && text.trim() == "Errors";
441                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
442                     Ok(o) => o,
443                     Err(e) => e - 1,
444                 };
445                 let (begin, span) = spans[index];
446                 if in_code {
447                     if is_rust {
448                         let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
449                         check_code(cx, &text, edition, span);
450                     }
451                 } else {
452                     // Adjust for the beginning of the current `Event`
453                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
454
455                     check_text(cx, valid_idents, &text, span);
456                 }
457             },
458         }
459     }
460     headers
461 }
462
463 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
464     fn has_needless_main(code: &str, edition: Edition) -> bool {
465         rustc_driver::catch_fatal_errors(|| {
466             rustc_span::with_session_globals(edition, || {
467                 let filename = FileName::anon_source_code(code);
468
469                 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
470                 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
471                 let handler = Handler::with_emitter(false, None, box emitter);
472                 let sess = ParseSess::with_span_handler(handler, sm);
473
474                 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
475                     Ok(p) => p,
476                     Err(errs) => {
477                         for mut err in errs {
478                             err.cancel();
479                         }
480                         return false;
481                     },
482                 };
483
484                 let mut relevant_main_found = false;
485                 loop {
486                     match parser.parse_item() {
487                         Ok(Some(item)) => match &item.kind {
488                             // Tests with one of these items are ignored
489                             ItemKind::Static(..)
490                             | ItemKind::Const(..)
491                             | ItemKind::ExternCrate(..)
492                             | ItemKind::ForeignMod(..) => return false,
493                             // We found a main function ...
494                             ItemKind::Fn(_, sig, _, Some(block)) if item.ident.name == sym::main => {
495                                 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
496                                 let returns_nothing = match &sig.decl.output {
497                                     FnRetTy::Default(..) => true,
498                                     FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
499                                     _ => false,
500                                 };
501
502                                 if returns_nothing && !is_async && !block.stmts.is_empty() {
503                                     // This main function should be linted, but only if there are no other functions
504                                     relevant_main_found = true;
505                                 } else {
506                                     // This main function should not be linted, we're done
507                                     return false;
508                                 }
509                             },
510                             // Another function was found; this case is ignored too
511                             ItemKind::Fn(..) => return false,
512                             _ => {},
513                         },
514                         Ok(None) => break,
515                         Err(mut e) => {
516                             e.cancel();
517                             return false;
518                         },
519                     }
520                 }
521
522                 relevant_main_found
523             })
524         })
525         .ok()
526         .unwrap_or_default()
527     }
528
529     if has_needless_main(text, edition) {
530         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
531     }
532 }
533
534 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
535     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
536         // Trim punctuation as in `some comment (see foo::bar).`
537         //                                                   ^^
538         // Or even as in `_foo bar_` which is emphasized.
539         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
540
541         if valid_idents.contains(word) {
542             continue;
543         }
544
545         // Adjust for the current word
546         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
547         let span = Span::new(
548             span.lo() + BytePos::from_usize(offset),
549             span.lo() + BytePos::from_usize(offset + word.len()),
550             span.ctxt(),
551         );
552
553         check_word(cx, word, span);
554     }
555 }
556
557 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
558     /// Checks if a string is camel-case, i.e., contains at least two uppercase
559     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
560     /// Plurals are also excluded (`IDs` is ok).
561     fn is_camel_case(s: &str) -> bool {
562         if s.starts_with(|c: char| c.is_digit(10)) {
563             return false;
564         }
565
566         let s = s.strip_suffix('s').unwrap_or(s);
567
568         s.chars().all(char::is_alphanumeric)
569             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
570             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
571     }
572
573     fn has_underscore(s: &str) -> bool {
574         s != "_" && !s.contains("\\_") && s.contains('_')
575     }
576
577     fn has_hyphen(s: &str) -> bool {
578         s != "-" && s.contains('-')
579     }
580
581     if let Ok(url) = Url::parse(word) {
582         // try to get around the fact that `foo::bar` parses as a valid URL
583         if !url.cannot_be_a_base() {
584             span_lint(
585                 cx,
586                 DOC_MARKDOWN,
587                 span,
588                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
589             );
590
591             return;
592         }
593     }
594
595     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
596     if has_underscore(word) && has_hyphen(word) {
597         return;
598     }
599
600     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
601         span_lint(
602             cx,
603             DOC_MARKDOWN,
604             span,
605             &format!("you should put `{}` between ticks in the documentation", word),
606         );
607     }
608 }