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(ref impl_) => {
186 self.in_trait_impl = impl_.of_trait.is_some();
192 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
193 if let hir::ItemKind::Impl { .. } = item.kind {
194 self.in_trait_impl = false;
198 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
199 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
200 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
201 if !in_external_macro(cx.tcx.sess, item.span) {
202 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
207 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
208 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
209 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
212 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
213 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
218 fn lint_for_missing_headers<'tcx>(
219 cx: &LateContext<'tcx>,
221 span: impl Into<MultiSpan> + Copy,
222 sig: &hir::FnSig<'_>,
224 body_id: Option<hir::BodyId>,
226 if !cx.access_levels.is_exported(hir_id) {
227 return; // Private functions do not require doc comments
229 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
234 "unsafe function's docs miss `# Safety` section",
238 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
243 "docs for function returning `Result` missing `# Errors` section",
247 if let Some(body_id) = body_id;
248 if let Some(future) = cx.tcx.lang_items().future_trait();
249 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
250 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
251 let ret_ty = mir.return_ty();
252 if implements_trait(cx, ret_ty, future, &[]);
253 if let ty::Opaque(_, subs) = ret_ty.kind();
254 if let Some(gen) = subs.types().next();
255 if let ty::Generator(_, subs, _) = gen.kind();
256 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
262 "docs for function returning `Result` missing `# Errors` section",
270 /// Cleanup documentation decoration.
272 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
273 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
274 /// need to keep track of
275 /// the spans but this function is inspired from the later.
276 #[allow(clippy::cast_possible_truncation)]
278 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
279 // one-line comments lose their prefix
280 if comment_kind == CommentKind::Line {
281 let mut doc = doc.to_owned();
284 // +3 skips the opening delimiter
285 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
288 let mut sizes = vec![];
289 let mut contains_initial_stars = false;
290 for line in doc.lines() {
291 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
292 debug_assert_eq!(offset as u32 as usize, offset);
293 contains_initial_stars |= line.trim_start().starts_with('*');
294 // +1 adds the newline, +3 skips the opening delimiter
295 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
297 if !contains_initial_stars {
298 return (doc.to_string(), sizes);
300 // remove the initial '*'s if any
301 let mut no_stars = String::with_capacity(doc.len());
302 for line in doc.lines() {
303 let mut chars = line.chars();
304 while let Some(c) = chars.next() {
305 if c.is_whitespace() {
308 no_stars.push(if c == '*' { ' ' } else { c });
312 no_stars.push_str(chars.as_str());
319 #[derive(Copy, Clone)]
325 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
326 let mut doc = String::new();
327 let mut spans = vec![];
330 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
331 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
332 spans.extend_from_slice(¤t_spans);
333 doc.push_str(&comment);
334 } else if attr.has_name(sym::doc) {
335 // ignore mix of sugared and non-sugared doc
336 // don't trigger the safety or errors check
345 for &mut (ref mut offset, _) in &mut spans {
346 let offset_copy = *offset;
348 current += offset_copy;
358 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
359 // Iterate over all `Events` and combine consecutive events into one
360 let events = parser.coalesce(|previous, current| {
361 use pulldown_cmark::Event::Text;
363 let previous_range = previous.1;
364 let current_range = current.1;
366 match (previous.0, current.0) {
367 (Text(previous), Text(current)) => {
368 let mut previous = previous.to_string();
369 previous.push_str(¤t);
370 Ok((Text(previous.into()), previous_range))
372 (previous, current) => Err(((previous, previous_range), (current, current_range))),
375 check_doc(cx, valid_idents, events, &spans)
378 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
380 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
381 cx: &LateContext<'_>,
382 valid_idents: &FxHashSet<String>,
384 spans: &[(usize, Span)],
386 // true if a safety header was found
387 use pulldown_cmark::CodeBlockKind;
388 use pulldown_cmark::Event::{
389 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
391 use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
393 let mut headers = DocHeaders {
397 let mut in_code = false;
398 let mut in_link = None;
399 let mut in_heading = false;
400 let mut is_rust = false;
401 let mut edition = None;
402 for (event, range) in events {
404 Start(CodeBlock(ref kind)) => {
406 if let CodeBlockKind::Fenced(lang) = kind {
407 for item in lang.split(',') {
408 if item == "ignore" {
412 if let Some(stripped) = item.strip_prefix("edition") {
414 edition = stripped.parse::<Edition>().ok();
415 } else if item.is_empty() || RUST_CODE.contains(&item) {
421 End(CodeBlock(_)) => {
425 Start(Link(_, url, _)) => in_link = Some(url),
426 End(Link(..)) => in_link = None,
427 Start(Heading(_)) => in_heading = true,
428 End(Heading(_)) => in_heading = false,
429 Start(_tag) | End(_tag) => (), // We don't care about other tags
430 Html(_html) => (), // HTML is weird, just ignore it
431 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
432 FootnoteReference(text) | Text(text) => {
433 if Some(&text) == in_link.as_ref() {
434 // Probably a link of the form `<http://example.com>`
435 // Which are represented as a link to "http://example.com" with
436 // text "http://example.com" by pulldown-cmark
439 headers.safety |= in_heading && text.trim() == "Safety";
440 headers.errors |= in_heading && text.trim() == "Errors";
441 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
445 let (begin, span) = spans[index];
448 let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
449 check_code(cx, &text, edition, span);
452 // Adjust for the beginning of the current `Event`
453 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
455 check_text(cx, valid_idents, &text, span);
463 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
464 fn has_needless_main(code: &str, edition: Edition) -> bool {
465 rustc_driver::catch_fatal_errors(|| {
466 rustc_span::with_session_globals(edition, || {
467 let filename = FileName::anon_source_code(code);
469 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
470 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
471 let handler = Handler::with_emitter(false, None, box emitter);
472 let sess = ParseSess::with_span_handler(handler, sm);
474 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
477 for mut err in errs {
484 let mut relevant_main_found = false;
486 match parser.parse_item() {
487 Ok(Some(item)) => match &item.kind {
488 // Tests with one of these items are ignored
490 | ItemKind::Const(..)
491 | ItemKind::ExternCrate(..)
492 | ItemKind::ForeignMod(..) => return false,
493 // We found a main function ...
494 ItemKind::Fn(_, sig, _, Some(block)) if item.ident.name == sym::main => {
495 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
496 let returns_nothing = match &sig.decl.output {
497 FnRetTy::Default(..) => true,
498 FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
502 if returns_nothing && !is_async && !block.stmts.is_empty() {
503 // This main function should be linted, but only if there are no other functions
504 relevant_main_found = true;
506 // This main function should not be linted, we're done
510 // Another function was found; this case is ignored too
511 ItemKind::Fn(..) => return false,
529 if has_needless_main(text, edition) {
530 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
534 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
535 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
536 // Trim punctuation as in `some comment (see foo::bar).`
538 // Or even as in `_foo bar_` which is emphasized.
539 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
541 if valid_idents.contains(word) {
545 // Adjust for the current word
546 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
547 let span = Span::new(
548 span.lo() + BytePos::from_usize(offset),
549 span.lo() + BytePos::from_usize(offset + word.len()),
553 check_word(cx, word, span);
557 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
558 /// Checks if a string is camel-case, i.e., contains at least two uppercase
559 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
560 /// Plurals are also excluded (`IDs` is ok).
561 fn is_camel_case(s: &str) -> bool {
562 if s.starts_with(|c: char| c.is_digit(10)) {
566 let s = s.strip_suffix('s').unwrap_or(s);
568 s.chars().all(char::is_alphanumeric)
569 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
570 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
573 fn has_underscore(s: &str) -> bool {
574 s != "_" && !s.contains("\\_") && s.contains('_')
577 fn has_hyphen(s: &str) -> bool {
578 s != "-" && s.contains('-')
581 if let Ok(url) = Url::parse(word) {
582 // try to get around the fact that `foo::bar` parses as a valid URL
583 if !url.cannot_be_a_base() {
588 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
595 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
596 if has_underscore(word) && has_hyphen(word) {
600 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
605 &format!("you should put `{}` between ticks in the documentation", word),