2 implements_trait, is_entrypoint_fn, is_type_diagnostic_item, match_panic_def_id, method_chain_args, return_ty,
3 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())
220 || in_external_macro(cx.tcx.sess, item.span))
222 let body = cx.tcx.hir().body(body_id);
223 let mut fpu = FindPanicUnwrap {
225 typeck_results: cx.tcx.typeck(item.def_id),
228 fpu.visit_expr(&body.value);
229 lint_for_missing_headers(cx, item.hir_id(), item.span, sig, headers, Some(body_id), fpu.panic_span);
232 hir::ItemKind::Impl(ref impl_) => {
233 self.in_trait_impl = impl_.of_trait.is_some();
239 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
240 if let hir::ItemKind::Impl { .. } = item.kind {
241 self.in_trait_impl = false;
245 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
246 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
247 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
248 if !in_external_macro(cx.tcx.sess, item.span) {
249 lint_for_missing_headers(cx, item.hir_id(), item.span, sig, headers, None, None);
254 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
255 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
256 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
259 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
260 let body = cx.tcx.hir().body(body_id);
261 let mut fpu = FindPanicUnwrap {
263 typeck_results: cx.tcx.typeck(item.def_id),
266 fpu.visit_expr(&body.value);
267 lint_for_missing_headers(cx, item.hir_id(), item.span, sig, headers, Some(body_id), fpu.panic_span);
272 fn lint_for_missing_headers<'tcx>(
273 cx: &LateContext<'tcx>,
275 span: impl Into<MultiSpan> + Copy,
276 sig: &hir::FnSig<'_>,
278 body_id: Option<hir::BodyId>,
279 panic_span: Option<Span>,
281 if !cx.access_levels.is_exported(hir_id) {
282 return; // Private functions do not require doc comments
284 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
289 "unsafe function's docs miss `# Safety` section",
292 if !headers.panics && panic_span.is_some() {
297 "docs for function which may panic missing `# Panics` section",
299 "first possible panic found here",
303 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
308 "docs for function returning `Result` missing `# Errors` section",
312 if let Some(body_id) = body_id;
313 if let Some(future) = cx.tcx.lang_items().future_trait();
314 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
315 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
316 let ret_ty = mir.return_ty();
317 if implements_trait(cx, ret_ty, future, &[]);
318 if let ty::Opaque(_, subs) = ret_ty.kind();
319 if let Some(gen) = subs.types().next();
320 if let ty::Generator(_, subs, _) = gen.kind();
321 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
327 "docs for function returning `Result` missing `# Errors` section",
335 /// Cleanup documentation decoration.
337 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
338 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
339 /// need to keep track of
340 /// the spans but this function is inspired from the later.
341 #[allow(clippy::cast_possible_truncation)]
343 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
344 // one-line comments lose their prefix
345 if comment_kind == CommentKind::Line {
346 let mut doc = doc.to_owned();
349 // +3 skips the opening delimiter
350 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
353 let mut sizes = vec![];
354 let mut contains_initial_stars = false;
355 for line in doc.lines() {
356 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
357 debug_assert_eq!(offset as u32 as usize, offset);
358 contains_initial_stars |= line.trim_start().starts_with('*');
359 // +1 adds the newline, +3 skips the opening delimiter
360 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
362 if !contains_initial_stars {
363 return (doc.to_string(), sizes);
365 // remove the initial '*'s if any
366 let mut no_stars = String::with_capacity(doc.len());
367 for line in doc.lines() {
368 let mut chars = line.chars();
369 while let Some(c) = chars.next() {
370 if c.is_whitespace() {
373 no_stars.push(if c == '*' { ' ' } else { c });
377 no_stars.push_str(chars.as_str());
384 #[derive(Copy, Clone)]
391 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
392 let mut doc = String::new();
393 let mut spans = vec![];
396 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
397 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
398 spans.extend_from_slice(¤t_spans);
399 doc.push_str(&comment);
400 } else if attr.has_name(sym::doc) {
401 // ignore mix of sugared and non-sugared doc
402 // don't trigger the safety or errors check
412 for &mut (ref mut offset, _) in &mut spans {
413 let offset_copy = *offset;
415 current += offset_copy;
426 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
427 // Iterate over all `Events` and combine consecutive events into one
428 let events = parser.coalesce(|previous, current| {
429 use pulldown_cmark::Event::Text;
431 let previous_range = previous.1;
432 let current_range = current.1;
434 match (previous.0, current.0) {
435 (Text(previous), Text(current)) => {
436 let mut previous = previous.to_string();
437 previous.push_str(¤t);
438 Ok((Text(previous.into()), previous_range))
440 (previous, current) => Err(((previous, previous_range), (current, current_range))),
443 check_doc(cx, valid_idents, events, &spans)
446 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
448 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
449 cx: &LateContext<'_>,
450 valid_idents: &FxHashSet<String>,
452 spans: &[(usize, Span)],
454 // true if a safety header was found
455 use pulldown_cmark::CodeBlockKind;
456 use pulldown_cmark::Event::{
457 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
459 use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
461 let mut headers = DocHeaders {
466 let mut in_code = false;
467 let mut in_link = None;
468 let mut in_heading = false;
469 let mut is_rust = false;
470 let mut edition = None;
471 for (event, range) in events {
473 Start(CodeBlock(ref kind)) => {
475 if let CodeBlockKind::Fenced(lang) = kind {
476 for item in lang.split(',') {
477 if item == "ignore" {
481 if let Some(stripped) = item.strip_prefix("edition") {
483 edition = stripped.parse::<Edition>().ok();
484 } else if item.is_empty() || RUST_CODE.contains(&item) {
490 End(CodeBlock(_)) => {
494 Start(Link(_, url, _)) => in_link = Some(url),
495 End(Link(..)) => in_link = None,
496 Start(Heading(_)) => in_heading = true,
497 End(Heading(_)) => in_heading = false,
498 Start(_tag) | End(_tag) => (), // We don't care about other tags
499 Html(_html) => (), // HTML is weird, just ignore it
500 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
501 FootnoteReference(text) | Text(text) => {
502 if Some(&text) == in_link.as_ref() {
503 // Probably a link of the form `<http://example.com>`
504 // Which are represented as a link to "http://example.com" with
505 // text "http://example.com" by pulldown-cmark
508 headers.safety |= in_heading && text.trim() == "Safety";
509 headers.errors |= in_heading && text.trim() == "Errors";
510 headers.panics |= in_heading && text.trim() == "Panics";
511 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
515 let (begin, span) = spans[index];
518 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
519 check_code(cx, &text, edition, span);
522 // Adjust for the beginning of the current `Event`
523 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
525 check_text(cx, valid_idents, &text, span);
533 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
534 fn has_needless_main(code: &str, edition: Edition) -> bool {
535 rustc_driver::catch_fatal_errors(|| {
536 rustc_span::with_session_globals(edition, || {
537 let filename = FileName::anon_source_code(code);
539 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
540 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
541 let handler = Handler::with_emitter(false, None, box emitter);
542 let sess = ParseSess::with_span_handler(handler, sm);
544 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
547 for mut err in errs {
554 let mut relevant_main_found = false;
556 match parser.parse_item(ForceCollect::No) {
557 Ok(Some(item)) => match &item.kind {
558 // Tests with one of these items are ignored
560 | ItemKind::Const(..)
561 | ItemKind::ExternCrate(..)
562 | ItemKind::ForeignMod(..) => return false,
563 // We found a main function ...
564 ItemKind::Fn(box FnKind(_, sig, _, Some(block)))
565 if item.ident.name == sym::main =>
567 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
568 let returns_nothing = match &sig.decl.output {
569 FnRetTy::Default(..) => true,
570 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
574 if returns_nothing && !is_async && !block.stmts.is_empty() {
575 // This main function should be linted, but only if there are no other functions
576 relevant_main_found = true;
578 // This main function should not be linted, we're done
582 // Another function was found; this case is ignored too
583 ItemKind::Fn(..) => return false,
601 if has_needless_main(text, edition) {
602 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
606 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
607 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
608 // Trim punctuation as in `some comment (see foo::bar).`
610 // Or even as in `_foo bar_` which is emphasized.
611 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
613 if valid_idents.contains(word) {
617 // Adjust for the current word
618 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
619 let span = Span::new(
620 span.lo() + BytePos::from_usize(offset),
621 span.lo() + BytePos::from_usize(offset + word.len()),
625 check_word(cx, word, span);
629 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
630 /// Checks if a string is camel-case, i.e., contains at least two uppercase
631 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
632 /// Plurals are also excluded (`IDs` is ok).
633 fn is_camel_case(s: &str) -> bool {
634 if s.starts_with(|c: char| c.is_digit(10)) {
638 let s = s.strip_suffix('s').unwrap_or(s);
640 s.chars().all(char::is_alphanumeric)
641 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
642 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
645 fn has_underscore(s: &str) -> bool {
646 s != "_" && !s.contains("\\_") && s.contains('_')
649 fn has_hyphen(s: &str) -> bool {
650 s != "-" && s.contains('-')
653 if let Ok(url) = Url::parse(word) {
654 // try to get around the fact that `foo::bar` parses as a valid URL
655 if !url.cannot_be_a_base() {
660 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
667 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
668 if has_underscore(word) && has_hyphen(word) {
672 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
677 &format!("you should put `{}` between ticks in the documentation", word),
682 struct FindPanicUnwrap<'a, 'tcx> {
683 cx: &'a LateContext<'tcx>,
684 panic_span: Option<Span>,
685 typeck_results: &'tcx ty::TypeckResults<'tcx>,
688 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
689 type Map = Map<'tcx>;
691 fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
692 if self.panic_span.is_some() {
696 // check for `begin_panic`
698 if let ExprKind::Call(ref func_expr, _) = expr.kind;
699 if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind;
700 if let Some(path_def_id) = path.res.opt_def_id();
701 if match_panic_def_id(self.cx, path_def_id);
703 self.panic_span = Some(expr.span);
707 // check for `unwrap`
708 if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
709 let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
710 if is_type_diagnostic_item(self.cx, reciever_ty, sym::option_type)
711 || is_type_diagnostic_item(self.cx, reciever_ty, sym::result_type)
713 self.panic_span = Some(expr.span);
717 // and check sub-expressions
718 intravisit::walk_expr(self, expr);
721 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
722 NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())