1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
11 use itertools::Itertools;
13 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::syntax::ast;
16 use crate::syntax::source_map::{BytePos, Span};
17 use crate::syntax_pos::Pos;
18 use crate::utils::span_lint;
21 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
22 /// outside ticks in documentation.
24 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
25 /// camel-case probably indicates some code which should be included between
26 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
29 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
30 /// for is limited, and there are still false positives.
34 /// /// Do something with the foo_bar parameter. See also
35 /// /// that::other::module::foo.
36 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
37 /// fn doit(foo_bar) { .. }
39 declare_clippy_lint! {
42 "presence of `_`, `::` or camel-case outside backticks in documentation"
47 valid_idents: Vec<String>,
51 pub fn new(valid_idents: Vec<String>) -> Self {
58 impl LintPass for Doc {
59 fn get_lints(&self) -> LintArray {
60 lint_array![DOC_MARKDOWN]
64 impl EarlyLintPass for Doc {
65 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
66 check_attrs(cx, &self.valid_idents, &krate.attrs);
69 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
70 check_attrs(cx, &self.valid_idents, &item.attrs);
75 parser: pulldown_cmark::Parser<'a>,
79 fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
84 impl<'a> Iterator for Parser<'a> {
85 type Item = (usize, pulldown_cmark::Event<'a>);
87 fn next(&mut self) -> Option<Self::Item> {
88 let offset = self.parser.get_offset();
89 self.parser.next().map(|event| (offset, event))
93 /// Cleanup documentation decoration (`///` and such).
95 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
96 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
97 /// need to keep track of
98 /// the spans but this function is inspired from the later.
99 #[allow(clippy::cast_possible_truncation)]
100 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
101 // one-line comments lose their prefix
102 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
103 for prefix in ONELINERS {
104 if comment.starts_with(*prefix) {
105 let doc = &comment[prefix.len()..];
106 let mut doc = doc.to_owned();
111 (doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32))),
117 if comment.starts_with("/*") {
118 let doc = &comment[3..comment.len() - 2];
119 let mut sizes = vec![];
120 let mut contains_initial_stars = false;
121 for line in doc.lines() {
122 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
123 debug_assert_eq!(offset as u32 as usize, offset);
124 contains_initial_stars |= line.trim_left().starts_with('*');
125 // +1 for the newline
126 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
128 if !contains_initial_stars {
129 return (doc.to_string(), sizes);
131 // remove the initial '*'s if any
132 let mut no_stars = String::with_capacity(doc.len());
133 for line in doc.lines() {
134 let mut chars = line.chars();
135 while let Some(c) = chars.next() {
136 if c.is_whitespace() {
139 no_stars.push(if c == '*' { ' ' } else { c });
143 no_stars.push_str(chars.as_str());
146 return (no_stars, sizes);
149 panic!("not a doc-comment: {}", comment);
152 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
153 let mut doc = String::new();
154 let mut spans = vec![];
157 if attr.is_sugared_doc {
158 if let Some(ref current) = attr.value_str() {
159 let current = current.to_string();
160 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
161 spans.extend_from_slice(¤t_spans);
162 doc.push_str(¤t);
164 } else if attr.name() == "doc" {
165 // ignore mix of sugared and non-sugared doc
171 for &mut (ref mut offset, _) in &mut spans {
172 let offset_copy = *offset;
174 current += offset_copy;
178 let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
179 let parser = parser.coalesce(|x, y| {
180 use pulldown_cmark::Event::*;
186 (Text(x), Text(y)) => {
187 let mut x = x.into_owned();
189 Ok((x_offset, Text(x.into())))
191 (x, y) => Err(((x_offset, x), (y_offset, y))),
194 check_doc(cx, valid_idents, parser, &spans);
198 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
199 cx: &EarlyContext<'_>,
200 valid_idents: &[String],
202 spans: &[(usize, Span)],
204 use pulldown_cmark::Event::*;
205 use pulldown_cmark::Tag::*;
207 let mut in_code = false;
208 let mut in_link = None;
210 for (offset, event) in docs {
212 Start(CodeBlock(_)) | Start(Code) => in_code = true,
213 End(CodeBlock(_)) | End(Code) => in_code = false,
214 Start(Link(link, _)) => in_link = Some(link),
215 End(Link(_, _)) => in_link = None,
216 Start(_tag) | End(_tag) => (), // We don't care about other tags
217 Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
218 SoftBreak | HardBreak => (),
219 FootnoteReference(text) | Text(text) => {
220 if Some(&text) == in_link.as_ref() {
221 // Probably a link of the form `<http://example.com>`
222 // Which are represented as a link to "http://example.com" with
223 // text "http://example.com" by pulldown-cmark
228 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
233 let (begin, span) = spans[index];
235 // Adjust for the beginning of the current `Event`
236 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
238 check_text(cx, valid_idents, &text, span);
245 fn check_text(cx: &EarlyContext<'_>, valid_idents: &[String], text: &str, span: Span) {
246 for word in text.split_whitespace() {
247 // Trim punctuation as in `some comment (see foo::bar).`
249 // Or even as in `_foo bar_` which is emphasized.
250 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
252 if valid_idents.iter().any(|i| i == word) {
256 // Adjust for the current word
257 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
258 let span = Span::new(
259 span.lo() + BytePos::from_usize(offset),
260 span.lo() + BytePos::from_usize(offset + word.len()),
264 check_word(cx, word, span);
268 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
269 /// Checks if a string is camel-case, ie. contains at least two uppercase
270 /// letter (`Clippy` is
271 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
273 fn is_camel_case(s: &str) -> bool {
274 if s.starts_with(|c: char| c.is_digit(10)) {
278 let s = if s.ends_with('s') {
284 s.chars().all(char::is_alphanumeric) && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
285 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
288 fn has_underscore(s: &str) -> bool {
289 s != "_" && !s.contains("\\_") && s.contains('_')
292 if let Ok(url) = Url::parse(word) {
293 // try to get around the fact that `foo::bar` parses as a valid URL
294 if !url.cannot_be_a_base() {
299 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
306 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
311 &format!("you should put `{}` between ticks in the documentation", word),