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::{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 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
158 hir::ItemKind::Impl(_, _, _, _, ref trait_ref, ..) => {
159 self.in_trait_impl = trait_ref.is_some();
165 fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
166 if let hir::ItemKind::Impl(..) = item.kind {
167 self.in_trait_impl = false;
171 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
172 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
173 if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
174 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
178 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
179 let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
180 if self.in_trait_impl {
183 if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
184 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
189 fn lint_for_missing_headers<'a, 'tcx>(
190 cx: &LateContext<'a, 'tcx>,
192 span: impl Into<MultiSpan> + Copy,
193 sig: &hir::FnSig<'_>,
196 if !cx.access_levels.is_exported(hir_id) {
197 return; // Private functions do not require doc comments
199 if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
204 "unsafe function's docs miss `# Safety` section",
207 if !headers.errors && match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
212 "docs for function returning `Result` missing `# Errors` section",
217 /// Cleanup documentation decoration (`///` and such).
219 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
220 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
221 /// need to keep track of
222 /// the spans but this function is inspired from the later.
223 #[allow(clippy::cast_possible_truncation)]
225 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
226 // one-line comments lose their prefix
227 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
228 for prefix in ONELINERS {
229 if comment.starts_with(*prefix) {
230 let doc = &comment[prefix.len()..];
231 let mut doc = doc.to_owned();
235 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
240 if comment.starts_with("/*") {
241 let doc = &comment[3..comment.len() - 2];
242 let mut sizes = vec![];
243 let mut contains_initial_stars = false;
244 for line in doc.lines() {
245 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
246 debug_assert_eq!(offset as u32 as usize, offset);
247 contains_initial_stars |= line.trim_start().starts_with('*');
248 // +1 for the newline
249 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
251 if !contains_initial_stars {
252 return (doc.to_string(), sizes);
254 // remove the initial '*'s if any
255 let mut no_stars = String::with_capacity(doc.len());
256 for line in doc.lines() {
257 let mut chars = line.chars();
258 while let Some(c) = chars.next() {
259 if c.is_whitespace() {
262 no_stars.push(if c == '*' { ' ' } else { c });
266 no_stars.push_str(chars.as_str());
269 return (no_stars, sizes);
272 panic!("not a doc-comment: {}", comment);
275 #[derive(Copy, Clone)]
281 fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
282 let mut doc = String::new();
283 let mut spans = vec![];
286 if let AttrKind::DocComment(ref comment) = attr.kind {
287 let comment = comment.to_string();
288 let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
289 spans.extend_from_slice(¤t_spans);
290 doc.push_str(&comment);
291 } else if attr.check_name(sym!(doc)) {
292 // ignore mix of sugared and non-sugared doc
293 // don't trigger the safety or errors check
302 for &mut (ref mut offset, _) in &mut spans {
303 let offset_copy = *offset;
305 current += offset_copy;
315 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
316 // Iterate over all `Events` and combine consecutive events into one
317 let events = parser.coalesce(|previous, current| {
318 use pulldown_cmark::Event::*;
320 let previous_range = previous.1;
321 let current_range = current.1;
323 match (previous.0, current.0) {
324 (Text(previous), Text(current)) => {
325 let mut previous = previous.to_string();
326 previous.push_str(¤t);
327 Ok((Text(previous.into()), previous_range))
329 (previous, current) => Err(((previous, previous_range), (current, current_range))),
332 check_doc(cx, valid_idents, events, &spans)
335 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
336 cx: &LateContext<'_, '_>,
337 valid_idents: &FxHashSet<String>,
339 spans: &[(usize, Span)],
341 // true if a safety header was found
342 use pulldown_cmark::Event::*;
343 use pulldown_cmark::Tag::*;
345 let mut headers = DocHeaders {
349 let mut in_code = false;
350 let mut in_link = None;
351 let mut in_heading = false;
353 for (event, range) in events {
355 Start(CodeBlock(_)) => in_code = true,
356 End(CodeBlock(_)) => in_code = false,
357 Start(Link(_, url, _)) => in_link = Some(url),
358 End(Link(..)) => in_link = None,
359 Start(Heading(_)) => in_heading = true,
360 End(Heading(_)) => in_heading = false,
361 Start(_tag) | End(_tag) => (), // We don't care about other tags
362 Html(_html) => (), // HTML is weird, just ignore it
363 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
364 FootnoteReference(text) | Text(text) => {
365 if Some(&text) == in_link.as_ref() {
366 // Probably a link of the form `<http://example.com>`
367 // Which are represented as a link to "http://example.com" with
368 // text "http://example.com" by pulldown-cmark
371 headers.safety |= in_heading && text.trim() == "Safety";
372 headers.errors |= in_heading && text.trim() == "Errors";
373 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
377 let (begin, span) = spans[index];
379 check_code(cx, &text, span);
381 // Adjust for the beginning of the current `Event`
382 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
384 check_text(cx, valid_idents, &text, span);
392 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
394 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
395 if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
396 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
400 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
401 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
402 // Trim punctuation as in `some comment (see foo::bar).`
404 // Or even as in `_foo bar_` which is emphasized.
405 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
407 if valid_idents.contains(word) {
411 // Adjust for the current word
412 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
413 let span = Span::new(
414 span.lo() + BytePos::from_usize(offset),
415 span.lo() + BytePos::from_usize(offset + word.len()),
419 check_word(cx, word, span);
423 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
424 /// Checks if a string is camel-case, i.e., contains at least two uppercase
425 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
426 /// Plurals are also excluded (`IDs` is ok).
427 fn is_camel_case(s: &str) -> bool {
428 if s.starts_with(|c: char| c.is_digit(10)) {
432 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
434 s.chars().all(char::is_alphanumeric)
435 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
436 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
439 fn has_underscore(s: &str) -> bool {
440 s != "_" && !s.contains("\\_") && s.contains('_')
443 fn has_hyphen(s: &str) -> bool {
444 s != "-" && s.contains('-')
447 if let Ok(url) = Url::parse(word) {
448 // try to get around the fact that `foo::bar` parses as a valid URL
449 if !url.cannot_be_a_base() {
454 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
461 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
462 if has_underscore(word) && has_hyphen(word) {
466 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
471 &format!("you should put `{}` between ticks in the documentation", word),