1 use crate::utils::{is_entrypoint_fn, match_type, paths, return_ty, span_lint};
2 use itertools::Itertools;
3 use rustc::lint::in_external_macro;
4 use rustc_data_structures::fx::FxHashSet;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_span::source_map::{BytePos, MultiSpan, Span};
11 use syntax::ast::{AttrKind, Attribute};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
16 /// outside ticks in documentation.
18 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
19 /// camel-case probably indicates some code which should be included between
20 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
23 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
24 /// for is limited, and there are still false positives.
28 /// /// Do something with the foo_bar parameter. See also
29 /// /// that::other::module::foo.
30 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
31 /// fn doit(foo_bar: usize) {}
35 "presence of `_`, `::` or camel-case outside backticks in documentation"
38 declare_clippy_lint! {
39 /// **What it does:** Checks for the doc comments of publicly visible
40 /// unsafe functions and warns if there is no `# Safety` section.
42 /// **Why is this bad?** Unsafe functions should document their safety
43 /// preconditions, so that users can be sure they are using them safely.
45 /// **Known problems:** None.
49 ///# type Universe = ();
50 /// /// This function should really be documented
51 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
56 /// At least write a line about safety:
59 ///# type Universe = ();
62 /// /// This function should not be called before the horsemen are ready.
63 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
67 pub MISSING_SAFETY_DOC,
69 "`pub unsafe fn` without `# Safety` docs"
72 declare_clippy_lint! {
73 /// **What it does:** Checks the doc comments of publicly visible functions that
74 /// return a `Result` type and warns if there is no `# Errors` section.
76 /// **Why is this bad?** Documenting the type of errors that can be returned from a
77 /// function can help callers write code to handle the errors appropriately.
79 /// **Known problems:** None.
83 /// Since the following function returns a `Result` it has an `# Errors` section in
90 /// /// Will return `Err` if `filename` does not exist or the user does not have
91 /// /// permission to read it.
92 /// pub fn read(filename: String) -> io::Result<String> {
96 pub MISSING_ERRORS_DOC,
98 "`pub fn` returns `Result` without `# Errors` in doc comment"
101 declare_clippy_lint! {
102 /// **What it does:** Checks for `fn main() { .. }` in doctests
104 /// **Why is this bad?** The test can be shorter (and likely more readable)
105 /// if the `fn main()` is left implicit.
107 /// **Known problems:** None.
111 /// /// An example of a doctest with a `main()` function
117 /// /// // this needs not be in an `fn`
120 /// fn needless_main() {
121 /// unimplemented!();
124 pub NEEDLESS_DOCTEST_MAIN,
126 "presence of `fn main() {` in code examples"
129 #[allow(clippy::module_name_repetitions)]
131 pub struct DocMarkdown {
132 valid_idents: FxHashSet<String>,
137 pub fn new(valid_idents: FxHashSet<String>) -> Self {
140 in_trait_impl: false,
145 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
147 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown {
148 fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate<'_>) {
149 check_attrs(cx, &self.valid_idents, &krate.attrs);
152 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
153 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
155 hir::ItemKind::Fn(ref sig, ..) => {
156 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id))
157 || in_external_macro(cx.tcx.sess, item.span))
159 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
162 hir::ItemKind::Impl(_, _, _, _, ref trait_ref, ..) => {
163 self.in_trait_impl = trait_ref.is_some();
169 fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
170 if let hir::ItemKind::Impl(..) = item.kind {
171 self.in_trait_impl = false;
175 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
176 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
177 if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
178 if !in_external_macro(cx.tcx.sess, item.span) {
179 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
184 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
185 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
186 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
189 if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
190 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
195 fn lint_for_missing_headers<'a, 'tcx>(
196 cx: &LateContext<'a, 'tcx>,
198 span: impl Into<MultiSpan> + Copy,
199 sig: &hir::FnSig<'_>,
202 if !cx.access_levels.is_exported(hir_id) {
203 return; // Private functions do not require doc comments
205 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
210 "unsafe function's docs miss `# Safety` section",
213 if !headers.errors && match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
218 "docs for function returning `Result` missing `# Errors` section",
223 /// Cleanup documentation decoration (`///` and such).
225 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
226 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
227 /// need to keep track of
228 /// the spans but this function is inspired from the later.
229 #[allow(clippy::cast_possible_truncation)]
231 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
232 // one-line comments lose their prefix
233 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
234 for prefix in ONELINERS {
235 if comment.starts_with(*prefix) {
236 let doc = &comment[prefix.len()..];
237 let mut doc = doc.to_owned();
241 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
246 if comment.starts_with("/*") {
247 let doc = &comment[3..comment.len() - 2];
248 let mut sizes = vec![];
249 let mut contains_initial_stars = false;
250 for line in doc.lines() {
251 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
252 debug_assert_eq!(offset as u32 as usize, offset);
253 contains_initial_stars |= line.trim_start().starts_with('*');
254 // +1 for the newline
255 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
257 if !contains_initial_stars {
258 return (doc.to_string(), sizes);
260 // remove the initial '*'s if any
261 let mut no_stars = String::with_capacity(doc.len());
262 for line in doc.lines() {
263 let mut chars = line.chars();
264 while let Some(c) = chars.next() {
265 if c.is_whitespace() {
268 no_stars.push(if c == '*' { ' ' } else { c });
272 no_stars.push_str(chars.as_str());
275 return (no_stars, sizes);
278 panic!("not a doc-comment: {}", comment);
281 #[derive(Copy, Clone)]
287 fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
288 let mut doc = String::new();
289 let mut spans = vec![];
292 if let AttrKind::DocComment(ref comment) = attr.kind {
293 let comment = comment.to_string();
294 let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
295 spans.extend_from_slice(¤t_spans);
296 doc.push_str(&comment);
297 } else if attr.check_name(sym!(doc)) {
298 // ignore mix of sugared and non-sugared doc
299 // don't trigger the safety or errors check
308 for &mut (ref mut offset, _) in &mut spans {
309 let offset_copy = *offset;
311 current += offset_copy;
321 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
322 // Iterate over all `Events` and combine consecutive events into one
323 let events = parser.coalesce(|previous, current| {
324 use pulldown_cmark::Event::*;
326 let previous_range = previous.1;
327 let current_range = current.1;
329 match (previous.0, current.0) {
330 (Text(previous), Text(current)) => {
331 let mut previous = previous.to_string();
332 previous.push_str(¤t);
333 Ok((Text(previous.into()), previous_range))
335 (previous, current) => Err(((previous, previous_range), (current, current_range))),
338 check_doc(cx, valid_idents, events, &spans)
341 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
342 cx: &LateContext<'_, '_>,
343 valid_idents: &FxHashSet<String>,
345 spans: &[(usize, Span)],
347 // true if a safety header was found
348 use pulldown_cmark::Event::*;
349 use pulldown_cmark::Tag::*;
351 let mut headers = DocHeaders {
355 let mut in_code = false;
356 let mut in_link = None;
357 let mut in_heading = false;
359 for (event, range) in events {
361 Start(CodeBlock(_)) => in_code = true,
362 End(CodeBlock(_)) => in_code = false,
363 Start(Link(_, url, _)) => in_link = Some(url),
364 End(Link(..)) => in_link = None,
365 Start(Heading(_)) => in_heading = true,
366 End(Heading(_)) => in_heading = false,
367 Start(_tag) | End(_tag) => (), // We don't care about other tags
368 Html(_html) => (), // HTML is weird, just ignore it
369 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
370 FootnoteReference(text) | Text(text) => {
371 if Some(&text) == in_link.as_ref() {
372 // Probably a link of the form `<http://example.com>`
373 // Which are represented as a link to "http://example.com" with
374 // text "http://example.com" by pulldown-cmark
377 headers.safety |= in_heading && text.trim() == "Safety";
378 headers.errors |= in_heading && text.trim() == "Errors";
379 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
383 let (begin, span) = spans[index];
385 check_code(cx, &text, span);
387 // Adjust for the beginning of the current `Event`
388 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
390 check_text(cx, valid_idents, &text, span);
398 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
400 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
401 if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
402 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
406 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
407 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
408 // Trim punctuation as in `some comment (see foo::bar).`
410 // Or even as in `_foo bar_` which is emphasized.
411 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
413 if valid_idents.contains(word) {
417 // Adjust for the current word
418 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
419 let span = Span::new(
420 span.lo() + BytePos::from_usize(offset),
421 span.lo() + BytePos::from_usize(offset + word.len()),
425 check_word(cx, word, span);
429 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
430 /// Checks if a string is camel-case, i.e., contains at least two uppercase
431 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
432 /// Plurals are also excluded (`IDs` is ok).
433 fn is_camel_case(s: &str) -> bool {
434 if s.starts_with(|c: char| c.is_digit(10)) {
438 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
440 s.chars().all(char::is_alphanumeric)
441 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
442 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
445 fn has_underscore(s: &str) -> bool {
446 s != "_" && !s.contains("\\_") && s.contains('_')
449 fn has_hyphen(s: &str) -> bool {
450 s != "-" && s.contains('-')
453 if let Ok(url) = Url::parse(word) {
454 // try to get around the fact that `foo::bar` parses as a valid URL
455 if !url.cannot_be_a_base() {
460 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
467 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
468 if has_underscore(word) && has_hyphen(word) {
472 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
477 &format!("you should put `{}` between ticks in the documentation", word),