2 implements_trait, is_entrypoint_fn, is_expn_of, is_type_diagnostic_item, match_panic_def_id, method_chain_args,
3 return_ty, span_lint, span_lint_and_note,
5 use if_chain::if_chain;
6 use itertools::Itertools;
7 use rustc_ast::ast::{Async, AttrKind, Attribute, FnKind, FnRetTy, ItemKind};
8 use rustc_ast::token::CommentKind;
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_data_structures::sync::Lrc;
11 use rustc_errors::emitter::EmitterWriter;
12 use rustc_errors::Handler;
14 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
15 use rustc_hir::{Expr, ExprKind, QPath};
16 use rustc_lint::{LateContext, LateLintPass};
17 use rustc_middle::hir::map::Map;
18 use rustc_middle::lint::in_external_macro;
20 use rustc_parse::maybe_new_parser_from_source_str;
21 use rustc_parse::parser::ForceCollect;
22 use rustc_session::parse::ParseSess;
23 use rustc_session::{declare_tool_lint, impl_lint_pass};
24 use rustc_span::edition::Edition;
25 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
26 use rustc_span::{sym, FileName, Pos};
31 declare_clippy_lint! {
32 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
33 /// outside ticks in documentation.
35 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
36 /// camel-case probably indicates some code which should be included between
37 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
40 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
41 /// for is limited, and there are still false positives.
43 /// In addition, when writing documentation comments, including `[]` brackets
44 /// inside a link text would trip the parser. Therfore, documenting link with
45 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
50 /// /// Do something with the foo_bar parameter. See also
51 /// /// that::other::module::foo.
52 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
53 /// fn doit(foo_bar: usize) {}
57 /// // Link text with `[]` brackets should be written as following:
58 /// /// Consume the array and return the inner
59 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
60 /// /// [SmallVec]: SmallVec
65 "presence of `_`, `::` or camel-case outside backticks in documentation"
68 declare_clippy_lint! {
69 /// **What it does:** Checks for the doc comments of publicly visible
70 /// unsafe functions and warns if there is no `# Safety` section.
72 /// **Why is this bad?** Unsafe functions should document their safety
73 /// preconditions, so that users can be sure they are using them safely.
75 /// **Known problems:** None.
79 ///# type Universe = ();
80 /// /// This function should really be documented
81 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
86 /// At least write a line about safety:
89 ///# type Universe = ();
92 /// /// This function should not be called before the horsemen are ready.
93 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
97 pub MISSING_SAFETY_DOC,
99 "`pub unsafe fn` without `# Safety` docs"
102 declare_clippy_lint! {
103 /// **What it does:** Checks the doc comments of publicly visible functions that
104 /// return a `Result` type and warns if there is no `# Errors` section.
106 /// **Why is this bad?** Documenting the type of errors that can be returned from a
107 /// function can help callers write code to handle the errors appropriately.
109 /// **Known problems:** None.
113 /// Since the following function returns a `Result` it has an `# Errors` section in
120 /// /// Will return `Err` if `filename` does not exist or the user does not have
121 /// /// permission to read it.
122 /// pub fn read(filename: String) -> io::Result<String> {
123 /// unimplemented!();
126 pub MISSING_ERRORS_DOC,
128 "`pub fn` returns `Result` without `# Errors` in doc comment"
131 declare_clippy_lint! {
132 /// **What it does:** Checks the doc comments of publicly visible functions that
133 /// may panic and warns if there is no `# Panics` section.
135 /// **Why is this bad?** Documenting the scenarios in which panicking occurs
136 /// can help callers who do not want to panic to avoid those situations.
138 /// **Known problems:** None.
142 /// Since the following function may panic it has a `# Panics` section in
148 /// /// Will panic if y is 0
149 /// pub fn divide_by(x: i32, y: i32) -> i32 {
151 /// panic!("Cannot divide by 0")
157 pub MISSING_PANICS_DOC,
159 "`pub fn` may panic without `# Panics` in doc comment"
162 declare_clippy_lint! {
163 /// **What it does:** Checks for `fn main() { .. }` in doctests
165 /// **Why is this bad?** The test can be shorter (and likely more readable)
166 /// if the `fn main()` is left implicit.
168 /// **Known problems:** None.
172 /// /// An example of a doctest with a `main()` function
178 /// /// // this needs not be in an `fn`
181 /// fn needless_main() {
182 /// unimplemented!();
185 pub NEEDLESS_DOCTEST_MAIN,
187 "presence of `fn main() {` in code examples"
190 #[allow(clippy::module_name_repetitions)]
192 pub struct DocMarkdown {
193 valid_idents: FxHashSet<String>,
198 pub fn new(valid_idents: FxHashSet<String>) -> Self {
201 in_trait_impl: false,
206 impl_lint_pass!(DocMarkdown =>
207 [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, NEEDLESS_DOCTEST_MAIN]
210 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
211 fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) {
212 check_attrs(cx, &self.valid_idents, &krate.item.attrs);
215 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
216 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
218 hir::ItemKind::Fn(ref sig, _, body_id) => {
219 if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) {
220 let body = cx.tcx.hir().body(body_id);
221 let mut fpu = FindPanicUnwrap {
223 typeck_results: cx.tcx.typeck(item.def_id),
226 fpu.visit_expr(&body.value);
227 lint_for_missing_headers(
238 hir::ItemKind::Impl(ref impl_) => {
239 self.in_trait_impl = impl_.of_trait.is_some();
245 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
246 if let hir::ItemKind::Impl { .. } = item.kind {
247 self.in_trait_impl = false;
251 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
252 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
253 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
254 if !in_external_macro(cx.tcx.sess, item.span) {
255 lint_for_missing_headers(cx, item.hir_id(), item.span, sig, headers, None, None);
260 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
261 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
262 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
265 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
266 let body = cx.tcx.hir().body(body_id);
267 let mut fpu = FindPanicUnwrap {
269 typeck_results: cx.tcx.typeck(item.def_id),
272 fpu.visit_expr(&body.value);
273 lint_for_missing_headers(
286 fn lint_for_missing_headers<'tcx>(
287 cx: &LateContext<'tcx>,
289 span: impl Into<MultiSpan> + Copy,
290 sig: &hir::FnSig<'_>,
292 body_id: Option<hir::BodyId>,
293 panic_span: Option<Span>,
295 if !cx.access_levels.is_exported(hir_id) {
296 return; // Private functions do not require doc comments
298 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
303 "unsafe function's docs miss `# Safety` section",
306 if !headers.panics && panic_span.is_some() {
311 "docs for function which may panic missing `# Panics` section",
313 "first possible panic found here",
317 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
322 "docs for function returning `Result` missing `# Errors` section",
326 if let Some(body_id) = body_id;
327 if let Some(future) = cx.tcx.lang_items().future_trait();
328 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
329 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
330 let ret_ty = mir.return_ty();
331 if implements_trait(cx, ret_ty, future, &[]);
332 if let ty::Opaque(_, subs) = ret_ty.kind();
333 if let Some(gen) = subs.types().next();
334 if let ty::Generator(_, subs, _) = gen.kind();
335 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
341 "docs for function returning `Result` missing `# Errors` section",
349 /// Cleanup documentation decoration.
351 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
352 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
353 /// need to keep track of
354 /// the spans but this function is inspired from the later.
355 #[allow(clippy::cast_possible_truncation)]
357 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
358 // one-line comments lose their prefix
359 if comment_kind == CommentKind::Line {
360 let mut doc = doc.to_owned();
363 // +3 skips the opening delimiter
364 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
367 let mut sizes = vec![];
368 let mut contains_initial_stars = false;
369 for line in doc.lines() {
370 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
371 debug_assert_eq!(offset as u32 as usize, offset);
372 contains_initial_stars |= line.trim_start().starts_with('*');
373 // +1 adds the newline, +3 skips the opening delimiter
374 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
376 if !contains_initial_stars {
377 return (doc.to_string(), sizes);
379 // remove the initial '*'s if any
380 let mut no_stars = String::with_capacity(doc.len());
381 for line in doc.lines() {
382 let mut chars = line.chars();
383 while let Some(c) = chars.next() {
384 if c.is_whitespace() {
387 no_stars.push(if c == '*' { ' ' } else { c });
391 no_stars.push_str(chars.as_str());
398 #[derive(Copy, Clone)]
405 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
406 let mut doc = String::new();
407 let mut spans = vec![];
410 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
411 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
412 spans.extend_from_slice(¤t_spans);
413 doc.push_str(&comment);
414 } else if attr.has_name(sym::doc) {
415 // ignore mix of sugared and non-sugared doc
416 // don't trigger the safety or errors check
426 for &mut (ref mut offset, _) in &mut spans {
427 let offset_copy = *offset;
429 current += offset_copy;
440 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
441 // Iterate over all `Events` and combine consecutive events into one
442 let events = parser.coalesce(|previous, current| {
443 use pulldown_cmark::Event::Text;
445 let previous_range = previous.1;
446 let current_range = current.1;
448 match (previous.0, current.0) {
449 (Text(previous), Text(current)) => {
450 let mut previous = previous.to_string();
451 previous.push_str(¤t);
452 Ok((Text(previous.into()), previous_range))
454 (previous, current) => Err(((previous, previous_range), (current, current_range))),
457 check_doc(cx, valid_idents, events, &spans)
460 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
462 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
463 cx: &LateContext<'_>,
464 valid_idents: &FxHashSet<String>,
466 spans: &[(usize, Span)],
468 // true if a safety header was found
469 use pulldown_cmark::CodeBlockKind;
470 use pulldown_cmark::Event::{
471 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
473 use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
475 let mut headers = DocHeaders {
480 let mut in_code = false;
481 let mut in_link = None;
482 let mut in_heading = false;
483 let mut is_rust = false;
484 let mut edition = None;
485 for (event, range) in events {
487 Start(CodeBlock(ref kind)) => {
489 if let CodeBlockKind::Fenced(lang) = kind {
490 for item in lang.split(',') {
491 if item == "ignore" {
495 if let Some(stripped) = item.strip_prefix("edition") {
497 edition = stripped.parse::<Edition>().ok();
498 } else if item.is_empty() || RUST_CODE.contains(&item) {
504 End(CodeBlock(_)) => {
508 Start(Link(_, url, _)) => in_link = Some(url),
509 End(Link(..)) => in_link = None,
510 Start(Heading(_)) => in_heading = true,
511 End(Heading(_)) => in_heading = false,
512 Start(_tag) | End(_tag) => (), // We don't care about other tags
513 Html(_html) => (), // HTML is weird, just ignore it
514 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
515 FootnoteReference(text) | Text(text) => {
516 if Some(&text) == in_link.as_ref() {
517 // Probably a link of the form `<http://example.com>`
518 // Which are represented as a link to "http://example.com" with
519 // text "http://example.com" by pulldown-cmark
522 headers.safety |= in_heading && text.trim() == "Safety";
523 headers.errors |= in_heading && text.trim() == "Errors";
524 headers.panics |= in_heading && text.trim() == "Panics";
525 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
529 let (begin, span) = spans[index];
532 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
533 check_code(cx, &text, edition, span);
536 // Adjust for the beginning of the current `Event`
537 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
539 check_text(cx, valid_idents, &text, span);
547 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
548 fn has_needless_main(code: &str, edition: Edition) -> bool {
549 rustc_driver::catch_fatal_errors(|| {
550 rustc_span::with_session_globals(edition, || {
551 let filename = FileName::anon_source_code(code);
553 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
554 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
555 let handler = Handler::with_emitter(false, None, box emitter);
556 let sess = ParseSess::with_span_handler(handler, sm);
558 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
561 for mut err in errs {
568 let mut relevant_main_found = false;
570 match parser.parse_item(ForceCollect::No) {
571 Ok(Some(item)) => match &item.kind {
572 // Tests with one of these items are ignored
574 | ItemKind::Const(..)
575 | ItemKind::ExternCrate(..)
576 | ItemKind::ForeignMod(..) => return false,
577 // We found a main function ...
578 ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => {
579 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
580 let returns_nothing = match &sig.decl.output {
581 FnRetTy::Default(..) => true,
582 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
586 if returns_nothing && !is_async && !block.stmts.is_empty() {
587 // This main function should be linted, but only if there are no other functions
588 relevant_main_found = true;
590 // This main function should not be linted, we're done
594 // Another function was found; this case is ignored too
595 ItemKind::Fn(..) => return false,
613 if has_needless_main(text, edition) {
614 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
618 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
619 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
620 // Trim punctuation as in `some comment (see foo::bar).`
622 // Or even as in `_foo bar_` which is emphasized.
623 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
625 if valid_idents.contains(word) {
629 // Adjust for the current word
630 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
631 let span = Span::new(
632 span.lo() + BytePos::from_usize(offset),
633 span.lo() + BytePos::from_usize(offset + word.len()),
637 check_word(cx, word, span);
641 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
642 /// Checks if a string is camel-case, i.e., contains at least two uppercase
643 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
644 /// Plurals are also excluded (`IDs` is ok).
645 fn is_camel_case(s: &str) -> bool {
646 if s.starts_with(|c: char| c.is_digit(10)) {
650 let s = s.strip_suffix('s').unwrap_or(s);
652 s.chars().all(char::is_alphanumeric)
653 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
654 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
657 fn has_underscore(s: &str) -> bool {
658 s != "_" && !s.contains("\\_") && s.contains('_')
661 fn has_hyphen(s: &str) -> bool {
662 s != "-" && s.contains('-')
665 if let Ok(url) = Url::parse(word) {
666 // try to get around the fact that `foo::bar` parses as a valid URL
667 if !url.cannot_be_a_base() {
672 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
679 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
680 if has_underscore(word) && has_hyphen(word) {
684 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
689 &format!("you should put `{}` between ticks in the documentation", word),
694 struct FindPanicUnwrap<'a, 'tcx> {
695 cx: &'a LateContext<'tcx>,
696 panic_span: Option<Span>,
697 typeck_results: &'tcx ty::TypeckResults<'tcx>,
700 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
701 type Map = Map<'tcx>;
703 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
704 if self.panic_span.is_some() {
708 // check for `begin_panic`
710 if let ExprKind::Call(ref func_expr, _) = expr.kind;
711 if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind;
712 if let Some(path_def_id) = path.res.opt_def_id();
713 if match_panic_def_id(self.cx, path_def_id);
714 if is_expn_of(expr.span, "unreachable").is_none();
716 self.panic_span = Some(expr.span);
720 // check for `unwrap`
721 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
722 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
723 if is_type_diagnostic_item(self.cx, reciever_ty, sym::option_type)
724 || is_type_diagnostic_item(self.cx, reciever_ty, sym::result_type)
726 self.panic_span = Some(expr.span);
730 // and check sub-expressions
731 intravisit::walk_expr(self, expr);
734 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
735 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())