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! {
33 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
34 /// outside ticks in documentation.
36 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
37 /// camel-case probably indicates some code which should be included between
38 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
41 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
42 /// for is limited, and there are still false positives. HTML elements and their
43 /// content are not linted.
45 /// In addition, when writing documentation comments, including `[]` brackets
46 /// inside a link text would trip the parser. Therfore, documenting link with
47 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
52 /// /// Do something with the foo_bar parameter. See also
53 /// /// that::other::module::foo.
54 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
55 /// fn doit(foo_bar: usize) {}
59 /// // Link text with `[]` brackets should be written as following:
60 /// /// Consume the array and return the inner
61 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
62 /// /// [SmallVec]: SmallVec
67 "presence of `_`, `::` or camel-case outside backticks in documentation"
70 declare_clippy_lint! {
71 /// **What it does:** Checks for the doc comments of publicly visible
72 /// unsafe functions and warns if there is no `# Safety` section.
74 /// **Why is this bad?** Unsafe functions should document their safety
75 /// preconditions, so that users can be sure they are using them safely.
77 /// **Known problems:** None.
81 ///# type Universe = ();
82 /// /// This function should really be documented
83 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
88 /// At least write a line about safety:
91 ///# type Universe = ();
94 /// /// This function should not be called before the horsemen are ready.
95 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
99 pub MISSING_SAFETY_DOC,
101 "`pub unsafe fn` without `# Safety` docs"
104 declare_clippy_lint! {
105 /// **What it does:** Checks the doc comments of publicly visible functions that
106 /// return a `Result` type and warns if there is no `# Errors` section.
108 /// **Why is this bad?** Documenting the type of errors that can be returned from a
109 /// function can help callers write code to handle the errors appropriately.
111 /// **Known problems:** None.
115 /// Since the following function returns a `Result` it has an `# Errors` section in
122 /// /// Will return `Err` if `filename` does not exist or the user does not have
123 /// /// permission to read it.
124 /// pub fn read(filename: String) -> io::Result<String> {
125 /// unimplemented!();
128 pub MISSING_ERRORS_DOC,
130 "`pub fn` returns `Result` without `# Errors` in doc comment"
133 declare_clippy_lint! {
134 /// **What it does:** Checks the doc comments of publicly visible functions that
135 /// may panic and warns if there is no `# Panics` section.
137 /// **Why is this bad?** Documenting the scenarios in which panicking occurs
138 /// can help callers who do not want to panic to avoid those situations.
140 /// **Known problems:** None.
144 /// Since the following function may panic it has a `# Panics` section in
150 /// /// Will panic if y is 0
151 /// pub fn divide_by(x: i32, y: i32) -> i32 {
153 /// panic!("Cannot divide by 0")
159 pub MISSING_PANICS_DOC,
161 "`pub fn` may panic without `# Panics` in doc comment"
164 declare_clippy_lint! {
165 /// **What it does:** Checks for `fn main() { .. }` in doctests
167 /// **Why is this bad?** The test can be shorter (and likely more readable)
168 /// if the `fn main()` is left implicit.
170 /// **Known problems:** None.
174 /// /// An example of a doctest with a `main()` function
180 /// /// // this needs not be in an `fn`
183 /// fn needless_main() {
184 /// unimplemented!();
187 pub NEEDLESS_DOCTEST_MAIN,
189 "presence of `fn main() {` in code examples"
192 #[allow(clippy::module_name_repetitions)]
194 pub struct DocMarkdown {
195 valid_idents: FxHashSet<String>,
200 pub fn new(valid_idents: FxHashSet<String>) -> Self {
203 in_trait_impl: false,
208 impl_lint_pass!(DocMarkdown =>
209 [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, NEEDLESS_DOCTEST_MAIN]
212 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
213 fn check_crate(&mut self, cx: &LateContext<'tcx>, _: &'tcx hir::Crate<'_>) {
214 let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID);
215 check_attrs(cx, &self.valid_idents, attrs);
218 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
219 let attrs = cx.tcx.hir().attrs(item.hir_id());
220 let headers = check_attrs(cx, &self.valid_idents, attrs);
222 hir::ItemKind::Fn(ref sig, _, body_id) => {
223 if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) {
224 let body = cx.tcx.hir().body(body_id);
225 let mut fpu = FindPanicUnwrap {
227 typeck_results: cx.tcx.typeck(item.def_id),
230 fpu.visit_expr(&body.value);
231 lint_for_missing_headers(
242 hir::ItemKind::Impl(ref impl_) => {
243 self.in_trait_impl = impl_.of_trait.is_some();
249 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
250 if let hir::ItemKind::Impl { .. } = item.kind {
251 self.in_trait_impl = false;
255 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
256 let attrs = cx.tcx.hir().attrs(item.hir_id());
257 let headers = check_attrs(cx, &self.valid_idents, attrs);
258 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
259 if !in_external_macro(cx.tcx.sess, item.span) {
260 lint_for_missing_headers(cx, item.hir_id(), item.span, sig, headers, None, None);
265 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
266 let attrs = cx.tcx.hir().attrs(item.hir_id());
267 let headers = check_attrs(cx, &self.valid_idents, attrs);
268 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
271 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
272 let body = cx.tcx.hir().body(body_id);
273 let mut fpu = FindPanicUnwrap {
275 typeck_results: cx.tcx.typeck(item.def_id),
278 fpu.visit_expr(&body.value);
279 lint_for_missing_headers(
292 fn lint_for_missing_headers<'tcx>(
293 cx: &LateContext<'tcx>,
295 span: impl Into<MultiSpan> + Copy,
296 sig: &hir::FnSig<'_>,
298 body_id: Option<hir::BodyId>,
299 panic_span: Option<Span>,
301 if !cx.access_levels.is_exported(hir_id) {
302 return; // Private functions do not require doc comments
304 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
309 "unsafe function's docs miss `# Safety` section",
312 if !headers.panics && panic_span.is_some() {
317 "docs for function which may panic missing `# Panics` section",
319 "first possible panic found here",
323 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
328 "docs for function returning `Result` missing `# Errors` section",
332 if let Some(body_id) = body_id;
333 if let Some(future) = cx.tcx.lang_items().future_trait();
334 let typeck = cx.tcx.typeck_body(body_id);
335 let body = cx.tcx.hir().body(body_id);
336 let ret_ty = typeck.expr_ty(&body.value);
337 if implements_trait(cx, ret_ty, future, &[]);
338 if let ty::Opaque(_, subs) = ret_ty.kind();
339 if let Some(gen) = subs.types().next();
340 if let ty::Generator(_, subs, _) = gen.kind();
341 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
347 "docs for function returning `Result` missing `# Errors` section",
355 /// Cleanup documentation decoration.
357 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
358 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
359 /// need to keep track of
360 /// the spans but this function is inspired from the later.
361 #[allow(clippy::cast_possible_truncation)]
363 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
364 // one-line comments lose their prefix
365 if comment_kind == CommentKind::Line {
366 let mut doc = doc.to_owned();
369 // +3 skips the opening delimiter
370 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
373 let mut sizes = vec![];
374 let mut contains_initial_stars = false;
375 for line in doc.lines() {
376 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
377 debug_assert_eq!(offset as u32 as usize, offset);
378 contains_initial_stars |= line.trim_start().starts_with('*');
379 // +1 adds the newline, +3 skips the opening delimiter
380 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
382 if !contains_initial_stars {
383 return (doc.to_string(), sizes);
385 // remove the initial '*'s if any
386 let mut no_stars = String::with_capacity(doc.len());
387 for line in doc.lines() {
388 let mut chars = line.chars();
389 for c in &mut chars {
390 if c.is_whitespace() {
393 no_stars.push(if c == '*' { ' ' } else { c });
397 no_stars.push_str(chars.as_str());
404 #[derive(Copy, Clone)]
411 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
412 let mut doc = String::new();
413 let mut spans = vec![];
416 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
417 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
418 spans.extend_from_slice(¤t_spans);
419 doc.push_str(&comment);
420 } else if attr.has_name(sym::doc) {
421 // ignore mix of sugared and non-sugared doc
422 // don't trigger the safety or errors check
432 for &mut (ref mut offset, _) in &mut spans {
433 let offset_copy = *offset;
435 current += offset_copy;
446 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
447 // Iterate over all `Events` and combine consecutive events into one
448 let events = parser.coalesce(|previous, current| {
449 use pulldown_cmark::Event::Text;
451 let previous_range = previous.1;
452 let current_range = current.1;
454 match (previous.0, current.0) {
455 (Text(previous), Text(current)) => {
456 let mut previous = previous.to_string();
457 previous.push_str(¤t);
458 Ok((Text(previous.into()), previous_range))
460 (previous, current) => Err(((previous, previous_range), (current, current_range))),
463 check_doc(cx, valid_idents, events, &spans)
466 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
468 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
469 cx: &LateContext<'_>,
470 valid_idents: &FxHashSet<String>,
472 spans: &[(usize, Span)],
474 // true if a safety header was found
475 use pulldown_cmark::Event::{
476 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
478 use pulldown_cmark::Tag::{CodeBlock, Heading, Item, Link, Paragraph};
479 use pulldown_cmark::{CodeBlockKind, CowStr};
481 let mut headers = DocHeaders {
486 let mut in_code = false;
487 let mut in_link = None;
488 let mut in_heading = false;
489 let mut is_rust = false;
490 let mut edition = None;
491 let mut ticks_unbalanced = false;
492 let mut text_to_check: Vec<(CowStr<'_>, Span)> = Vec::new();
493 let mut paragraph_span = spans.get(0).expect("function isn't called if doc comment is empty").1;
494 for (event, range) in events {
496 Start(CodeBlock(ref kind)) => {
498 if let CodeBlockKind::Fenced(lang) = kind {
499 for item in lang.split(',') {
500 if item == "ignore" {
504 if let Some(stripped) = item.strip_prefix("edition") {
506 edition = stripped.parse::<Edition>().ok();
507 } else if item.is_empty() || RUST_CODE.contains(&item) {
513 End(CodeBlock(_)) => {
517 Start(Link(_, url, _)) => in_link = Some(url),
518 End(Link(..)) => in_link = None,
519 Start(Heading(_) | Paragraph | Item) => {
520 if let Start(Heading(_)) = event {
523 ticks_unbalanced = false;
524 let (_, span) = get_current_span(spans, range.start);
525 paragraph_span = first_line_of_span(cx, span);
527 End(Heading(_) | Paragraph | Item) => {
528 if let End(Heading(_)) = event {
531 if ticks_unbalanced {
536 "backticks are unbalanced",
538 "a backtick may be missing a pair",
541 for (text, span) in text_to_check {
542 check_text(cx, valid_idents, &text, span);
545 text_to_check = Vec::new();
547 Start(_tag) | End(_tag) => (), // We don't care about other tags
548 Html(_html) => (), // HTML is weird, just ignore it
549 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
550 FootnoteReference(text) | Text(text) => {
551 let (begin, span) = get_current_span(spans, range.start);
552 paragraph_span = paragraph_span.with_hi(span.hi());
553 ticks_unbalanced |= text.contains('`') && !in_code;
554 if Some(&text) == in_link.as_ref() || ticks_unbalanced {
555 // Probably a link of the form `<http://example.com>`
556 // Which are represented as a link to "http://example.com" with
557 // text "http://example.com" by pulldown-cmark
560 headers.safety |= in_heading && text.trim() == "Safety";
561 headers.errors |= in_heading && text.trim() == "Errors";
562 headers.panics |= in_heading && text.trim() == "Panics";
565 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
566 check_code(cx, &text, edition, span);
569 // Adjust for the beginning of the current `Event`
570 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
571 text_to_check.push((text, span));
579 fn get_current_span(spans: &[(usize, Span)], idx: usize) -> (usize, Span) {
580 let index = match spans.binary_search_by(|c| c.0.cmp(&idx)) {
587 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
588 fn has_needless_main(code: String, edition: Edition) -> bool {
589 rustc_driver::catch_fatal_errors(|| {
590 rustc_span::create_session_globals_then(edition, || {
591 let filename = FileName::anon_source_code(&code);
593 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
594 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
595 let handler = Handler::with_emitter(false, None, box emitter);
596 let sess = ParseSess::with_span_handler(handler, sm);
598 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) {
601 for mut err in errs {
608 let mut relevant_main_found = false;
610 match parser.parse_item(ForceCollect::No) {
611 Ok(Some(item)) => match &item.kind {
612 // Tests with one of these items are ignored
614 | ItemKind::Const(..)
615 | ItemKind::ExternCrate(..)
616 | ItemKind::ForeignMod(..) => return false,
617 // We found a main function ...
618 ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => {
619 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
620 let returns_nothing = match &sig.decl.output {
621 FnRetTy::Default(..) => true,
622 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
623 FnRetTy::Ty(_) => false,
626 if returns_nothing && !is_async && !block.stmts.is_empty() {
627 // This main function should be linted, but only if there are no other functions
628 relevant_main_found = true;
630 // This main function should not be linted, we're done
634 // Another function was found; this case is ignored too
635 ItemKind::Fn(..) => return false,
653 // Because of the global session, we need to create a new session in a different thread with
654 // the edition we need.
655 let text = text.to_owned();
656 if thread::spawn(move || has_needless_main(text, edition))
658 .expect("thread::spawn failed")
660 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
664 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
665 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
666 // Trim punctuation as in `some comment (see foo::bar).`
668 // Or even as in `_foo bar_` which is emphasized.
669 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
671 if valid_idents.contains(word) {
675 // Adjust for the current word
676 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
677 let span = Span::new(
678 span.lo() + BytePos::from_usize(offset),
679 span.lo() + BytePos::from_usize(offset + word.len()),
683 check_word(cx, word, span);
687 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
688 /// Checks if a string is camel-case, i.e., contains at least two uppercase
689 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
690 /// Plurals are also excluded (`IDs` is ok).
691 fn is_camel_case(s: &str) -> bool {
692 if s.starts_with(|c: char| c.is_digit(10)) {
696 let s = s.strip_suffix('s').unwrap_or(s);
698 s.chars().all(char::is_alphanumeric)
699 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
700 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
703 fn has_underscore(s: &str) -> bool {
704 s != "_" && !s.contains("\\_") && s.contains('_')
707 fn has_hyphen(s: &str) -> bool {
708 s != "-" && s.contains('-')
711 if let Ok(url) = Url::parse(word) {
712 // try to get around the fact that `foo::bar` parses as a valid URL
713 if !url.cannot_be_a_base() {
718 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
725 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
726 if has_underscore(word) && has_hyphen(word) {
730 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
735 &format!("you should put `{}` between ticks in the documentation", word),
740 struct FindPanicUnwrap<'a, 'tcx> {
741 cx: &'a LateContext<'tcx>,
742 panic_span: Option<Span>,
743 typeck_results: &'tcx ty::TypeckResults<'tcx>,
746 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
747 type Map = Map<'tcx>;
749 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
750 if self.panic_span.is_some() {
754 // check for `begin_panic`
756 if let ExprKind::Call(func_expr, _) = expr.kind;
757 if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
758 if let Some(path_def_id) = path.res.opt_def_id();
759 if match_panic_def_id(self.cx, path_def_id);
760 if is_expn_of(expr.span, "unreachable").is_none();
761 if !is_expn_of_debug_assertions(expr.span);
763 self.panic_span = Some(expr.span);
767 // check for `assert_eq` or `assert_ne`
768 if is_expn_of(expr.span, "assert_eq").is_some() || is_expn_of(expr.span, "assert_ne").is_some() {
769 self.panic_span = Some(expr.span);
772 // check for `unwrap`
773 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
774 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
775 if is_type_diagnostic_item(self.cx, reciever_ty, sym::option_type)
776 || is_type_diagnostic_item(self.cx, reciever_ty, sym::result_type)
778 self.panic_span = Some(expr.span);
782 // and check sub-expressions
783 intravisit::walk_expr(self, expr);
786 // Panics in const blocks will cause compilation to fail.
787 fn visit_anon_const(&mut self, _: &'tcx AnonConst) {}
789 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
790 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
794 fn is_expn_of_debug_assertions(span: Span) -> bool {
795 const MACRO_NAMES: &[&str] = &["debug_assert", "debug_assert_eq", "debug_assert_ne"];
796 MACRO_NAMES.iter().any(|name| is_expn_of(span, name).is_some())