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_parse::parser::ForceCollect;
16 use rustc_session::parse::ParseSess;
17 use rustc_session::{declare_tool_lint, impl_lint_pass};
18 use rustc_span::edition::Edition;
19 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
20 use rustc_span::{sym, FileName, Pos};
25 declare_clippy_lint! {
26 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
27 /// outside ticks in documentation.
29 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
30 /// camel-case probably indicates some code which should be included between
31 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
34 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
35 /// for is limited, and there are still false positives.
37 /// In addition, when writing documentation comments, including `[]` brackets
38 /// inside a link text would trip the parser. Therfore, documenting link with
39 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
44 /// /// Do something with the foo_bar parameter. See also
45 /// /// that::other::module::foo.
46 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
47 /// fn doit(foo_bar: usize) {}
51 /// // Link text with `[]` brackets should be written as following:
52 /// /// Consume the array and return the inner
53 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
54 /// /// [SmallVec]: SmallVec
59 "presence of `_`, `::` or camel-case outside backticks in documentation"
62 declare_clippy_lint! {
63 /// **What it does:** Checks for the doc comments of publicly visible
64 /// unsafe functions and warns if there is no `# Safety` section.
66 /// **Why is this bad?** Unsafe functions should document their safety
67 /// preconditions, so that users can be sure they are using them safely.
69 /// **Known problems:** None.
73 ///# type Universe = ();
74 /// /// This function should really be documented
75 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
80 /// At least write a line about safety:
83 ///# type Universe = ();
86 /// /// This function should not be called before the horsemen are ready.
87 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
91 pub MISSING_SAFETY_DOC,
93 "`pub unsafe fn` without `# Safety` docs"
96 declare_clippy_lint! {
97 /// **What it does:** Checks the doc comments of publicly visible functions that
98 /// return a `Result` type and warns if there is no `# Errors` section.
100 /// **Why is this bad?** Documenting the type of errors that can be returned from a
101 /// function can help callers write code to handle the errors appropriately.
103 /// **Known problems:** None.
107 /// Since the following function returns a `Result` it has an `# Errors` section in
114 /// /// Will return `Err` if `filename` does not exist or the user does not have
115 /// /// permission to read it.
116 /// pub fn read(filename: String) -> io::Result<String> {
117 /// unimplemented!();
120 pub MISSING_ERRORS_DOC,
122 "`pub fn` returns `Result` without `# Errors` in doc comment"
125 declare_clippy_lint! {
126 /// **What it does:** Checks for `fn main() { .. }` in doctests
128 /// **Why is this bad?** The test can be shorter (and likely more readable)
129 /// if the `fn main()` is left implicit.
131 /// **Known problems:** None.
135 /// /// An example of a doctest with a `main()` function
141 /// /// // this needs not be in an `fn`
144 /// fn needless_main() {
145 /// unimplemented!();
148 pub NEEDLESS_DOCTEST_MAIN,
150 "presence of `fn main() {` in code examples"
153 #[allow(clippy::module_name_repetitions)]
155 pub struct DocMarkdown {
156 valid_idents: FxHashSet<String>,
161 pub fn new(valid_idents: FxHashSet<String>) -> Self {
164 in_trait_impl: false,
169 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
171 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
172 fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) {
173 check_attrs(cx, &self.valid_idents, &krate.item.attrs);
176 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
177 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
179 hir::ItemKind::Fn(ref sig, _, body_id) => {
180 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id).to_def_id())
181 || in_external_macro(cx.tcx.sess, item.span))
183 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
186 hir::ItemKind::Impl(ref impl_) => {
187 self.in_trait_impl = impl_.of_trait.is_some();
193 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
194 if let hir::ItemKind::Impl { .. } = item.kind {
195 self.in_trait_impl = false;
199 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
200 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
201 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
202 if !in_external_macro(cx.tcx.sess, item.span) {
203 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
208 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
209 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
210 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
213 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
214 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
219 fn lint_for_missing_headers<'tcx>(
220 cx: &LateContext<'tcx>,
222 span: impl Into<MultiSpan> + Copy,
223 sig: &hir::FnSig<'_>,
225 body_id: Option<hir::BodyId>,
227 if !cx.access_levels.is_exported(hir_id) {
228 return; // Private functions do not require doc comments
230 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
235 "unsafe function's docs miss `# Safety` section",
239 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
244 "docs for function returning `Result` missing `# Errors` section",
248 if let Some(body_id) = body_id;
249 if let Some(future) = cx.tcx.lang_items().future_trait();
250 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
251 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
252 let ret_ty = mir.return_ty();
253 if implements_trait(cx, ret_ty, future, &[]);
254 if let ty::Opaque(_, subs) = ret_ty.kind();
255 if let Some(gen) = subs.types().next();
256 if let ty::Generator(_, subs, _) = gen.kind();
257 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
263 "docs for function returning `Result` missing `# Errors` section",
271 /// Cleanup documentation decoration.
273 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
274 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
275 /// need to keep track of
276 /// the spans but this function is inspired from the later.
277 #[allow(clippy::cast_possible_truncation)]
279 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
280 // one-line comments lose their prefix
281 if comment_kind == CommentKind::Line {
282 let mut doc = doc.to_owned();
285 // +3 skips the opening delimiter
286 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
289 let mut sizes = vec![];
290 let mut contains_initial_stars = false;
291 for line in doc.lines() {
292 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
293 debug_assert_eq!(offset as u32 as usize, offset);
294 contains_initial_stars |= line.trim_start().starts_with('*');
295 // +1 adds the newline, +3 skips the opening delimiter
296 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
298 if !contains_initial_stars {
299 return (doc.to_string(), sizes);
301 // remove the initial '*'s if any
302 let mut no_stars = String::with_capacity(doc.len());
303 for line in doc.lines() {
304 let mut chars = line.chars();
305 while let Some(c) = chars.next() {
306 if c.is_whitespace() {
309 no_stars.push(if c == '*' { ' ' } else { c });
313 no_stars.push_str(chars.as_str());
320 #[derive(Copy, Clone)]
326 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
327 let mut doc = String::new();
328 let mut spans = vec![];
331 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
332 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
333 spans.extend_from_slice(¤t_spans);
334 doc.push_str(&comment);
335 } else if attr.has_name(sym::doc) {
336 // ignore mix of sugared and non-sugared doc
337 // don't trigger the safety or errors check
346 for &mut (ref mut offset, _) in &mut spans {
347 let offset_copy = *offset;
349 current += offset_copy;
359 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
360 // Iterate over all `Events` and combine consecutive events into one
361 let events = parser.coalesce(|previous, current| {
362 use pulldown_cmark::Event::Text;
364 let previous_range = previous.1;
365 let current_range = current.1;
367 match (previous.0, current.0) {
368 (Text(previous), Text(current)) => {
369 let mut previous = previous.to_string();
370 previous.push_str(¤t);
371 Ok((Text(previous.into()), previous_range))
373 (previous, current) => Err(((previous, previous_range), (current, current_range))),
376 check_doc(cx, valid_idents, events, &spans)
379 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
381 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
382 cx: &LateContext<'_>,
383 valid_idents: &FxHashSet<String>,
385 spans: &[(usize, Span)],
387 // true if a safety header was found
388 use pulldown_cmark::CodeBlockKind;
389 use pulldown_cmark::Event::{
390 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
392 use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
394 let mut headers = DocHeaders {
398 let mut in_code = false;
399 let mut in_link = None;
400 let mut in_heading = false;
401 let mut is_rust = false;
402 let mut edition = None;
403 for (event, range) in events {
405 Start(CodeBlock(ref kind)) => {
407 if let CodeBlockKind::Fenced(lang) = kind {
408 for item in lang.split(',') {
409 if item == "ignore" {
413 if let Some(stripped) = item.strip_prefix("edition") {
415 edition = stripped.parse::<Edition>().ok();
416 } else if item.is_empty() || RUST_CODE.contains(&item) {
422 End(CodeBlock(_)) => {
426 Start(Link(_, url, _)) => in_link = Some(url),
427 End(Link(..)) => in_link = None,
428 Start(Heading(_)) => in_heading = true,
429 End(Heading(_)) => in_heading = false,
430 Start(_tag) | End(_tag) => (), // We don't care about other tags
431 Html(_html) => (), // HTML is weird, just ignore it
432 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
433 FootnoteReference(text) | Text(text) => {
434 if Some(&text) == in_link.as_ref() {
435 // Probably a link of the form `<http://example.com>`
436 // Which are represented as a link to "http://example.com" with
437 // text "http://example.com" by pulldown-cmark
440 headers.safety |= in_heading && text.trim() == "Safety";
441 headers.errors |= in_heading && text.trim() == "Errors";
442 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
446 let (begin, span) = spans[index];
449 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
450 check_code(cx, &text, edition, span);
453 // Adjust for the beginning of the current `Event`
454 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
456 check_text(cx, valid_idents, &text, span);
464 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
465 fn has_needless_main(code: &str, edition: Edition) -> bool {
466 rustc_driver::catch_fatal_errors(|| {
467 rustc_span::with_session_globals(edition, || {
468 let filename = FileName::anon_source_code(code);
470 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
471 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
472 let handler = Handler::with_emitter(false, None, box emitter);
473 let sess = ParseSess::with_span_handler(handler, sm);
475 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
478 for mut err in errs {
485 let mut relevant_main_found = false;
487 match parser.parse_item(ForceCollect::No) {
488 Ok(Some(item)) => match &item.kind {
489 // Tests with one of these items are ignored
491 | ItemKind::Const(..)
492 | ItemKind::ExternCrate(..)
493 | ItemKind::ForeignMod(..) => return false,
494 // We found a main function ...
495 ItemKind::Fn(_, sig, _, Some(block)) if item.ident.name == sym::main => {
496 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
497 let returns_nothing = match &sig.decl.output {
498 FnRetTy::Default(..) => true,
499 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
503 if returns_nothing && !is_async && !block.stmts.is_empty() {
504 // This main function should be linted, but only if there are no other functions
505 relevant_main_found = true;
507 // This main function should not be linted, we're done
511 // Another function was found; this case is ignored too
512 ItemKind::Fn(..) => return false,
530 if has_needless_main(text, edition) {
531 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
535 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
536 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
537 // Trim punctuation as in `some comment (see foo::bar).`
539 // Or even as in `_foo bar_` which is emphasized.
540 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
542 if valid_idents.contains(word) {
546 // Adjust for the current word
547 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
548 let span = Span::new(
549 span.lo() + BytePos::from_usize(offset),
550 span.lo() + BytePos::from_usize(offset + word.len()),
554 check_word(cx, word, span);
558 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
559 /// Checks if a string is camel-case, i.e., contains at least two uppercase
560 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
561 /// Plurals are also excluded (`IDs` is ok).
562 fn is_camel_case(s: &str) -> bool {
563 if s.starts_with(|c: char| c.is_digit(10)) {
567 let s = s.strip_suffix('s').unwrap_or(s);
569 s.chars().all(char::is_alphanumeric)
570 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
571 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
574 fn has_underscore(s: &str) -> bool {
575 s != "_" && !s.contains("\\_") && s.contains('_')
578 fn has_hyphen(s: &str) -> bool {
579 s != "-" && s.contains('-')
582 if let Ok(url) = Url::parse(word) {
583 // try to get around the fact that `foo::bar` parses as a valid URL
584 if !url.cannot_be_a_base() {
589 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
596 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
597 if has_underscore(word) && has_hyphen(word) {
601 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
606 &format!("you should put `{}` between ticks in the documentation", word),