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::{AttrKind, Attribute};
5 use rustc_ast::token::CommentKind;
6 use rustc_data_structures::fx::FxHashSet;
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_middle::lint::in_external_macro;
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::source_map::{BytePos, MultiSpan, Span};
17 declare_clippy_lint! {
18 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
19 /// outside ticks in documentation.
21 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
22 /// camel-case probably indicates some code which should be included between
23 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
26 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
27 /// for is limited, and there are still false positives.
31 /// /// Do something with the foo_bar parameter. See also
32 /// /// that::other::module::foo.
33 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
34 /// fn doit(foo_bar: usize) {}
38 "presence of `_`, `::` or camel-case outside backticks in documentation"
41 declare_clippy_lint! {
42 /// **What it does:** Checks for the doc comments of publicly visible
43 /// unsafe functions and warns if there is no `# Safety` section.
45 /// **Why is this bad?** Unsafe functions should document their safety
46 /// preconditions, so that users can be sure they are using them safely.
48 /// **Known problems:** None.
52 ///# type Universe = ();
53 /// /// This function should really be documented
54 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
59 /// At least write a line about safety:
62 ///# type Universe = ();
65 /// /// This function should not be called before the horsemen are ready.
66 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
70 pub MISSING_SAFETY_DOC,
72 "`pub unsafe fn` without `# Safety` docs"
75 declare_clippy_lint! {
76 /// **What it does:** Checks the doc comments of publicly visible functions that
77 /// return a `Result` type and warns if there is no `# Errors` section.
79 /// **Why is this bad?** Documenting the type of errors that can be returned from a
80 /// function can help callers write code to handle the errors appropriately.
82 /// **Known problems:** None.
86 /// Since the following function returns a `Result` it has an `# Errors` section in
93 /// /// Will return `Err` if `filename` does not exist or the user does not have
94 /// /// permission to read it.
95 /// pub fn read(filename: String) -> io::Result<String> {
99 pub MISSING_ERRORS_DOC,
101 "`pub fn` returns `Result` without `# Errors` in doc comment"
104 declare_clippy_lint! {
105 /// **What it does:** Checks for `fn main() { .. }` in doctests
107 /// **Why is this bad?** The test can be shorter (and likely more readable)
108 /// if the `fn main()` is left implicit.
110 /// **Known problems:** None.
114 /// /// An example of a doctest with a `main()` function
120 /// /// // this needs not be in an `fn`
123 /// fn needless_main() {
124 /// unimplemented!();
127 pub NEEDLESS_DOCTEST_MAIN,
129 "presence of `fn main() {` in code examples"
132 #[allow(clippy::module_name_repetitions)]
134 pub struct DocMarkdown {
135 valid_idents: FxHashSet<String>,
140 pub fn new(valid_idents: FxHashSet<String>) -> Self {
143 in_trait_impl: false,
148 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
150 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
151 fn check_crate(&mut self, cx: &LateContext<'tcx>, krate: &'tcx hir::Crate<'_>) {
152 check_attrs(cx, &self.valid_idents, &krate.item.attrs);
155 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
156 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
158 hir::ItemKind::Fn(ref sig, _, body_id) => {
159 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id).to_def_id())
160 || in_external_macro(cx.tcx.sess, item.span))
162 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
165 hir::ItemKind::Impl {
166 of_trait: ref trait_ref,
169 self.in_trait_impl = trait_ref.is_some();
175 fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
176 if let hir::ItemKind::Impl { .. } = item.kind {
177 self.in_trait_impl = false;
181 fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
182 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
183 if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
184 if !in_external_macro(cx.tcx.sess, item.span) {
185 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
190 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
191 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
192 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
195 if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
196 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
201 fn lint_for_missing_headers<'tcx>(
202 cx: &LateContext<'tcx>,
204 span: impl Into<MultiSpan> + Copy,
205 sig: &hir::FnSig<'_>,
207 body_id: Option<hir::BodyId>,
209 if !cx.access_levels.is_exported(hir_id) {
210 return; // Private functions do not require doc comments
212 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
217 "unsafe function's docs miss `# Safety` section",
221 if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym!(result_type)) {
226 "docs for function returning `Result` missing `# Errors` section",
230 if let Some(body_id) = body_id;
231 if let Some(future) = cx.tcx.lang_items().future_trait();
232 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
233 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
234 let ret_ty = mir.return_ty();
235 if implements_trait(cx, ret_ty, future, &[]);
236 if let ty::Opaque(_, subs) = ret_ty.kind;
237 if let Some(gen) = subs.types().next();
238 if let ty::Generator(_, subs, _) = gen.kind;
239 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym!(result_type));
245 "docs for function returning `Result` missing `# Errors` section",
253 /// Cleanup documentation decoration.
255 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
256 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
257 /// need to keep track of
258 /// the spans but this function is inspired from the later.
259 #[allow(clippy::cast_possible_truncation)]
261 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
262 // one-line comments lose their prefix
263 if comment_kind == CommentKind::Line {
264 let mut doc = doc.to_owned();
267 // +3 skips the opening delimiter
268 return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
271 let mut sizes = vec![];
272 let mut contains_initial_stars = false;
273 for line in doc.lines() {
274 let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
275 debug_assert_eq!(offset as u32 as usize, offset);
276 contains_initial_stars |= line.trim_start().starts_with('*');
277 // +1 adds the newline, +3 skips the opening delimiter
278 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
280 if !contains_initial_stars {
281 return (doc.to_string(), sizes);
283 // remove the initial '*'s if any
284 let mut no_stars = String::with_capacity(doc.len());
285 for line in doc.lines() {
286 let mut chars = line.chars();
287 while let Some(c) = chars.next() {
288 if c.is_whitespace() {
291 no_stars.push(if c == '*' { ' ' } else { c });
295 no_stars.push_str(chars.as_str());
302 #[derive(Copy, Clone)]
308 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
309 let mut doc = String::new();
310 let mut spans = vec![];
313 if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
314 let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
315 spans.extend_from_slice(¤t_spans);
316 doc.push_str(&comment);
317 } else if attr.has_name(sym!(doc)) {
318 // ignore mix of sugared and non-sugared doc
319 // don't trigger the safety or errors check
328 for &mut (ref mut offset, _) in &mut spans {
329 let offset_copy = *offset;
331 current += offset_copy;
341 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
342 // Iterate over all `Events` and combine consecutive events into one
343 let events = parser.coalesce(|previous, current| {
344 use pulldown_cmark::Event::Text;
346 let previous_range = previous.1;
347 let current_range = current.1;
349 match (previous.0, current.0) {
350 (Text(previous), Text(current)) => {
351 let mut previous = previous.to_string();
352 previous.push_str(¤t);
353 Ok((Text(previous.into()), previous_range))
355 (previous, current) => Err(((previous, previous_range), (current, current_range))),
358 check_doc(cx, valid_idents, events, &spans)
361 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail", "edition2018"];
363 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
364 cx: &LateContext<'_>,
365 valid_idents: &FxHashSet<String>,
367 spans: &[(usize, Span)],
369 // true if a safety header was found
370 use pulldown_cmark::CodeBlockKind;
371 use pulldown_cmark::Event::{
372 Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
374 use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
376 let mut headers = DocHeaders {
380 let mut in_code = false;
381 let mut in_link = None;
382 let mut in_heading = false;
383 let mut is_rust = false;
384 for (event, range) in events {
386 Start(CodeBlock(ref kind)) => {
388 if let CodeBlockKind::Fenced(lang) = kind {
390 lang.is_empty() || !lang.contains("ignore") && lang.split(',').any(|i| RUST_CODE.contains(&i));
393 End(CodeBlock(_)) => {
397 Start(Link(_, url, _)) => in_link = Some(url),
398 End(Link(..)) => in_link = None,
399 Start(Heading(_)) => in_heading = true,
400 End(Heading(_)) => in_heading = false,
401 Start(_tag) | End(_tag) => (), // We don't care about other tags
402 Html(_html) => (), // HTML is weird, just ignore it
403 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
404 FootnoteReference(text) | Text(text) => {
405 if Some(&text) == in_link.as_ref() {
406 // Probably a link of the form `<http://example.com>`
407 // Which are represented as a link to "http://example.com" with
408 // text "http://example.com" by pulldown-cmark
411 headers.safety |= in_heading && text.trim() == "Safety";
412 headers.errors |= in_heading && text.trim() == "Errors";
413 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
417 let (begin, span) = spans[index];
420 check_code(cx, &text, span);
423 // Adjust for the beginning of the current `Event`
424 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
426 check_text(cx, valid_idents, &text, span);
434 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate", "async fn main() {"];
436 fn check_code(cx: &LateContext<'_>, text: &str, span: Span) {
437 if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
438 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
442 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
443 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
444 // Trim punctuation as in `some comment (see foo::bar).`
446 // Or even as in `_foo bar_` which is emphasized.
447 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
449 if valid_idents.contains(word) {
453 // Adjust for the current word
454 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
455 let span = Span::new(
456 span.lo() + BytePos::from_usize(offset),
457 span.lo() + BytePos::from_usize(offset + word.len()),
461 check_word(cx, word, span);
465 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
466 /// Checks if a string is camel-case, i.e., contains at least two uppercase
467 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
468 /// Plurals are also excluded (`IDs` is ok).
469 fn is_camel_case(s: &str) -> bool {
470 if s.starts_with(|c: char| c.is_digit(10)) {
474 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
476 s.chars().all(char::is_alphanumeric)
477 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
478 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
481 fn has_underscore(s: &str) -> bool {
482 s != "_" && !s.contains("\\_") && s.contains('_')
485 fn has_hyphen(s: &str) -> bool {
486 s != "-" && s.contains('-')
489 if let Ok(url) = Url::parse(word) {
490 // try to get around the fact that `foo::bar` parses as a valid URL
491 if !url.cannot_be_a_base() {
496 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
503 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
504 if has_underscore(word) && has_hyphen(word) {
508 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
513 &format!("you should put `{}` between ticks in the documentation", word),