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