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::edition::Edition;
25 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
26 use rustc_span::{sym, FileName, Pos};
32 declare_clippy_lint! {
34 /// Checks for the presence of `_`, `::` or camel-case words
35 /// outside ticks in documentation.
37 /// ### Why is this bad?
38 /// *Rustdoc* supports markdown formatting, `_`, `::` and
39 /// camel-case probably indicates some code which should be included between
40 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
43 /// ### Known problems
44 /// Lots of bad docs won’t be fixed, what the lint checks
45 /// for is limited, and there are still false positives. HTML elements and their
46 /// content are not linted.
48 /// In addition, when writing documentation comments, including `[]` brackets
49 /// inside a link text would trip the parser. Therfore, documenting link with
50 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
55 /// /// Do something with the foo_bar parameter. See also
56 /// /// that::other::module::foo.
57 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
58 /// fn doit(foo_bar: usize) {}
62 /// // Link text with `[]` brackets should be written as following:
63 /// /// Consume the array and return the inner
64 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
65 /// /// [SmallVec]: SmallVec
70 "presence of `_`, `::` or camel-case outside backticks in documentation"
73 declare_clippy_lint! {
75 /// Checks for the doc comments of publicly visible
76 /// unsafe functions and warns if there is no `# Safety` section.
78 /// ### Why is this bad?
79 /// Unsafe functions should document their safety
80 /// preconditions, so that users can be sure they are using them safely.
84 ///# type Universe = ();
85 /// /// This function should really be documented
86 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
91 /// At least write a line about safety:
94 ///# type Universe = ();
97 /// /// This function should not be called before the horsemen are ready.
98 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
102 pub MISSING_SAFETY_DOC,
104 "`pub unsafe fn` without `# Safety` docs"
107 declare_clippy_lint! {
109 /// Checks the doc comments of publicly visible functions that
110 /// return a `Result` type and warns if there is no `# Errors` section.
112 /// ### Why is this bad?
113 /// Documenting the type of errors that can be returned from a
114 /// function can help callers write code to handle the errors appropriately.
117 /// Since the following function returns a `Result` it has an `# Errors` section in
124 /// /// Will return `Err` if `filename` does not exist or the user does not have
125 /// /// permission to read it.
126 /// pub fn read(filename: String) -> io::Result<String> {
127 /// unimplemented!();
130 pub MISSING_ERRORS_DOC,
132 "`pub fn` returns `Result` without `# Errors` in doc comment"
135 declare_clippy_lint! {
137 /// Checks the doc comments of publicly visible functions that
138 /// may panic and warns if there is no `# Panics` section.
140 /// ### Why is this bad?
141 /// Documenting the scenarios in which panicking occurs
142 /// can help callers who do not want to panic to avoid those situations.
145 /// Since the following function may panic it has a `# Panics` section in
151 /// /// Will panic if y is 0
152 /// pub fn divide_by(x: i32, y: i32) -> i32 {
154 /// panic!("Cannot divide by 0")
160 pub MISSING_PANICS_DOC,
162 "`pub fn` may panic without `# Panics` in doc comment"
165 declare_clippy_lint! {
167 /// Checks for `fn main() { .. }` in doctests
169 /// ### Why is this bad?
170 /// The test can be shorter (and likely more readable)
171 /// if the `fn main()` is left implicit.
175 /// /// An example of a doctest with a `main()` function
181 /// /// // this needs not be in an `fn`
184 /// fn needless_main() {
185 /// unimplemented!();
188 pub NEEDLESS_DOCTEST_MAIN,
190 "presence of `fn main() {` in code examples"
193 #[allow(clippy::module_name_repetitions)]
195 pub struct DocMarkdown {
196 valid_idents: FxHashSet<String>,
201 pub fn new(valid_idents: FxHashSet<String>) -> Self {
204 in_trait_impl: false,
209 impl_lint_pass!(DocMarkdown =>
210 [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, NEEDLESS_DOCTEST_MAIN]
213 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
214 fn check_crate(&mut self, cx: &LateContext<'tcx>, _: &'tcx hir::Crate<'_>) {
215 let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID);
216 check_attrs(cx, &self.valid_idents, attrs);
219 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
220 let attrs = cx.tcx.hir().attrs(item.hir_id());
221 let headers = check_attrs(cx, &self.valid_idents, attrs);
223 hir::ItemKind::Fn(ref sig, _, body_id) => {
224 if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) {
225 let body = cx.tcx.hir().body(body_id);
226 let mut fpu = FindPanicUnwrap {
228 typeck_results: cx.tcx.typeck(item.def_id),
231 fpu.visit_expr(&body.value);
232 lint_for_missing_headers(
243 hir::ItemKind::Impl(ref impl_) => {
244 self.in_trait_impl = impl_.of_trait.is_some();
250 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
251 if let hir::ItemKind::Impl { .. } = item.kind {
252 self.in_trait_impl = false;
256 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
257 let attrs = cx.tcx.hir().attrs(item.hir_id());
258 let headers = check_attrs(cx, &self.valid_idents, attrs);
259 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
260 if !in_external_macro(cx.tcx.sess, item.span) {
261 lint_for_missing_headers(cx, item.hir_id(), item.span, sig, headers, None, None);
266 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
267 let attrs = cx.tcx.hir().attrs(item.hir_id());
268 let headers = check_attrs(cx, &self.valid_idents, attrs);
269 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
272 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
273 let body = cx.tcx.hir().body(body_id);
274 let mut fpu = FindPanicUnwrap {
276 typeck_results: cx.tcx.typeck(item.def_id),
279 fpu.visit_expr(&body.value);
280 lint_for_missing_headers(
293 fn lint_for_missing_headers<'tcx>(
294 cx: &LateContext<'tcx>,
296 span: impl Into<MultiSpan> + Copy,
297 sig: &hir::FnSig<'_>,
299 body_id: Option<hir::BodyId>,
300 panic_span: Option<Span>,
302 if !cx.access_levels.is_exported(hir_id) {
303 return; // Private functions do not require doc comments
305 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
310 "unsafe function's docs miss `# Safety` section",
313 if !headers.panics && panic_span.is_some() {
318 "docs for function which may panic missing `# Panics` section",
320 "first possible panic found here",
324 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
329 "docs for function returning `Result` missing `# Errors` section",
333 if let Some(body_id) = body_id;
334 if let Some(future) = cx.tcx.lang_items().future_trait();
335 let typeck = cx.tcx.typeck_body(body_id);
336 let body = cx.tcx.hir().body(body_id);
337 let ret_ty = typeck.expr_ty(&body.value);
338 if implements_trait(cx, ret_ty, future, &[]);
339 if let ty::Opaque(_, subs) = ret_ty.kind();
340 if let Some(gen) = subs.types().next();
341 if let ty::Generator(_, subs, _) = gen.kind();
342 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
348 "docs for function returning `Result` missing `# Errors` section",
356 /// Cleanup documentation decoration.
358 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
359 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
360 /// need to keep track of
361 /// the spans but this function is inspired from the later.
362 #[allow(clippy::cast_possible_truncation)]
364 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
365 // one-line comments lose their prefix
366 if comment_kind == CommentKind::Line {
367 let mut doc = doc.to_owned();
370 // +3 skips the opening delimiter
371 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
374 let mut sizes = vec![];
375 let mut contains_initial_stars = false;
376 for line in doc.lines() {
377 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
378 debug_assert_eq!(offset as u32 as usize, offset);
379 contains_initial_stars |= line.trim_start().starts_with('*');
380 // +1 adds the newline, +3 skips the opening delimiter
381 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
383 if !contains_initial_stars {
384 return (doc.to_string(), sizes);
386 // remove the initial '*'s if any
387 let mut no_stars = String::with_capacity(doc.len());
388 for line in doc.lines() {
389 let mut chars = line.chars();
390 for c in &mut chars {
391 if c.is_whitespace() {
394 no_stars.push(if c == '*' { ' ' } else { c });
398 no_stars.push_str(chars.as_str());
405 #[derive(Copy, Clone)]
412 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
413 let mut doc = String::new();
414 let mut spans = vec![];
417 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
418 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
419 spans.extend_from_slice(¤t_spans);
420 doc.push_str(&comment);
421 } else if attr.has_name(sym::doc) {
422 // ignore mix of sugared and non-sugared doc
423 // don't trigger the safety or errors check
433 for &mut (ref mut offset, _) in &mut spans {
434 let offset_copy = *offset;
436 current += offset_copy;
447 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
448 // Iterate over all `Events` and combine consecutive events into one
449 let events = parser.coalesce(|previous, current| {
450 use pulldown_cmark::Event::Text;
452 let previous_range = previous.1;
453 let current_range = current.1;
455 match (previous.0, current.0) {
456 (Text(previous), Text(current)) => {
457 let mut previous = previous.to_string();
458 previous.push_str(¤t);
459 Ok((Text(previous.into()), previous_range))
461 (previous, current) => Err(((previous, previous_range), (current, current_range))),
464 check_doc(cx, valid_idents, events, &spans)
467 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
469 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
470 cx: &LateContext<'_>,
471 valid_idents: &FxHashSet<String>,
473 spans: &[(usize, Span)],
475 // true if a safety header was found
476 use pulldown_cmark::Event::{
477 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
479 use pulldown_cmark::Tag::{CodeBlock, Heading, Item, Link, Paragraph};
480 use pulldown_cmark::{CodeBlockKind, CowStr};
482 let mut headers = DocHeaders {
487 let mut in_code = false;
488 let mut in_link = None;
489 let mut in_heading = false;
490 let mut is_rust = false;
491 let mut edition = None;
492 let mut ticks_unbalanced = false;
493 let mut text_to_check: Vec<(CowStr<'_>, Span)> = Vec::new();
494 let mut paragraph_span = spans.get(0).expect("function isn't called if doc comment is empty").1;
495 for (event, range) in events {
497 Start(CodeBlock(ref kind)) => {
499 if let CodeBlockKind::Fenced(lang) = kind {
500 for item in lang.split(',') {
501 if item == "ignore" {
505 if let Some(stripped) = item.strip_prefix("edition") {
507 edition = stripped.parse::<Edition>().ok();
508 } else if item.is_empty() || RUST_CODE.contains(&item) {
514 End(CodeBlock(_)) => {
518 Start(Link(_, url, _)) => in_link = Some(url),
519 End(Link(..)) => in_link = None,
520 Start(Heading(_) | Paragraph | Item) => {
521 if let Start(Heading(_)) = event {
524 ticks_unbalanced = false;
525 let (_, span) = get_current_span(spans, range.start);
526 paragraph_span = first_line_of_span(cx, span);
528 End(Heading(_) | Paragraph | Item) => {
529 if let End(Heading(_)) = event {
532 if ticks_unbalanced {
537 "backticks are unbalanced",
539 "a backtick may be missing a pair",
542 for (text, span) in text_to_check {
543 check_text(cx, valid_idents, &text, span);
546 text_to_check = Vec::new();
548 Start(_tag) | End(_tag) => (), // We don't care about other tags
549 Html(_html) => (), // HTML is weird, just ignore it
550 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
551 FootnoteReference(text) | Text(text) => {
552 let (begin, span) = get_current_span(spans, range.start);
553 paragraph_span = paragraph_span.with_hi(span.hi());
554 ticks_unbalanced |= text.contains('`') && !in_code;
555 if Some(&text) == in_link.as_ref() || ticks_unbalanced {
556 // Probably a link of the form `<http://example.com>`
557 // Which are represented as a link to "http://example.com" with
558 // text "http://example.com" by pulldown-cmark
561 headers.safety |= in_heading && text.trim() == "Safety";
562 headers.errors |= in_heading && text.trim() == "Errors";
563 headers.panics |= in_heading && text.trim() == "Panics";
566 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
567 check_code(cx, &text, edition, span);
570 // Adjust for the beginning of the current `Event`
571 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
572 text_to_check.push((text, span));
580 fn get_current_span(spans: &[(usize, Span)], idx: usize) -> (usize, Span) {
581 let index = match spans.binary_search_by(|c| c.0.cmp(&idx)) {
588 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
589 fn has_needless_main(code: String, edition: Edition) -> bool {
590 rustc_driver::catch_fatal_errors(|| {
591 rustc_span::create_session_globals_then(edition, || {
592 let filename = FileName::anon_source_code(&code);
594 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
595 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
596 let handler = Handler::with_emitter(false, None, box emitter);
597 let sess = ParseSess::with_span_handler(handler, sm);
599 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) {
602 for mut err in errs {
609 let mut relevant_main_found = false;
611 match parser.parse_item(ForceCollect::No) {
612 Ok(Some(item)) => match &item.kind {
613 // Tests with one of these items are ignored
615 | ItemKind::Const(..)
616 | ItemKind::ExternCrate(..)
617 | ItemKind::ForeignMod(..) => return false,
618 // We found a main function ...
619 ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => {
620 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
621 let returns_nothing = match &sig.decl.output {
622 FnRetTy::Default(..) => true,
623 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
624 FnRetTy::Ty(_) => false,
627 if returns_nothing && !is_async && !block.stmts.is_empty() {
628 // This main function should be linted, but only if there are no other functions
629 relevant_main_found = true;
631 // This main function should not be linted, we're done
635 // Another function was found; this case is ignored too
636 ItemKind::Fn(..) => return false,
654 // Because of the global session, we need to create a new session in a different thread with
655 // the edition we need.
656 let text = text.to_owned();
657 if thread::spawn(move || has_needless_main(text, edition))
659 .expect("thread::spawn failed")
661 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
665 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
666 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
667 // Trim punctuation as in `some comment (see foo::bar).`
669 // Or even as in `_foo bar_` which is emphasized.
670 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
672 if valid_idents.contains(word) {
676 // Adjust for the current word
677 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
678 let span = Span::new(
679 span.lo() + BytePos::from_usize(offset),
680 span.lo() + BytePos::from_usize(offset + word.len()),
684 check_word(cx, word, span);
688 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
689 /// Checks if a string is camel-case, i.e., contains at least two uppercase
690 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
691 /// Plurals are also excluded (`IDs` is ok).
692 fn is_camel_case(s: &str) -> bool {
693 if s.starts_with(|c: char| c.is_digit(10)) {
697 let s = s.strip_suffix('s').unwrap_or(s);
699 s.chars().all(char::is_alphanumeric)
700 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
701 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
704 fn has_underscore(s: &str) -> bool {
705 s != "_" && !s.contains("\\_") && s.contains('_')
708 fn has_hyphen(s: &str) -> bool {
709 s != "-" && s.contains('-')
712 if let Ok(url) = Url::parse(word) {
713 // try to get around the fact that `foo::bar` parses as a valid URL
714 if !url.cannot_be_a_base() {
719 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
726 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
727 if has_underscore(word) && has_hyphen(word) {
731 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
736 &format!("you should put `{}` between ticks in the documentation", word),
741 struct FindPanicUnwrap<'a, 'tcx> {
742 cx: &'a LateContext<'tcx>,
743 panic_span: Option<Span>,
744 typeck_results: &'tcx ty::TypeckResults<'tcx>,
747 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
748 type Map = Map<'tcx>;
750 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
751 if self.panic_span.is_some() {
755 // check for `begin_panic`
757 if let ExprKind::Call(func_expr, _) = expr.kind;
758 if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
759 if let Some(path_def_id) = path.res.opt_def_id();
760 if match_panic_def_id(self.cx, path_def_id);
761 if is_expn_of(expr.span, "unreachable").is_none();
762 if !is_expn_of_debug_assertions(expr.span);
764 self.panic_span = Some(expr.span);
768 // check for `assert_eq` or `assert_ne`
769 if is_expn_of(expr.span, "assert_eq").is_some() || is_expn_of(expr.span, "assert_ne").is_some() {
770 self.panic_span = Some(expr.span);
773 // check for `unwrap`
774 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
775 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
776 if is_type_diagnostic_item(self.cx, reciever_ty, sym::option_type)
777 || is_type_diagnostic_item(self.cx, reciever_ty, sym::result_type)
779 self.panic_span = Some(expr.span);
783 // and check sub-expressions
784 intravisit::walk_expr(self, expr);
787 // Panics in const blocks will cause compilation to fail.
788 fn visit_anon_const(&mut self, _: &'tcx AnonConst) {}
790 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
791 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
795 fn is_expn_of_debug_assertions(span: Span) -> bool {
796 const MACRO_NAMES: &[&str] = &["debug_assert", "debug_assert_eq", "debug_assert_ne"];
797 MACRO_NAMES.iter().any(|name| is_expn_of(span, name).is_some())