1 use crate::utils::{get_trait_def_id, implements_trait, is_entrypoint_fn, match_type, paths, return_ty, span_lint};
2 use itertools::Itertools;
3 use rustc::lint::in_external_macro;
5 use rustc_data_structures::fx::FxHashSet;
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
9 use rustc_span::source_map::{BytePos, MultiSpan, Span};
12 use syntax::ast::{AttrKind, Attribute};
15 declare_clippy_lint! {
16 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
17 /// outside ticks in documentation.
19 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
20 /// camel-case probably indicates some code which should be included between
21 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
24 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
25 /// for is limited, and there are still false positives.
29 /// /// Do something with the foo_bar parameter. See also
30 /// /// that::other::module::foo.
31 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
32 /// fn doit(foo_bar: usize) {}
36 "presence of `_`, `::` or camel-case outside backticks in documentation"
39 declare_clippy_lint! {
40 /// **What it does:** Checks for the doc comments of publicly visible
41 /// unsafe functions and warns if there is no `# Safety` section.
43 /// **Why is this bad?** Unsafe functions should document their safety
44 /// preconditions, so that users can be sure they are using them safely.
46 /// **Known problems:** None.
50 ///# type Universe = ();
51 /// /// This function should really be documented
52 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
57 /// At least write a line about safety:
60 ///# type Universe = ();
63 /// /// This function should not be called before the horsemen are ready.
64 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
68 pub MISSING_SAFETY_DOC,
70 "`pub unsafe fn` without `# Safety` docs"
73 declare_clippy_lint! {
74 /// **What it does:** Checks the doc comments of publicly visible functions that
75 /// return a `Result` type and warns if there is no `# Errors` section.
77 /// **Why is this bad?** Documenting the type of errors that can be returned from a
78 /// function can help callers write code to handle the errors appropriately.
80 /// **Known problems:** None.
84 /// Since the following function returns a `Result` it has an `# Errors` section in
91 /// /// Will return `Err` if `filename` does not exist or the user does not have
92 /// /// permission to read it.
93 /// pub fn read(filename: String) -> io::Result<String> {
97 pub MISSING_ERRORS_DOC,
99 "`pub fn` returns `Result` without `# Errors` in doc comment"
102 declare_clippy_lint! {
103 /// **What it does:** Checks for `fn main() { .. }` in doctests
105 /// **Why is this bad?** The test can be shorter (and likely more readable)
106 /// if the `fn main()` is left implicit.
108 /// **Known problems:** None.
112 /// /// An example of a doctest with a `main()` function
118 /// /// // this needs not be in an `fn`
121 /// fn needless_main() {
122 /// unimplemented!();
125 pub NEEDLESS_DOCTEST_MAIN,
127 "presence of `fn main() {` in code examples"
130 #[allow(clippy::module_name_repetitions)]
132 pub struct DocMarkdown {
133 valid_idents: FxHashSet<String>,
138 pub fn new(valid_idents: FxHashSet<String>) -> Self {
141 in_trait_impl: false,
146 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
148 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown {
149 fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate<'_>) {
150 check_attrs(cx, &self.valid_idents, &krate.attrs);
153 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
154 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
156 hir::ItemKind::Fn(ref sig, _, body_id) => {
157 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id))
158 || in_external_macro(cx.tcx.sess, item.span))
160 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
163 hir::ItemKind::Impl {
164 of_trait: ref trait_ref,
167 self.in_trait_impl = trait_ref.is_some();
173 fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
174 if let hir::ItemKind::Impl { .. } = item.kind {
175 self.in_trait_impl = false;
179 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
180 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
181 if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
182 if !in_external_macro(cx.tcx.sess, item.span) {
183 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None);
188 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
189 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
190 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
193 if let hir::ImplItemKind::Method(ref sig, body_id) = item.kind {
194 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id));
199 fn lint_for_missing_headers<'a, 'tcx>(
200 cx: &LateContext<'a, 'tcx>,
202 span: impl Into<MultiSpan> + Copy,
203 sig: &hir::FnSig<'_>,
205 body_id: Option<hir::BodyId>,
207 if !cx.access_levels.is_exported(hir_id) {
208 return; // Private functions do not require doc comments
210 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
215 "unsafe function's docs miss `# Safety` section",
219 if match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
224 "docs for function returning `Result` missing `# Errors` section",
226 } else if let (Some(body_id), Some(future)) = (body_id, get_trait_def_id(cx, &paths::FUTURE)) {
227 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
228 let mir = cx.tcx.optimized_mir(def_id);
229 let ret_ty = mir.return_ty();
231 if implements_trait(cx, ret_ty, future, &[]) {
234 if let Opaque(_, subs) = ret_ty.kind {
235 if let Some(ty) = subs.types().next() {
236 if let Generator(_, subs, _) = ty.kind {
237 if match_type(cx, subs.as_generator().return_ty(def_id, cx.tcx), &paths::RESULT) {
242 "docs for function returning `Result` missing `# Errors` section",
253 /// Cleanup documentation decoration (`///` and such).
255 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
256 /// `syntax::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(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
262 // one-line comments lose their prefix
263 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
264 for prefix in ONELINERS {
265 if comment.starts_with(*prefix) {
266 let doc = &comment[prefix.len()..];
267 let mut doc = doc.to_owned();
271 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
276 if comment.starts_with("/*") {
277 let doc = &comment[3..comment.len() - 2];
278 let mut sizes = vec![];
279 let mut contains_initial_stars = false;
280 for line in doc.lines() {
281 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
282 debug_assert_eq!(offset as u32 as usize, offset);
283 contains_initial_stars |= line.trim_start().starts_with('*');
284 // +1 for the newline
285 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
287 if !contains_initial_stars {
288 return (doc.to_string(), sizes);
290 // remove the initial '*'s if any
291 let mut no_stars = String::with_capacity(doc.len());
292 for line in doc.lines() {
293 let mut chars = line.chars();
294 while let Some(c) = chars.next() {
295 if c.is_whitespace() {
298 no_stars.push(if c == '*' { ' ' } else { c });
302 no_stars.push_str(chars.as_str());
305 return (no_stars, sizes);
308 panic!("not a doc-comment: {}", comment);
311 #[derive(Copy, Clone)]
317 fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
318 let mut doc = String::new();
319 let mut spans = vec![];
322 if let AttrKind::DocComment(ref comment) = attr.kind {
323 let comment = comment.to_string();
324 let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
325 spans.extend_from_slice(¤t_spans);
326 doc.push_str(&comment);
327 } else if attr.check_name(sym!(doc)) {
328 // ignore mix of sugared and non-sugared doc
329 // don't trigger the safety or errors check
338 for &mut (ref mut offset, _) in &mut spans {
339 let offset_copy = *offset;
341 current += offset_copy;
351 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
352 // Iterate over all `Events` and combine consecutive events into one
353 let events = parser.coalesce(|previous, current| {
354 use pulldown_cmark::Event::*;
356 let previous_range = previous.1;
357 let current_range = current.1;
359 match (previous.0, current.0) {
360 (Text(previous), Text(current)) => {
361 let mut previous = previous.to_string();
362 previous.push_str(¤t);
363 Ok((Text(previous.into()), previous_range))
365 (previous, current) => Err(((previous, previous_range), (current, current_range))),
368 check_doc(cx, valid_idents, events, &spans)
371 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
372 cx: &LateContext<'_, '_>,
373 valid_idents: &FxHashSet<String>,
375 spans: &[(usize, Span)],
377 // true if a safety header was found
378 use pulldown_cmark::Event::*;
379 use pulldown_cmark::Tag::*;
381 let mut headers = DocHeaders {
385 let mut in_code = false;
386 let mut in_link = None;
387 let mut in_heading = false;
389 for (event, range) in events {
391 Start(CodeBlock(_)) => in_code = true,
392 End(CodeBlock(_)) => in_code = false,
393 Start(Link(_, url, _)) => in_link = Some(url),
394 End(Link(..)) => in_link = None,
395 Start(Heading(_)) => in_heading = true,
396 End(Heading(_)) => in_heading = false,
397 Start(_tag) | End(_tag) => (), // We don't care about other tags
398 Html(_html) => (), // HTML is weird, just ignore it
399 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
400 FootnoteReference(text) | Text(text) => {
401 if Some(&text) == in_link.as_ref() {
402 // Probably a link of the form `<http://example.com>`
403 // Which are represented as a link to "http://example.com" with
404 // text "http://example.com" by pulldown-cmark
407 headers.safety |= in_heading && text.trim() == "Safety";
408 headers.errors |= in_heading && text.trim() == "Errors";
409 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
413 let (begin, span) = spans[index];
415 check_code(cx, &text, span);
417 // Adjust for the beginning of the current `Event`
418 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
420 check_text(cx, valid_idents, &text, span);
428 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
430 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
431 if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
432 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
436 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
437 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
438 // Trim punctuation as in `some comment (see foo::bar).`
440 // Or even as in `_foo bar_` which is emphasized.
441 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
443 if valid_idents.contains(word) {
447 // Adjust for the current word
448 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
449 let span = Span::new(
450 span.lo() + BytePos::from_usize(offset),
451 span.lo() + BytePos::from_usize(offset + word.len()),
455 check_word(cx, word, span);
459 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
460 /// Checks if a string is camel-case, i.e., contains at least two uppercase
461 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
462 /// Plurals are also excluded (`IDs` is ok).
463 fn is_camel_case(s: &str) -> bool {
464 if s.starts_with(|c: char| c.is_digit(10)) {
468 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
470 s.chars().all(char::is_alphanumeric)
471 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
472 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
475 fn has_underscore(s: &str) -> bool {
476 s != "_" && !s.contains("\\_") && s.contains('_')
479 fn has_hyphen(s: &str) -> bool {
480 s != "-" && s.contains('-')
483 if let Ok(url) = Url::parse(word) {
484 // try to get around the fact that `foo::bar` parses as a valid URL
485 if !url.cannot_be_a_base() {
490 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
497 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
498 if has_underscore(word) && has_hyphen(word) {
502 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
507 &format!("you should put `{}` between ticks in the documentation", word),