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::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
18 use rustc_span::{sym, FileName, Pos};
23 declare_clippy_lint! {
24 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
25 /// outside ticks in documentation.
27 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
28 /// camel-case probably indicates some code which should be included between
29 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
32 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
33 /// for is limited, and there are still false positives.
35 /// In addition, when writing documentation comments, including `[]` brackets
36 /// inside a link text would trip the parser. Therfore, documenting link with
37 /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
42 /// /// Do something with the foo_bar parameter. See also
43 /// /// that::other::module::foo.
44 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
45 /// fn doit(foo_bar: usize) {}
49 /// // Link text with `[]` brackets should be written as following:
50 /// /// Consume the array and return the inner
51 /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
52 /// /// [SmallVec]: SmallVec
57 "presence of `_`, `::` or camel-case outside backticks in documentation"
60 declare_clippy_lint! {
61 /// **What it does:** Checks for the doc comments of publicly visible
62 /// unsafe functions and warns if there is no `# Safety` section.
64 /// **Why is this bad?** Unsafe functions should document their safety
65 /// preconditions, so that users can be sure they are using them safely.
67 /// **Known problems:** None.
71 ///# type Universe = ();
72 /// /// This function should really be documented
73 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
78 /// At least write a line about safety:
81 ///# type Universe = ();
84 /// /// This function should not be called before the horsemen are ready.
85 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
89 pub MISSING_SAFETY_DOC,
91 "`pub unsafe fn` without `# Safety` docs"
94 declare_clippy_lint! {
95 /// **What it does:** Checks the doc comments of publicly visible functions that
96 /// return a `Result` type and warns if there is no `# Errors` section.
98 /// **Why is this bad?** Documenting the type of errors that can be returned from a
99 /// function can help callers write code to handle the errors appropriately.
101 /// **Known problems:** None.
105 /// Since the following function returns a `Result` it has an `# Errors` section in
112 /// /// Will return `Err` if `filename` does not exist or the user does not have
113 /// /// permission to read it.
114 /// pub fn read(filename: String) -> io::Result<String> {
115 /// unimplemented!();
118 pub MISSING_ERRORS_DOC,
120 "`pub fn` returns `Result` without `# Errors` in doc comment"
123 declare_clippy_lint! {
124 /// **What it does:** Checks for `fn main() { .. }` in doctests
126 /// **Why is this bad?** The test can be shorter (and likely more readable)
127 /// if the `fn main()` is left implicit.
129 /// **Known problems:** None.
133 /// /// An example of a doctest with a `main()` function
139 /// /// // this needs not be in an `fn`
142 /// fn needless_main() {
143 /// unimplemented!();
146 pub NEEDLESS_DOCTEST_MAIN,
148 "presence of `fn main() {` in code examples"
151 #[allow(clippy::module_name_repetitions)]
153 pub struct DocMarkdown {
154 valid_idents: FxHashSet<String>,
159 pub fn new(valid_idents: FxHashSet<String>) -> Self {
162 in_trait_impl: false,
167 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
169 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
170 fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) {
171 check_attrs(cx, &self.valid_idents, &krate.item.attrs);
174 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
175 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
177 hir::ItemKind::Fn(ref sig, _, body_id) => {
178 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id).to_def_id())
179 || in_external_macro(cx.tcx.sess, item.span))
181 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
184 hir::ItemKind::Impl {
185 of_trait: ref trait_ref,
188 self.in_trait_impl = trait_ref.is_some();
194 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
195 if let hir::ItemKind::Impl { .. } = item.kind {
196 self.in_trait_impl = false;
200 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
201 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
202 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
203 if !in_external_macro(cx.tcx.sess, item.span) {
204 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
209 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
210 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
211 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
214 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
215 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
220 fn lint_for_missing_headers<'tcx>(
221 cx: &LateContext<'tcx>,
223 span: impl Into<MultiSpan> + Copy,
224 sig: &hir::FnSig<'_>,
226 body_id: Option<hir::BodyId>,
228 if !cx.access_levels.is_exported(hir_id) {
229 return; // Private functions do not require doc comments
231 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
236 "unsafe function's docs miss `# Safety` section",
240 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
245 "docs for function returning `Result` missing `# Errors` section",
249 if let Some(body_id) = body_id;
250 if let Some(future) = cx.tcx.lang_items().future_trait();
251 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
252 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
253 let ret_ty = mir.return_ty();
254 if implements_trait(cx, ret_ty, future, &[]);
255 if let ty::Opaque(_, subs) = ret_ty.kind();
256 if let Some(gen) = subs.types().next();
257 if let ty::Generator(_, subs, _) = gen.kind();
258 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
264 "docs for function returning `Result` missing `# Errors` section",
272 /// Cleanup documentation decoration.
274 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
275 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
276 /// need to keep track of
277 /// the spans but this function is inspired from the later.
278 #[allow(clippy::cast_possible_truncation)]
280 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
281 // one-line comments lose their prefix
282 if comment_kind == CommentKind::Line {
283 let mut doc = doc.to_owned();
286 // +3 skips the opening delimiter
287 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
290 let mut sizes = vec![];
291 let mut contains_initial_stars = false;
292 for line in doc.lines() {
293 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
294 debug_assert_eq!(offset as u32 as usize, offset);
295 contains_initial_stars |= line.trim_start().starts_with('*');
296 // +1 adds the newline, +3 skips the opening delimiter
297 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
299 if !contains_initial_stars {
300 return (doc.to_string(), sizes);
302 // remove the initial '*'s if any
303 let mut no_stars = String::with_capacity(doc.len());
304 for line in doc.lines() {
305 let mut chars = line.chars();
306 while let Some(c) = chars.next() {
307 if c.is_whitespace() {
310 no_stars.push(if c == '*' { ' ' } else { c });
314 no_stars.push_str(chars.as_str());
321 #[derive(Copy, Clone)]
327 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
328 let mut doc = String::new();
329 let mut spans = vec![];
332 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
333 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
334 spans.extend_from_slice(¤t_spans);
335 doc.push_str(&comment);
336 } else if attr.has_name(sym::doc) {
337 // ignore mix of sugared and non-sugared doc
338 // don't trigger the safety or errors check
347 for &mut (ref mut offset, _) in &mut spans {
348 let offset_copy = *offset;
350 current += offset_copy;
360 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
361 // Iterate over all `Events` and combine consecutive events into one
362 let events = parser.coalesce(|previous, current| {
363 use pulldown_cmark::Event::Text;
365 let previous_range = previous.1;
366 let current_range = current.1;
368 match (previous.0, current.0) {
369 (Text(previous), Text(current)) => {
370 let mut previous = previous.to_string();
371 previous.push_str(¤t);
372 Ok((Text(previous.into()), previous_range))
374 (previous, current) => Err(((previous, previous_range), (current, current_range))),
377 check_doc(cx, valid_idents, events, &spans)
380 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail", "edition2018"];
382 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
383 cx: &LateContext<'_>,
384 valid_idents: &FxHashSet<String>,
386 spans: &[(usize, Span)],
388 // true if a safety header was found
389 use pulldown_cmark::CodeBlockKind;
390 use pulldown_cmark::Event::{
391 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
393 use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
395 let mut headers = DocHeaders {
399 let mut in_code = false;
400 let mut in_link = None;
401 let mut in_heading = false;
402 let mut is_rust = false;
403 for (event, range) in events {
405 Start(CodeBlock(ref kind)) => {
407 if let CodeBlockKind::Fenced(lang) = kind {
409 lang.is_empty() || !lang.contains("ignore") && lang.split(',').any(|i| RUST_CODE.contains(&i));
412 End(CodeBlock(_)) => {
416 Start(Link(_, url, _)) => in_link = Some(url),
417 End(Link(..)) => in_link = None,
418 Start(Heading(_)) => in_heading = true,
419 End(Heading(_)) => in_heading = false,
420 Start(_tag) | End(_tag) => (), // We don't care about other tags
421 Html(_html) => (), // HTML is weird, just ignore it
422 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
423 FootnoteReference(text) | Text(text) => {
424 if Some(&text) == in_link.as_ref() {
425 // Probably a link of the form `<http://example.com>`
426 // Which are represented as a link to "http://example.com" with
427 // text "http://example.com" by pulldown-cmark
430 headers.safety |= in_heading && text.trim() == "Safety";
431 headers.errors |= in_heading && text.trim() == "Errors";
432 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
436 let (begin, span) = spans[index];
439 check_code(cx, &text, span);
442 // Adjust for the beginning of the current `Event`
443 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
445 check_text(cx, valid_idents, &text, span);
453 fn check_code(cx: &LateContext<'_>, text: &str, span: Span) {
454 fn has_needless_main(code: &str) -> bool {
455 let filename = FileName::anon_source_code(code);
457 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
458 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
459 let handler = Handler::with_emitter(false, None, box emitter);
460 let sess = ParseSess::with_span_handler(handler, sm);
462 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
465 for mut err in errs {
472 let mut relevant_main_found = false;
474 match parser.parse_item() {
475 Ok(Some(item)) => match &item.kind {
476 // Tests with one of these items are ignored
478 | ItemKind::Const(..)
479 | ItemKind::ExternCrate(..)
480 | ItemKind::ForeignMod(..) => return false,
481 // We found a main function ...
482 ItemKind::Fn(_, sig, _, Some(block)) if item.ident.name == sym::main => {
483 let is_async = matches!(sig.header.asyncness, Async::Yes{..});
484 let returns_nothing = match &sig.decl.output {
485 FnRetTy::Default(..) => true,
486 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
490 if returns_nothing && !is_async && !block.stmts.is_empty() {
491 // This main function should be linted, but only if there are no other functions
492 relevant_main_found = true;
494 // This main function should not be linted, we're done
498 // Another function was found; this case is ignored too
499 ItemKind::Fn(..) => return false,
513 if has_needless_main(text) {
514 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
518 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
519 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
520 // Trim punctuation as in `some comment (see foo::bar).`
522 // Or even as in `_foo bar_` which is emphasized.
523 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
525 if valid_idents.contains(word) {
529 // Adjust for the current word
530 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
531 let span = Span::new(
532 span.lo() + BytePos::from_usize(offset),
533 span.lo() + BytePos::from_usize(offset + word.len()),
537 check_word(cx, word, span);
541 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
542 /// Checks if a string is camel-case, i.e., contains at least two uppercase
543 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
544 /// Plurals are also excluded (`IDs` is ok).
545 fn is_camel_case(s: &str) -> bool {
546 if s.starts_with(|c: char| c.is_digit(10)) {
550 let s = s.strip_suffix('s').unwrap_or(s);
552 s.chars().all(char::is_alphanumeric)
553 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
554 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
557 fn has_underscore(s: &str) -> bool {
558 s != "_" && !s.contains("\\_") && s.contains('_')
561 fn has_hyphen(s: &str) -> bool {
562 s != "-" && s.contains('-')
565 if let Ok(url) = Url::parse(word) {
566 // try to get around the fact that `foo::bar` parses as a valid URL
567 if !url.cannot_be_a_base() {
572 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
579 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
580 if has_underscore(word) && has_hyphen(word) {
584 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
589 &format!("you should put `{}` between ticks in the documentation", word),