1 use crate::utils::{match_type, paths, return_ty, span_lint};
2 use itertools::Itertools;
4 use rustc::impl_lint_pass;
5 use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintPass};
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_session::declare_tool_lint;
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 !in_external_macro(cx.tcx.sess, item.span) {
157 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
160 hir::ItemKind::Impl(_, _, _, _, ref trait_ref, ..) => {
161 self.in_trait_impl = trait_ref.is_some();
167 fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
168 if let hir::ItemKind::Impl(..) = item.kind {
169 self.in_trait_impl = false;
173 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
174 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
175 if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
176 if !in_external_macro(cx.tcx.sess, item.span) {
177 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
182 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
183 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
184 if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
187 if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
188 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
193 fn lint_for_missing_headers<'a, 'tcx>(
194 cx: &LateContext<'a, 'tcx>,
196 span: impl Into<MultiSpan> + Copy,
197 sig: &hir::FnSig<'_>,
200 if !cx.access_levels.is_exported(hir_id) {
201 return; // Private functions do not require doc comments
203 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
208 "unsafe function's docs miss `# Safety` section",
211 if !headers.errors && match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
216 "docs for function returning `Result` missing `# Errors` section",
221 /// Cleanup documentation decoration (`///` and such).
223 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
224 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
225 /// need to keep track of
226 /// the spans but this function is inspired from the later.
227 #[allow(clippy::cast_possible_truncation)]
229 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
230 // one-line comments lose their prefix
231 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
232 for prefix in ONELINERS {
233 if comment.starts_with(*prefix) {
234 let doc = &comment[prefix.len()..];
235 let mut doc = doc.to_owned();
239 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
244 if comment.starts_with("/*") {
245 let doc = &comment[3..comment.len() - 2];
246 let mut sizes = vec![];
247 let mut contains_initial_stars = false;
248 for line in doc.lines() {
249 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
250 debug_assert_eq!(offset as u32 as usize, offset);
251 contains_initial_stars |= line.trim_start().starts_with('*');
252 // +1 for the newline
253 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
255 if !contains_initial_stars {
256 return (doc.to_string(), sizes);
258 // remove the initial '*'s if any
259 let mut no_stars = String::with_capacity(doc.len());
260 for line in doc.lines() {
261 let mut chars = line.chars();
262 while let Some(c) = chars.next() {
263 if c.is_whitespace() {
266 no_stars.push(if c == '*' { ' ' } else { c });
270 no_stars.push_str(chars.as_str());
273 return (no_stars, sizes);
276 panic!("not a doc-comment: {}", comment);
279 #[derive(Copy, Clone)]
285 fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
286 let mut doc = String::new();
287 let mut spans = vec![];
290 if let AttrKind::DocComment(ref comment) = attr.kind {
291 let comment = comment.to_string();
292 let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
293 spans.extend_from_slice(¤t_spans);
294 doc.push_str(&comment);
295 } else if attr.check_name(sym!(doc)) {
296 // ignore mix of sugared and non-sugared doc
297 // don't trigger the safety or errors check
306 for &mut (ref mut offset, _) in &mut spans {
307 let offset_copy = *offset;
309 current += offset_copy;
319 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
320 // Iterate over all `Events` and combine consecutive events into one
321 let events = parser.coalesce(|previous, current| {
322 use pulldown_cmark::Event::*;
324 let previous_range = previous.1;
325 let current_range = current.1;
327 match (previous.0, current.0) {
328 (Text(previous), Text(current)) => {
329 let mut previous = previous.to_string();
330 previous.push_str(¤t);
331 Ok((Text(previous.into()), previous_range))
333 (previous, current) => Err(((previous, previous_range), (current, current_range))),
336 check_doc(cx, valid_idents, events, &spans)
339 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
340 cx: &LateContext<'_, '_>,
341 valid_idents: &FxHashSet<String>,
343 spans: &[(usize, Span)],
345 // true if a safety header was found
346 use pulldown_cmark::Event::*;
347 use pulldown_cmark::Tag::*;
349 let mut headers = DocHeaders {
353 let mut in_code = false;
354 let mut in_link = None;
355 let mut in_heading = false;
357 for (event, range) in events {
359 Start(CodeBlock(_)) => in_code = true,
360 End(CodeBlock(_)) => in_code = false,
361 Start(Link(_, url, _)) => in_link = Some(url),
362 End(Link(..)) => in_link = None,
363 Start(Heading(_)) => in_heading = true,
364 End(Heading(_)) => in_heading = false,
365 Start(_tag) | End(_tag) => (), // We don't care about other tags
366 Html(_html) => (), // HTML is weird, just ignore it
367 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
368 FootnoteReference(text) | Text(text) => {
369 if Some(&text) == in_link.as_ref() {
370 // Probably a link of the form `<http://example.com>`
371 // Which are represented as a link to "http://example.com" with
372 // text "http://example.com" by pulldown-cmark
375 headers.safety |= in_heading && text.trim() == "Safety";
376 headers.errors |= in_heading && text.trim() == "Errors";
377 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
381 let (begin, span) = spans[index];
383 check_code(cx, &text, span);
385 // Adjust for the beginning of the current `Event`
386 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
388 check_text(cx, valid_idents, &text, span);
396 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
398 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
399 if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
400 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
404 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
405 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
406 // Trim punctuation as in `some comment (see foo::bar).`
408 // Or even as in `_foo bar_` which is emphasized.
409 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
411 if valid_idents.contains(word) {
415 // Adjust for the current word
416 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
417 let span = Span::new(
418 span.lo() + BytePos::from_usize(offset),
419 span.lo() + BytePos::from_usize(offset + word.len()),
423 check_word(cx, word, span);
427 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
428 /// Checks if a string is camel-case, i.e., contains at least two uppercase
429 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
430 /// Plurals are also excluded (`IDs` is ok).
431 fn is_camel_case(s: &str) -> bool {
432 if s.starts_with(|c: char| c.is_digit(10)) {
436 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
438 s.chars().all(char::is_alphanumeric)
439 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
440 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
443 fn has_underscore(s: &str) -> bool {
444 s != "_" && !s.contains("\\_") && s.contains('_')
447 fn has_hyphen(s: &str) -> bool {
448 s != "-" && s.contains('-')
451 if let Ok(url) = Url::parse(word) {
452 // try to get around the fact that `foo::bar` parses as a valid URL
453 if !url.cannot_be_a_base() {
458 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
465 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
466 if has_underscore(word) && has_hyphen(word) {
470 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
475 &format!("you should put `{}` between ticks in the documentation", word),