1 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_note};
2 use clippy_utils::source::first_line_of_span;
3 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
4 use clippy_utils::{is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty};
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::{AnonConst, 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::def_id::LocalDefId;
25 use rustc_span::edition::Edition;
26 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
27 use rustc_span::{sym, FileName, Pos};
33 declare_clippy_lint! {
35 /// Checks for the presence of `_`, `::` or camel-case words
36 /// outside ticks in documentation.
38 /// ### Why is this bad?
39 /// *Rustdoc* supports markdown formatting, `_`, `::` and
40 /// camel-case probably indicates some code which should be included between
41 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
44 /// ### Known problems
45 /// Lots of bad docs won’t be fixed, what the lint checks
46 /// for is limited, and there are still false positives. HTML elements and their
47 /// content are not linted.
49 /// In addition, when writing documentation comments, including `[]` brackets
50 /// inside a link text would trip the parser. Therfore, documenting link with
51 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
56 /// /// Do something with the foo_bar parameter. See also
57 /// /// that::other::module::foo.
58 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
59 /// fn doit(foo_bar: usize) {}
63 /// // Link text with `[]` brackets should be written as following:
64 /// /// Consume the array and return the inner
65 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
66 /// /// [SmallVec]: SmallVec
71 "presence of `_`, `::` or camel-case outside backticks in documentation"
74 declare_clippy_lint! {
76 /// Checks for the doc comments of publicly visible
77 /// unsafe functions and warns if there is no `# Safety` section.
79 /// ### Why is this bad?
80 /// Unsafe functions should document their safety
81 /// preconditions, so that users can be sure they are using them safely.
85 ///# type Universe = ();
86 /// /// This function should really be documented
87 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
92 /// At least write a line about safety:
95 ///# type Universe = ();
98 /// /// This function should not be called before the horsemen are ready.
99 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
100 /// unimplemented!();
103 pub MISSING_SAFETY_DOC,
105 "`pub unsafe fn` without `# Safety` docs"
108 declare_clippy_lint! {
110 /// Checks the doc comments of publicly visible functions that
111 /// return a `Result` type and warns if there is no `# Errors` section.
113 /// ### Why is this bad?
114 /// Documenting the type of errors that can be returned from a
115 /// function can help callers write code to handle the errors appropriately.
118 /// Since the following function returns a `Result` it has an `# Errors` section in
125 /// /// Will return `Err` if `filename` does not exist or the user does not have
126 /// /// permission to read it.
127 /// pub fn read(filename: String) -> io::Result<String> {
128 /// unimplemented!();
131 pub MISSING_ERRORS_DOC,
133 "`pub fn` returns `Result` without `# Errors` in doc comment"
136 declare_clippy_lint! {
138 /// Checks the doc comments of publicly visible functions that
139 /// may panic and warns if there is no `# Panics` section.
141 /// ### Why is this bad?
142 /// Documenting the scenarios in which panicking occurs
143 /// can help callers who do not want to panic to avoid those situations.
146 /// Since the following function may panic it has a `# Panics` section in
152 /// /// Will panic if y is 0
153 /// pub fn divide_by(x: i32, y: i32) -> i32 {
155 /// panic!("Cannot divide by 0")
161 pub MISSING_PANICS_DOC,
163 "`pub fn` may panic without `# Panics` in doc comment"
166 declare_clippy_lint! {
168 /// Checks for `fn main() { .. }` in doctests
170 /// ### Why is this bad?
171 /// The test can be shorter (and likely more readable)
172 /// if the `fn main()` is left implicit.
176 /// /// An example of a doctest with a `main()` function
182 /// /// // this needs not be in an `fn`
185 /// fn needless_main() {
186 /// unimplemented!();
189 pub NEEDLESS_DOCTEST_MAIN,
191 "presence of `fn main() {` in code examples"
194 #[allow(clippy::module_name_repetitions)]
196 pub struct DocMarkdown {
197 valid_idents: FxHashSet<String>,
202 pub fn new(valid_idents: FxHashSet<String>) -> Self {
205 in_trait_impl: false,
210 impl_lint_pass!(DocMarkdown =>
211 [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, NEEDLESS_DOCTEST_MAIN]
214 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
215 fn check_crate(&mut self, cx: &LateContext<'tcx>) {
216 let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID);
217 check_attrs(cx, &self.valid_idents, attrs);
220 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
221 let attrs = cx.tcx.hir().attrs(item.hir_id());
222 let headers = check_attrs(cx, &self.valid_idents, attrs);
224 hir::ItemKind::Fn(ref sig, _, body_id) => {
225 if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) {
226 let body = cx.tcx.hir().body(body_id);
227 let mut fpu = FindPanicUnwrap {
229 typeck_results: cx.tcx.typeck(item.def_id),
232 fpu.visit_expr(&body.value);
233 lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span);
236 hir::ItemKind::Impl(ref impl_) => {
237 self.in_trait_impl = impl_.of_trait.is_some();
239 hir::ItemKind::Trait(_, unsafety, ..) => {
240 if !headers.safety && unsafety == hir::Unsafety::Unsafe {
245 "docs for unsafe trait missing `# Safety` section",
253 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
254 if let hir::ItemKind::Impl { .. } = item.kind {
255 self.in_trait_impl = false;
259 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
260 let attrs = cx.tcx.hir().attrs(item.hir_id());
261 let headers = check_attrs(cx, &self.valid_idents, attrs);
262 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
263 if !in_external_macro(cx.tcx.sess, item.span) {
264 lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, None, None);
269 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
270 let attrs = cx.tcx.hir().attrs(item.hir_id());
271 let headers = check_attrs(cx, &self.valid_idents, attrs);
272 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
275 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
276 let body = cx.tcx.hir().body(body_id);
277 let mut fpu = FindPanicUnwrap {
279 typeck_results: cx.tcx.typeck(item.def_id),
282 fpu.visit_expr(&body.value);
283 lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, Some(body_id), fpu.panic_span);
288 fn lint_for_missing_headers<'tcx>(
289 cx: &LateContext<'tcx>,
291 span: impl Into<MultiSpan> + Copy,
292 sig: &hir::FnSig<'_>,
294 body_id: Option<hir::BodyId>,
295 panic_span: Option<Span>,
297 if !cx.access_levels.is_exported(def_id) {
298 return; // Private functions do not require doc comments
300 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
305 "unsafe function's docs miss `# Safety` section",
308 if !headers.panics && panic_span.is_some() {
313 "docs for function which may panic missing `# Panics` section",
315 "first possible panic found here",
319 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
320 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::Result) {
325 "docs for function returning `Result` missing `# Errors` section",
329 if let Some(body_id) = body_id;
330 if let Some(future) = cx.tcx.lang_items().future_trait();
331 let typeck = cx.tcx.typeck_body(body_id);
332 let body = cx.tcx.hir().body(body_id);
333 let ret_ty = typeck.expr_ty(&body.value);
334 if implements_trait(cx, ret_ty, future, &[]);
335 if let ty::Opaque(_, subs) = ret_ty.kind();
336 if let Some(gen) = subs.types().next();
337 if let ty::Generator(_, subs, _) = gen.kind();
338 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::Result);
344 "docs for function returning `Result` missing `# Errors` section",
352 /// Cleanup documentation decoration.
354 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
355 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
356 /// need to keep track of
357 /// the spans but this function is inspired from the later.
358 #[allow(clippy::cast_possible_truncation)]
360 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
361 // one-line comments lose their prefix
362 if comment_kind == CommentKind::Line {
363 let mut doc = doc.to_owned();
366 // +3 skips the opening delimiter
367 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
370 let mut sizes = vec![];
371 let mut contains_initial_stars = false;
372 for line in doc.lines() {
373 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
374 debug_assert_eq!(offset as u32 as usize, offset);
375 contains_initial_stars |= line.trim_start().starts_with('*');
376 // +1 adds the newline, +3 skips the opening delimiter
377 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
379 if !contains_initial_stars {
380 return (doc.to_string(), sizes);
382 // remove the initial '*'s if any
383 let mut no_stars = String::with_capacity(doc.len());
384 for line in doc.lines() {
385 let mut chars = line.chars();
386 for c in &mut chars {
387 if c.is_whitespace() {
390 no_stars.push(if c == '*' { ' ' } else { c });
394 no_stars.push_str(chars.as_str());
401 #[derive(Copy, Clone)]
408 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
409 use pulldown_cmark::{BrokenLink, CowStr, Options};
410 /// We don't want the parser to choke on intra doc links. Since we don't
411 /// actually care about rendering them, just pretend that all broken links are
412 /// point to a fake address.
413 #[allow(clippy::unnecessary_wraps)] // we're following a type signature
414 fn fake_broken_link_callback<'a>(_: BrokenLink<'_>) -> Option<(CowStr<'a>, CowStr<'a>)> {
415 Some(("fake".into(), "fake".into()))
418 let mut doc = String::new();
419 let mut spans = vec![];
422 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
423 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
424 spans.extend_from_slice(¤t_spans);
425 doc.push_str(&comment);
426 } else if attr.has_name(sym::doc) {
427 // ignore mix of sugared and non-sugared doc
428 // don't trigger the safety or errors check
438 for &mut (ref mut offset, _) in &mut spans {
439 let offset_copy = *offset;
441 current += offset_copy;
452 let mut cb = fake_broken_link_callback;
455 pulldown_cmark::Parser::new_with_broken_link_callback(&doc, Options::empty(), Some(&mut cb)).into_offset_iter();
456 // Iterate over all `Events` and combine consecutive events into one
457 let events = parser.coalesce(|previous, current| {
458 use pulldown_cmark::Event::Text;
460 let previous_range = previous.1;
461 let current_range = current.1;
463 match (previous.0, current.0) {
464 (Text(previous), Text(current)) => {
465 let mut previous = previous.to_string();
466 previous.push_str(¤t);
467 Ok((Text(previous.into()), previous_range))
469 (previous, current) => Err(((previous, previous_range), (current, current_range))),
472 check_doc(cx, valid_idents, events, &spans)
475 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
477 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
478 cx: &LateContext<'_>,
479 valid_idents: &FxHashSet<String>,
481 spans: &[(usize, Span)],
483 // true if a safety header was found
484 use pulldown_cmark::Event::{
485 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
487 use pulldown_cmark::Tag::{CodeBlock, Heading, Item, Link, Paragraph};
488 use pulldown_cmark::{CodeBlockKind, CowStr};
490 let mut headers = DocHeaders {
495 let mut in_code = false;
496 let mut in_link = None;
497 let mut in_heading = false;
498 let mut is_rust = false;
499 let mut edition = None;
500 let mut ticks_unbalanced = false;
501 let mut text_to_check: Vec<(CowStr<'_>, Span)> = Vec::new();
502 let mut paragraph_span = spans.get(0).expect("function isn't called if doc comment is empty").1;
503 for (event, range) in events {
505 Start(CodeBlock(ref kind)) => {
507 if let CodeBlockKind::Fenced(lang) = kind {
508 for item in lang.split(',') {
509 if item == "ignore" {
513 if let Some(stripped) = item.strip_prefix("edition") {
515 edition = stripped.parse::<Edition>().ok();
516 } else if item.is_empty() || RUST_CODE.contains(&item) {
522 End(CodeBlock(_)) => {
526 Start(Link(_, url, _)) => in_link = Some(url),
527 End(Link(..)) => in_link = None,
528 Start(Heading(_) | Paragraph | Item) => {
529 if let Start(Heading(_)) = event {
532 ticks_unbalanced = false;
533 let (_, span) = get_current_span(spans, range.start);
534 paragraph_span = first_line_of_span(cx, span);
536 End(Heading(_) | Paragraph | Item) => {
537 if let End(Heading(_)) = event {
540 if ticks_unbalanced {
545 "backticks are unbalanced",
547 "a backtick may be missing a pair",
550 for (text, span) in text_to_check {
551 check_text(cx, valid_idents, &text, span);
554 text_to_check = Vec::new();
556 Start(_tag) | End(_tag) => (), // We don't care about other tags
557 Html(_html) => (), // HTML is weird, just ignore it
558 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
559 FootnoteReference(text) | Text(text) => {
560 let (begin, span) = get_current_span(spans, range.start);
561 paragraph_span = paragraph_span.with_hi(span.hi());
562 ticks_unbalanced |= text.contains('`') && !in_code;
563 if Some(&text) == in_link.as_ref() || ticks_unbalanced {
564 // Probably a link of the form `<http://example.com>`
565 // Which are represented as a link to "http://example.com" with
566 // text "http://example.com" by pulldown-cmark
569 headers.safety |= in_heading && text.trim() == "Safety";
570 headers.errors |= in_heading && text.trim() == "Errors";
571 headers.panics |= in_heading && text.trim() == "Panics";
574 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
575 check_code(cx, &text, edition, span);
578 // Adjust for the beginning of the current `Event`
579 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
580 text_to_check.push((text, span));
588 fn get_current_span(spans: &[(usize, Span)], idx: usize) -> (usize, Span) {
589 let index = match spans.binary_search_by(|c| c.0.cmp(&idx)) {
596 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
597 fn has_needless_main(code: String, edition: Edition) -> bool {
598 rustc_driver::catch_fatal_errors(|| {
599 rustc_span::create_session_globals_then(edition, || {
600 let filename = FileName::anon_source_code(&code);
602 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
603 let emitter = EmitterWriter::new(Box::new(io::sink()), None, false, false, false, None, false);
604 let handler = Handler::with_emitter(false, None, Box::new(emitter));
605 let sess = ParseSess::with_span_handler(handler, sm);
607 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) {
610 for mut err in errs {
617 let mut relevant_main_found = false;
619 match parser.parse_item(ForceCollect::No) {
620 Ok(Some(item)) => match &item.kind {
621 // Tests with one of these items are ignored
623 | ItemKind::Const(..)
624 | ItemKind::ExternCrate(..)
625 | ItemKind::ForeignMod(..) => return false,
626 // We found a main function ...
627 ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => {
628 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
629 let returns_nothing = match &sig.decl.output {
630 FnRetTy::Default(..) => true,
631 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
632 FnRetTy::Ty(_) => false,
635 if returns_nothing && !is_async && !block.stmts.is_empty() {
636 // This main function should be linted, but only if there are no other functions
637 relevant_main_found = true;
639 // This main function should not be linted, we're done
643 // Another function was found; this case is ignored too
644 ItemKind::Fn(..) => return false,
662 // Because of the global session, we need to create a new session in a different thread with
663 // the edition we need.
664 let text = text.to_owned();
665 if thread::spawn(move || has_needless_main(text, edition))
667 .expect("thread::spawn failed")
669 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
673 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
674 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
675 // Trim punctuation as in `some comment (see foo::bar).`
677 // Or even as in `_foo bar_` which is emphasized.
678 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
680 if valid_idents.contains(word) {
684 // Adjust for the current word
685 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
686 let span = Span::new(
687 span.lo() + BytePos::from_usize(offset),
688 span.lo() + BytePos::from_usize(offset + word.len()),
693 check_word(cx, word, span);
697 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
698 /// Checks if a string is camel-case, i.e., contains at least two uppercase
699 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
700 /// Plurals are also excluded (`IDs` is ok).
701 fn is_camel_case(s: &str) -> bool {
702 if s.starts_with(|c: char| c.is_digit(10)) {
706 let s = s.strip_suffix('s').unwrap_or(s);
708 s.chars().all(char::is_alphanumeric)
709 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
710 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
713 fn has_underscore(s: &str) -> bool {
714 s != "_" && !s.contains("\\_") && s.contains('_')
717 fn has_hyphen(s: &str) -> bool {
718 s != "-" && s.contains('-')
721 if let Ok(url) = Url::parse(word) {
722 // try to get around the fact that `foo::bar` parses as a valid URL
723 if !url.cannot_be_a_base() {
728 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
735 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
736 if has_underscore(word) && has_hyphen(word) {
740 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
745 &format!("you should put `{}` between ticks in the documentation", word),
750 struct FindPanicUnwrap<'a, 'tcx> {
751 cx: &'a LateContext<'tcx>,
752 panic_span: Option<Span>,
753 typeck_results: &'tcx ty::TypeckResults<'tcx>,
756 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
757 type Map = Map<'tcx>;
759 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
760 if self.panic_span.is_some() {
764 // check for `begin_panic`
766 if let ExprKind::Call(func_expr, _) = expr.kind;
767 if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
768 if let Some(path_def_id) = path.res.opt_def_id();
769 if match_panic_def_id(self.cx, path_def_id);
770 if is_expn_of(expr.span, "unreachable").is_none();
771 if !is_expn_of_debug_assertions(expr.span);
773 self.panic_span = Some(expr.span);
777 // check for `assert_eq` or `assert_ne`
778 if is_expn_of(expr.span, "assert_eq").is_some() || is_expn_of(expr.span, "assert_ne").is_some() {
779 self.panic_span = Some(expr.span);
782 // check for `unwrap`
783 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
784 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
785 if is_type_diagnostic_item(self.cx, reciever_ty, sym::Option)
786 || is_type_diagnostic_item(self.cx, reciever_ty, sym::Result)
788 self.panic_span = Some(expr.span);
792 // and check sub-expressions
793 intravisit::walk_expr(self, expr);
796 // Panics in const blocks will cause compilation to fail.
797 fn visit_anon_const(&mut self, _: &'tcx AnonConst) {}
799 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
800 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
804 fn is_expn_of_debug_assertions(span: Span) -> bool {
805 const MACRO_NAMES: &[&str] = &["debug_assert", "debug_assert_eq", "debug_assert_ne"];
806 MACRO_NAMES.iter().any(|name| is_expn_of(span, name).is_some())