1 use clippy_utils::attrs::is_doc_hidden;
2 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_note};
3 use clippy_utils::source::first_line_of_span;
4 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
5 use clippy_utils::{is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty};
6 use if_chain::if_chain;
7 use itertools::Itertools;
8 use rustc_ast::ast::{Async, AttrKind, Attribute, FnKind, FnRetTy, ItemKind};
9 use rustc_ast::token::CommentKind;
10 use rustc_data_structures::fx::FxHashSet;
11 use rustc_data_structures::sync::Lrc;
12 use rustc_errors::emitter::EmitterWriter;
13 use rustc_errors::Handler;
15 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
16 use rustc_hir::{AnonConst, Expr, ExprKind, QPath};
17 use rustc_lint::{LateContext, LateLintPass};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::lint::in_external_macro;
21 use rustc_parse::maybe_new_parser_from_source_str;
22 use rustc_parse::parser::ForceCollect;
23 use rustc_session::parse::ParseSess;
24 use rustc_session::{declare_tool_lint, impl_lint_pass};
25 use rustc_span::def_id::LocalDefId;
26 use rustc_span::edition::Edition;
27 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
28 use rustc_span::{sym, FileName, Pos};
34 declare_clippy_lint! {
36 /// Checks for the presence of `_`, `::` or camel-case words
37 /// outside ticks in documentation.
39 /// ### Why is this bad?
40 /// *Rustdoc* supports markdown formatting, `_`, `::` and
41 /// camel-case probably indicates some code which should be included between
42 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
45 /// ### Known problems
46 /// Lots of bad docs won’t be fixed, what the lint checks
47 /// for is limited, and there are still false positives. HTML elements and their
48 /// content are not linted.
50 /// In addition, when writing documentation comments, including `[]` brackets
51 /// inside a link text would trip the parser. Therfore, documenting link with
52 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
57 /// /// Do something with the foo_bar parameter. See also
58 /// /// that::other::module::foo.
59 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
60 /// fn doit(foo_bar: usize) {}
64 /// // Link text with `[]` brackets should be written as following:
65 /// /// Consume the array and return the inner
66 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
67 /// /// [SmallVec]: SmallVec
72 "presence of `_`, `::` or camel-case outside backticks in documentation"
75 declare_clippy_lint! {
77 /// Checks for the doc comments of publicly visible
78 /// unsafe functions and warns if there is no `# Safety` section.
80 /// ### Why is this bad?
81 /// Unsafe functions should document their safety
82 /// preconditions, so that users can be sure they are using them safely.
86 ///# type Universe = ();
87 /// /// This function should really be documented
88 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
93 /// At least write a line about safety:
96 ///# type Universe = ();
99 /// /// This function should not be called before the horsemen are ready.
100 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
101 /// unimplemented!();
104 pub MISSING_SAFETY_DOC,
106 "`pub unsafe fn` without `# Safety` docs"
109 declare_clippy_lint! {
111 /// Checks the doc comments of publicly visible functions that
112 /// return a `Result` type and warns if there is no `# Errors` section.
114 /// ### Why is this bad?
115 /// Documenting the type of errors that can be returned from a
116 /// function can help callers write code to handle the errors appropriately.
119 /// Since the following function returns a `Result` it has an `# Errors` section in
126 /// /// Will return `Err` if `filename` does not exist or the user does not have
127 /// /// permission to read it.
128 /// pub fn read(filename: String) -> io::Result<String> {
129 /// unimplemented!();
132 pub MISSING_ERRORS_DOC,
134 "`pub fn` returns `Result` without `# Errors` in doc comment"
137 declare_clippy_lint! {
139 /// Checks the doc comments of publicly visible functions that
140 /// may panic and warns if there is no `# Panics` section.
142 /// ### Why is this bad?
143 /// Documenting the scenarios in which panicking occurs
144 /// can help callers who do not want to panic to avoid those situations.
147 /// Since the following function may panic it has a `# Panics` section in
153 /// /// Will panic if y is 0
154 /// pub fn divide_by(x: i32, y: i32) -> i32 {
156 /// panic!("Cannot divide by 0")
162 pub MISSING_PANICS_DOC,
164 "`pub fn` may panic without `# Panics` in doc comment"
167 declare_clippy_lint! {
169 /// Checks for `fn main() { .. }` in doctests
171 /// ### Why is this bad?
172 /// The test can be shorter (and likely more readable)
173 /// if the `fn main()` is left implicit.
177 /// /// An example of a doctest with a `main()` function
183 /// /// // this needs not be in an `fn`
186 /// fn needless_main() {
187 /// unimplemented!();
190 pub NEEDLESS_DOCTEST_MAIN,
192 "presence of `fn main() {` in code examples"
195 #[allow(clippy::module_name_repetitions)]
197 pub struct DocMarkdown {
198 valid_idents: FxHashSet<String>,
203 pub fn new(valid_idents: FxHashSet<String>) -> Self {
206 in_trait_impl: false,
211 impl_lint_pass!(DocMarkdown =>
212 [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, NEEDLESS_DOCTEST_MAIN]
215 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
216 fn check_crate(&mut self, cx: &LateContext<'tcx>) {
217 let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID);
218 check_attrs(cx, &self.valid_idents, attrs);
221 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
222 let attrs = cx.tcx.hir().attrs(item.hir_id());
223 let headers = check_attrs(cx, &self.valid_idents, attrs);
225 hir::ItemKind::Fn(ref sig, _, body_id) => {
226 if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) {
227 let body = cx.tcx.hir().body(body_id);
228 let mut fpu = FindPanicUnwrap {
230 typeck_results: cx.tcx.typeck(item.def_id),
233 fpu.visit_expr(&body.value);
234 lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span);
237 hir::ItemKind::Impl(ref impl_) => {
238 self.in_trait_impl = impl_.of_trait.is_some();
240 hir::ItemKind::Trait(_, unsafety, ..) => {
241 if !headers.safety && unsafety == hir::Unsafety::Unsafe {
246 "docs for unsafe trait missing `# Safety` section",
254 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
255 if let hir::ItemKind::Impl { .. } = item.kind {
256 self.in_trait_impl = false;
260 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
261 let attrs = cx.tcx.hir().attrs(item.hir_id());
262 let headers = check_attrs(cx, &self.valid_idents, attrs);
263 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
264 if !in_external_macro(cx.tcx.sess, item.span) {
265 lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, None, None);
270 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
271 let attrs = cx.tcx.hir().attrs(item.hir_id());
272 let headers = check_attrs(cx, &self.valid_idents, attrs);
273 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
276 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
277 let body = cx.tcx.hir().body(body_id);
278 let mut fpu = FindPanicUnwrap {
280 typeck_results: cx.tcx.typeck(item.def_id),
283 fpu.visit_expr(&body.value);
284 lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span);
289 fn lint_for_missing_headers<'tcx>(
290 cx: &LateContext<'tcx>,
292 span: impl Into<MultiSpan> + Copy,
293 sig: &hir::FnSig<'_>,
295 body_id: Option<hir::BodyId>,
296 panic_span: Option<Span>,
298 if !cx.access_levels.is_exported(def_id) {
299 return; // Private functions do not require doc comments
302 // do not lint if any parent has `#[doc(hidden)]` attribute (#7347)
306 .parent_iter(cx.tcx.hir().local_def_id_to_hir_id(def_id))
307 .any(|(id, _node)| is_doc_hidden(cx.tcx.hir().attrs(id)))
312 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
317 "unsafe function's docs miss `# Safety` section",
320 if !headers.panics && panic_span.is_some() {
325 "docs for function which may panic missing `# Panics` section",
327 "first possible panic found here",
331 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
332 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::Result) {
337 "docs for function returning `Result` missing `# Errors` section",
341 if let Some(body_id) = body_id;
342 if let Some(future) = cx.tcx.lang_items().future_trait();
343 let typeck = cx.tcx.typeck_body(body_id);
344 let body = cx.tcx.hir().body(body_id);
345 let ret_ty = typeck.expr_ty(&body.value);
346 if implements_trait(cx, ret_ty, future, &[]);
347 if let ty::Opaque(_, subs) = ret_ty.kind();
348 if let Some(gen) = subs.types().next();
349 if let ty::Generator(_, subs, _) = gen.kind();
350 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::Result);
356 "docs for function returning `Result` missing `# Errors` section",
364 /// Cleanup documentation decoration.
366 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
367 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
368 /// need to keep track of
369 /// the spans but this function is inspired from the later.
370 #[allow(clippy::cast_possible_truncation)]
372 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
373 // one-line comments lose their prefix
374 if comment_kind == CommentKind::Line {
375 let mut doc = doc.to_owned();
378 // +3 skips the opening delimiter
379 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
382 let mut sizes = vec![];
383 let mut contains_initial_stars = false;
384 for line in doc.lines() {
385 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
386 debug_assert_eq!(offset as u32 as usize, offset);
387 contains_initial_stars |= line.trim_start().starts_with('*');
388 // +1 adds the newline, +3 skips the opening delimiter
389 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
391 if !contains_initial_stars {
392 return (doc.to_string(), sizes);
394 // remove the initial '*'s if any
395 let mut no_stars = String::with_capacity(doc.len());
396 for line in doc.lines() {
397 let mut chars = line.chars();
398 for c in &mut chars {
399 if c.is_whitespace() {
402 no_stars.push(if c == '*' { ' ' } else { c });
406 no_stars.push_str(chars.as_str());
413 #[derive(Copy, Clone)]
420 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
421 use pulldown_cmark::{BrokenLink, CowStr, Options};
422 /// We don't want the parser to choke on intra doc links. Since we don't
423 /// actually care about rendering them, just pretend that all broken links are
424 /// point to a fake address.
425 #[allow(clippy::unnecessary_wraps)] // we're following a type signature
426 fn fake_broken_link_callback<'a>(_: BrokenLink<'_>) -> Option<(CowStr<'a>, CowStr<'a>)> {
427 Some(("fake".into(), "fake".into()))
430 let mut doc = String::new();
431 let mut spans = vec![];
434 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
435 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
436 spans.extend_from_slice(¤t_spans);
437 doc.push_str(&comment);
438 } else if attr.has_name(sym::doc) {
439 // ignore mix of sugared and non-sugared doc
440 // don't trigger the safety or errors check
450 for &mut (ref mut offset, _) in &mut spans {
451 let offset_copy = *offset;
453 current += offset_copy;
464 let mut cb = fake_broken_link_callback;
467 pulldown_cmark::Parser::new_with_broken_link_callback(&doc, Options::empty(), Some(&mut cb)).into_offset_iter();
468 // Iterate over all `Events` and combine consecutive events into one
469 let events = parser.coalesce(|previous, current| {
470 use pulldown_cmark::Event::Text;
472 let previous_range = previous.1;
473 let current_range = current.1;
475 match (previous.0, current.0) {
476 (Text(previous), Text(current)) => {
477 let mut previous = previous.to_string();
478 previous.push_str(¤t);
479 Ok((Text(previous.into()), previous_range))
481 (previous, current) => Err(((previous, previous_range), (current, current_range))),
484 check_doc(cx, valid_idents, events, &spans)
487 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
489 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
490 cx: &LateContext<'_>,
491 valid_idents: &FxHashSet<String>,
493 spans: &[(usize, Span)],
495 // true if a safety header was found
496 use pulldown_cmark::Event::{
497 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
499 use pulldown_cmark::Tag::{CodeBlock, Heading, Item, Link, Paragraph};
500 use pulldown_cmark::{CodeBlockKind, CowStr};
502 let mut headers = DocHeaders {
507 let mut in_code = false;
508 let mut in_link = None;
509 let mut in_heading = false;
510 let mut is_rust = false;
511 let mut edition = None;
512 let mut ticks_unbalanced = false;
513 let mut text_to_check: Vec<(CowStr<'_>, Span)> = Vec::new();
514 let mut paragraph_span = spans.get(0).expect("function isn't called if doc comment is empty").1;
515 for (event, range) in events {
517 Start(CodeBlock(ref kind)) => {
519 if let CodeBlockKind::Fenced(lang) = kind {
520 for item in lang.split(',') {
521 if item == "ignore" {
525 if let Some(stripped) = item.strip_prefix("edition") {
527 edition = stripped.parse::<Edition>().ok();
528 } else if item.is_empty() || RUST_CODE.contains(&item) {
534 End(CodeBlock(_)) => {
538 Start(Link(_, url, _)) => in_link = Some(url),
539 End(Link(..)) => in_link = None,
540 Start(Heading(_) | Paragraph | Item) => {
541 if let Start(Heading(_)) = event {
544 ticks_unbalanced = false;
545 let (_, span) = get_current_span(spans, range.start);
546 paragraph_span = first_line_of_span(cx, span);
548 End(Heading(_) | Paragraph | Item) => {
549 if let End(Heading(_)) = event {
552 if ticks_unbalanced {
557 "backticks are unbalanced",
559 "a backtick may be missing a pair",
562 for (text, span) in text_to_check {
563 check_text(cx, valid_idents, &text, span);
566 text_to_check = Vec::new();
568 Start(_tag) | End(_tag) => (), // We don't care about other tags
569 Html(_html) => (), // HTML is weird, just ignore it
570 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
571 FootnoteReference(text) | Text(text) => {
572 let (begin, span) = get_current_span(spans, range.start);
573 paragraph_span = paragraph_span.with_hi(span.hi());
574 ticks_unbalanced |= text.contains('`') && !in_code;
575 if Some(&text) == in_link.as_ref() || ticks_unbalanced {
576 // Probably a link of the form `<http://example.com>`
577 // Which are represented as a link to "http://example.com" with
578 // text "http://example.com" by pulldown-cmark
581 headers.safety |= in_heading && text.trim() == "Safety";
582 headers.errors |= in_heading && text.trim() == "Errors";
583 headers.panics |= in_heading && text.trim() == "Panics";
586 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
587 check_code(cx, &text, edition, span);
590 // Adjust for the beginning of the current `Event`
591 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
592 text_to_check.push((text, span));
600 fn get_current_span(spans: &[(usize, Span)], idx: usize) -> (usize, Span) {
601 let index = match spans.binary_search_by(|c| c.0.cmp(&idx)) {
608 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
609 fn has_needless_main(code: String, edition: Edition) -> bool {
610 rustc_driver::catch_fatal_errors(|| {
611 rustc_span::create_session_globals_then(edition, || {
612 let filename = FileName::anon_source_code(&code);
614 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
615 let emitter = EmitterWriter::new(Box::new(io::sink()), None, false, false, false, None, false);
616 let handler = Handler::with_emitter(false, None, Box::new(emitter));
617 let sess = ParseSess::with_span_handler(handler, sm);
619 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) {
622 for mut err in errs {
629 let mut relevant_main_found = false;
631 match parser.parse_item(ForceCollect::No) {
632 Ok(Some(item)) => match &item.kind {
633 // Tests with one of these items are ignored
635 | ItemKind::Const(..)
636 | ItemKind::ExternCrate(..)
637 | ItemKind::ForeignMod(..) => return false,
638 // We found a main function ...
639 ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => {
640 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
641 let returns_nothing = match &sig.decl.output {
642 FnRetTy::Default(..) => true,
643 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
644 FnRetTy::Ty(_) => false,
647 if returns_nothing && !is_async && !block.stmts.is_empty() {
648 // This main function should be linted, but only if there are no other functions
649 relevant_main_found = true;
651 // This main function should not be linted, we're done
655 // Another function was found; this case is ignored too
656 ItemKind::Fn(..) => return false,
674 // Because of the global session, we need to create a new session in a different thread with
675 // the edition we need.
676 let text = text.to_owned();
677 if thread::spawn(move || has_needless_main(text, edition))
679 .expect("thread::spawn failed")
681 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
685 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
686 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
687 // Trim punctuation as in `some comment (see foo::bar).`
689 // Or even as in `_foo bar_` which is emphasized.
690 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
692 if valid_idents.contains(word) {
696 // Adjust for the current word
697 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
698 let span = Span::new(
699 span.lo() + BytePos::from_usize(offset),
700 span.lo() + BytePos::from_usize(offset + word.len()),
705 check_word(cx, word, span);
709 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
710 /// Checks if a string is camel-case, i.e., contains at least two uppercase
711 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
712 /// Plurals are also excluded (`IDs` is ok).
713 fn is_camel_case(s: &str) -> bool {
714 if s.starts_with(|c: char| c.is_digit(10)) {
718 let s = s.strip_suffix('s').unwrap_or(s);
720 s.chars().all(char::is_alphanumeric)
721 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
722 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
725 fn has_underscore(s: &str) -> bool {
726 s != "_" && !s.contains("\\_") && s.contains('_')
729 fn has_hyphen(s: &str) -> bool {
730 s != "-" && s.contains('-')
733 if let Ok(url) = Url::parse(word) {
734 // try to get around the fact that `foo::bar` parses as a valid URL
735 if !url.cannot_be_a_base() {
740 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
747 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
748 if has_underscore(word) && has_hyphen(word) {
752 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
757 &format!("you should put `{}` between ticks in the documentation", word),
762 struct FindPanicUnwrap<'a, 'tcx> {
763 cx: &'a LateContext<'tcx>,
764 panic_span: Option<Span>,
765 typeck_results: &'tcx ty::TypeckResults<'tcx>,
768 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
769 type Map = Map<'tcx>;
771 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
772 if self.panic_span.is_some() {
776 // check for `begin_panic`
778 if let ExprKind::Call(func_expr, _) = expr.kind;
779 if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
780 if let Some(path_def_id) = path.res.opt_def_id();
781 if match_panic_def_id(self.cx, path_def_id);
782 if is_expn_of(expr.span, "unreachable").is_none();
783 if !is_expn_of_debug_assertions(expr.span);
785 self.panic_span = Some(expr.span);
789 // check for `assert_eq` or `assert_ne`
790 if is_expn_of(expr.span, "assert_eq").is_some() || is_expn_of(expr.span, "assert_ne").is_some() {
791 self.panic_span = Some(expr.span);
794 // check for `unwrap`
795 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
796 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
797 if is_type_diagnostic_item(self.cx, reciever_ty, sym::Option)
798 || is_type_diagnostic_item(self.cx, reciever_ty, sym::Result)
800 self.panic_span = Some(expr.span);
804 // and check sub-expressions
805 intravisit::walk_expr(self, expr);
808 // Panics in const blocks will cause compilation to fail.
809 fn visit_anon_const(&mut self, _: &'tcx AnonConst) {}
811 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
812 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
816 fn is_expn_of_debug_assertions(span: Span) -> bool {
817 const MACRO_NAMES: &[&str] = &["debug_assert", "debug_assert_eq", "debug_assert_ne"];
818 MACRO_NAMES.iter().any(|name| is_expn_of(span, name).is_some())