1 use crate::utils::{implements_trait, is_entrypoint_fn, is_type_diagnostic_item, return_ty, span_lint};
2 use if_chain::if_chain;
3 use itertools::Itertools;
4 use rustc_ast::ast::{Async, AttrKind, Attribute, FnRetTy, ItemKind};
5 use rustc_ast::token::CommentKind;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_data_structures::sync::Lrc;
8 use rustc_errors::emitter::EmitterWriter;
9 use rustc_errors::Handler;
11 use rustc_lint::{LateContext, LateLintPass};
12 use rustc_middle::lint::in_external_macro;
14 use rustc_parse::maybe_new_parser_from_source_str;
15 use rustc_session::parse::ParseSess;
16 use rustc_session::{declare_tool_lint, impl_lint_pass};
17 use rustc_span::edition::Edition;
18 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
19 use rustc_span::{sym, FileName, Pos};
24 declare_clippy_lint! {
25 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
26 /// outside ticks in documentation.
28 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
29 /// camel-case probably indicates some code which should be included between
30 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
33 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
34 /// for is limited, and there are still false positives.
36 /// In addition, when writing documentation comments, including `[]` brackets
37 /// inside a link text would trip the parser. Therfore, documenting link with
38 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
43 /// /// Do something with the foo_bar parameter. See also
44 /// /// that::other::module::foo.
45 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
46 /// fn doit(foo_bar: usize) {}
50 /// // Link text with `[]` brackets should be written as following:
51 /// /// Consume the array and return the inner
52 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
53 /// /// [SmallVec]: SmallVec
58 "presence of `_`, `::` or camel-case outside backticks in documentation"
61 declare_clippy_lint! {
62 /// **What it does:** Checks for the doc comments of publicly visible
63 /// unsafe functions and warns if there is no `# Safety` section.
65 /// **Why is this bad?** Unsafe functions should document their safety
66 /// preconditions, so that users can be sure they are using them safely.
68 /// **Known problems:** None.
72 ///# type Universe = ();
73 /// /// This function should really be documented
74 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
79 /// At least write a line about safety:
82 ///# type Universe = ();
85 /// /// This function should not be called before the horsemen are ready.
86 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
90 pub MISSING_SAFETY_DOC,
92 "`pub unsafe fn` without `# Safety` docs"
95 declare_clippy_lint! {
96 /// **What it does:** Checks the doc comments of publicly visible functions that
97 /// return a `Result` type and warns if there is no `# Errors` section.
99 /// **Why is this bad?** Documenting the type of errors that can be returned from a
100 /// function can help callers write code to handle the errors appropriately.
102 /// **Known problems:** None.
106 /// Since the following function returns a `Result` it has an `# Errors` section in
113 /// /// Will return `Err` if `filename` does not exist or the user does not have
114 /// /// permission to read it.
115 /// pub fn read(filename: String) -> io::Result<String> {
116 /// unimplemented!();
119 pub MISSING_ERRORS_DOC,
121 "`pub fn` returns `Result` without `# Errors` in doc comment"
124 declare_clippy_lint! {
125 /// **What it does:** Checks for `fn main() { .. }` in doctests
127 /// **Why is this bad?** The test can be shorter (and likely more readable)
128 /// if the `fn main()` is left implicit.
130 /// **Known problems:** None.
134 /// /// An example of a doctest with a `main()` function
140 /// /// // this needs not be in an `fn`
143 /// fn needless_main() {
144 /// unimplemented!();
147 pub NEEDLESS_DOCTEST_MAIN,
149 "presence of `fn main() {` in code examples"
152 #[allow(clippy::module_name_repetitions)]
154 pub struct DocMarkdown {
155 valid_idents: FxHashSet<String>,
160 pub fn new(valid_idents: FxHashSet<String>) -> Self {
163 in_trait_impl: false,
168 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
170 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
171 fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) {
172 check_attrs(cx, &self.valid_idents, &krate.item.attrs);
175 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
176 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
178 hir::ItemKind::Fn(ref sig, _, body_id) => {
179 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id).to_def_id())
180 || in_external_macro(cx.tcx.sess, item.span))
182 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
185 hir::ItemKind::Impl {
186 of_trait: ref trait_ref,
189 self.in_trait_impl = trait_ref.is_some();
195 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
196 if let hir::ItemKind::Impl { .. } = item.kind {
197 self.in_trait_impl = false;
201 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
202 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
203 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
204 if !in_external_macro(cx.tcx.sess, item.span) {
205 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
210 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
211 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
212 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
215 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
216 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
221 fn lint_for_missing_headers<'tcx>(
222 cx: &LateContext<'tcx>,
224 span: impl Into<MultiSpan> + Copy,
225 sig: &hir::FnSig<'_>,
227 body_id: Option<hir::BodyId>,
229 if !cx.access_levels.is_exported(hir_id) {
230 return; // Private functions do not require doc comments
232 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
237 "unsafe function's docs miss `# Safety` section",
241 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
246 "docs for function returning `Result` missing `# Errors` section",
250 if let Some(body_id) = body_id;
251 if let Some(future) = cx.tcx.lang_items().future_trait();
252 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
253 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
254 let ret_ty = mir.return_ty();
255 if implements_trait(cx, ret_ty, future, &[]);
256 if let ty::Opaque(_, subs) = ret_ty.kind();
257 if let Some(gen) = subs.types().next();
258 if let ty::Generator(_, subs, _) = gen.kind();
259 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
265 "docs for function returning `Result` missing `# Errors` section",
273 /// Cleanup documentation decoration.
275 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
276 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
277 /// need to keep track of
278 /// the spans but this function is inspired from the later.
279 #[allow(clippy::cast_possible_truncation)]
281 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
282 // one-line comments lose their prefix
283 if comment_kind == CommentKind::Line {
284 let mut doc = doc.to_owned();
287 // +3 skips the opening delimiter
288 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
291 let mut sizes = vec![];
292 let mut contains_initial_stars = false;
293 for line in doc.lines() {
294 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
295 debug_assert_eq!(offset as u32 as usize, offset);
296 contains_initial_stars |= line.trim_start().starts_with('*');
297 // +1 adds the newline, +3 skips the opening delimiter
298 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
300 if !contains_initial_stars {
301 return (doc.to_string(), sizes);
303 // remove the initial '*'s if any
304 let mut no_stars = String::with_capacity(doc.len());
305 for line in doc.lines() {
306 let mut chars = line.chars();
307 while let Some(c) = chars.next() {
308 if c.is_whitespace() {
311 no_stars.push(if c == '*' { ' ' } else { c });
315 no_stars.push_str(chars.as_str());
322 #[derive(Copy, Clone)]
328 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
329 let mut doc = String::new();
330 let mut spans = vec![];
333 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
334 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
335 spans.extend_from_slice(¤t_spans);
336 doc.push_str(&comment);
337 } else if attr.has_name(sym::doc) {
338 // ignore mix of sugared and non-sugared doc
339 // don't trigger the safety or errors check
348 for &mut (ref mut offset, _) in &mut spans {
349 let offset_copy = *offset;
351 current += offset_copy;
361 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
362 // Iterate over all `Events` and combine consecutive events into one
363 let events = parser.coalesce(|previous, current| {
364 use pulldown_cmark::Event::Text;
366 let previous_range = previous.1;
367 let current_range = current.1;
369 match (previous.0, current.0) {
370 (Text(previous), Text(current)) => {
371 let mut previous = previous.to_string();
372 previous.push_str(¤t);
373 Ok((Text(previous.into()), previous_range))
375 (previous, current) => Err(((previous, previous_range), (current, current_range))),
378 check_doc(cx, valid_idents, events, &spans)
381 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
383 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
384 cx: &LateContext<'_>,
385 valid_idents: &FxHashSet<String>,
387 spans: &[(usize, Span)],
389 // true if a safety header was found
390 use pulldown_cmark::CodeBlockKind;
391 use pulldown_cmark::Event::{
392 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
394 use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
396 let mut headers = DocHeaders {
400 let mut in_code = false;
401 let mut in_link = None;
402 let mut in_heading = false;
403 let mut is_rust = false;
404 let mut edition = None;
405 for (event, range) in events {
407 Start(CodeBlock(ref kind)) => {
409 if let CodeBlockKind::Fenced(lang) = kind {
410 for item in lang.split(',') {
411 if item == "ignore" {
415 if let Some(stripped) = item.strip_prefix("edition") {
417 edition = stripped.parse::<Edition>().ok();
418 } else if item.is_empty() || RUST_CODE.contains(&item) {
424 End(CodeBlock(_)) => {
428 Start(Link(_, url, _)) => in_link = Some(url),
429 End(Link(..)) => in_link = None,
430 Start(Heading(_)) => in_heading = true,
431 End(Heading(_)) => in_heading = false,
432 Start(_tag) | End(_tag) => (), // We don't care about other tags
433 Html(_html) => (), // HTML is weird, just ignore it
434 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
435 FootnoteReference(text) | Text(text) => {
436 if Some(&text) == in_link.as_ref() {
437 // Probably a link of the form `<http://example.com>`
438 // Which are represented as a link to "http://example.com" with
439 // text "http://example.com" by pulldown-cmark
442 headers.safety |= in_heading && text.trim() == "Safety";
443 headers.errors |= in_heading && text.trim() == "Errors";
444 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
448 let (begin, span) = spans[index];
451 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
452 check_code(cx, &text, edition, span);
455 // Adjust for the beginning of the current `Event`
456 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
458 check_text(cx, valid_idents, &text, span);
466 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
467 fn has_needless_main(code: &str, edition: Edition) -> bool {
468 rustc_driver::catch_fatal_errors(|| {
469 rustc_span::with_session_globals(edition, || {
470 let filename = FileName::anon_source_code(code);
472 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
473 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
474 let handler = Handler::with_emitter(false, None, box emitter);
475 let sess = ParseSess::with_span_handler(handler, sm);
477 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
480 for mut err in errs {
487 let mut relevant_main_found = false;
489 match parser.parse_item() {
490 Ok(Some(item)) => match &item.kind {
491 // Tests with one of these items are ignored
493 | ItemKind::Const(..)
494 | ItemKind::ExternCrate(..)
495 | ItemKind::ForeignMod(..) => return false,
496 // We found a main function ...
497 ItemKind::Fn(_, sig, _, Some(block)) if item.ident.name == sym::main => {
498 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
499 let returns_nothing = match &sig.decl.output {
500 FnRetTy::Default(..) => true,
501 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
505 if returns_nothing && !is_async && !block.stmts.is_empty() {
506 // This main function should be linted, but only if there are no other functions
507 relevant_main_found = true;
509 // This main function should not be linted, we're done
513 // Another function was found; this case is ignored too
514 ItemKind::Fn(..) => return false,
532 if has_needless_main(text, edition) {
533 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
537 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
538 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
539 // Trim punctuation as in `some comment (see foo::bar).`
541 // Or even as in `_foo bar_` which is emphasized.
542 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
544 if valid_idents.contains(word) {
548 // Adjust for the current word
549 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
550 let span = Span::new(
551 span.lo() + BytePos::from_usize(offset),
552 span.lo() + BytePos::from_usize(offset + word.len()),
556 check_word(cx, word, span);
560 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
561 /// Checks if a string is camel-case, i.e., contains at least two uppercase
562 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
563 /// Plurals are also excluded (`IDs` is ok).
564 fn is_camel_case(s: &str) -> bool {
565 if s.starts_with(|c: char| c.is_digit(10)) {
569 let s = s.strip_suffix('s').unwrap_or(s);
571 s.chars().all(char::is_alphanumeric)
572 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
573 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
576 fn has_underscore(s: &str) -> bool {
577 s != "_" && !s.contains("\\_") && s.contains('_')
580 fn has_hyphen(s: &str) -> bool {
581 s != "-" && s.contains('-')
584 if let Ok(url) = Url::parse(word) {
585 // try to get around the fact that `foo::bar` parses as a valid URL
586 if !url.cannot_be_a_base() {
591 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
598 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
599 if has_underscore(word) && has_hyphen(word) {
603 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
608 &format!("you should put `{}` between ticks in the documentation", word),