1 use itertools::Itertools;
4 use rustc::{declare_lint, lint_array};
6 use syntax::source_map::{BytePos, Span};
8 use crate::utils::span_lint;
11 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
12 /// outside ticks in documentation.
14 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
15 /// camel-case probably indicates some code which should be included between
16 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
19 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
20 /// for is limited, and there are still false positives.
24 /// /// Do something with the foo_bar parameter. See also
25 /// /// that::other::module::foo.
26 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
27 /// fn doit(foo_bar) { .. }
29 declare_clippy_lint! {
32 "presence of `_`, `::` or camel-case outside backticks in documentation"
37 valid_idents: Vec<String>,
41 pub fn new(valid_idents: Vec<String>) -> Self {
48 impl LintPass for Doc {
49 fn get_lints(&self) -> LintArray {
50 lint_array![DOC_MARKDOWN]
54 impl EarlyLintPass for Doc {
55 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
56 check_attrs(cx, &self.valid_idents, &krate.attrs);
59 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
60 check_attrs(cx, &self.valid_idents, &item.attrs);
65 parser: pulldown_cmark::Parser<'a>,
69 fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
74 impl<'a> Iterator for Parser<'a> {
75 type Item = (usize, pulldown_cmark::Event<'a>);
77 fn next(&mut self) -> Option<Self::Item> {
78 let offset = self.parser.get_offset();
79 self.parser.next().map(|event| (offset, event))
83 /// Cleanup documentation decoration (`///` and such).
85 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
86 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
87 /// need to keep track of
88 /// the spans but this function is inspired from the later.
89 #[allow(cast_possible_truncation)]
90 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
91 // one-line comments lose their prefix
92 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
93 for prefix in ONELINERS {
94 if comment.starts_with(*prefix) {
95 let doc = &comment[prefix.len()..];
96 let mut doc = doc.to_owned();
101 (doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32))),
107 if comment.starts_with("/*") {
108 let doc = &comment[3..comment.len() - 2];
109 let mut sizes = vec![];
110 let mut contains_initial_stars = false;
111 for line in doc.lines() {
112 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
113 debug_assert_eq!(offset as u32 as usize, offset);
114 contains_initial_stars |= line.trim_left().starts_with('*');
115 // +1 for the newline
116 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
118 if !contains_initial_stars {
119 return (doc.to_string(), sizes);
121 // remove the initial '*'s if any
122 let mut no_stars = String::with_capacity(doc.len());
123 for line in doc.lines() {
124 let mut chars = line.chars();
125 while let Some(c) = chars.next() {
126 if c.is_whitespace() {
129 no_stars.push(if c == '*' { ' ' } else { c });
133 no_stars.push_str(chars.as_str());
136 return (no_stars, sizes);
139 panic!("not a doc-comment: {}", comment);
142 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
143 let mut doc = String::new();
144 let mut spans = vec![];
147 if attr.is_sugared_doc {
148 if let Some(ref current) = attr.value_str() {
149 let current = current.to_string();
150 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
151 spans.extend_from_slice(¤t_spans);
152 doc.push_str(¤t);
154 } else if attr.name() == "doc" {
155 // ignore mix of sugared and non-sugared doc
161 for &mut (ref mut offset, _) in &mut spans {
162 let offset_copy = *offset;
164 current += offset_copy;
168 let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
169 let parser = parser.coalesce(|x, y| {
170 use pulldown_cmark::Event::*;
176 (Text(x), Text(y)) => {
177 let mut x = x.into_owned();
179 Ok((x_offset, Text(x.into())))
181 (x, y) => Err(((x_offset, x), (y_offset, y))),
184 check_doc(cx, valid_idents, parser, &spans);
188 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
189 cx: &EarlyContext<'_>,
190 valid_idents: &[String],
192 spans: &[(usize, Span)],
194 use pulldown_cmark::Event::*;
195 use pulldown_cmark::Tag::*;
197 let mut in_code = false;
198 let mut in_link = None;
200 for (offset, event) in docs {
202 Start(CodeBlock(_)) | Start(Code) => in_code = true,
203 End(CodeBlock(_)) | End(Code) => in_code = false,
204 Start(Link(link, _)) => in_link = Some(link),
205 End(Link(_, _)) => in_link = None,
206 Start(_tag) | End(_tag) => (), // We don't care about other tags
207 Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
208 SoftBreak | HardBreak => (),
209 FootnoteReference(text) | Text(text) => {
210 if Some(&text) == in_link.as_ref() {
211 // Probably a link of the form `<http://example.com>`
212 // Which are represented as a link to "http://example.com" with
213 // text "http://example.com" by pulldown-cmark
218 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
223 let (begin, span) = spans[index];
225 // Adjust for the beginning of the current `Event`
226 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
228 check_text(cx, valid_idents, &text, span);
235 fn check_text(cx: &EarlyContext<'_>, valid_idents: &[String], text: &str, span: Span) {
236 for word in text.split_whitespace() {
237 // Trim punctuation as in `some comment (see foo::bar).`
239 // Or even as in `_foo bar_` which is emphasized.
240 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
242 if valid_idents.iter().any(|i| i == word) {
246 // Adjust for the current word
247 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
248 let span = Span::new(
249 span.lo() + BytePos::from_usize(offset),
250 span.lo() + BytePos::from_usize(offset + word.len()),
254 check_word(cx, word, span);
258 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
259 /// Checks if a string is camel-case, ie. contains at least two uppercase
260 /// letter (`Clippy` is
261 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
263 fn is_camel_case(s: &str) -> bool {
264 if s.starts_with(|c: char| c.is_digit(10)) {
268 let s = if s.ends_with('s') {
274 s.chars().all(char::is_alphanumeric) && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
275 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
278 fn has_underscore(s: &str) -> bool {
279 s != "_" && !s.contains("\\_") && s.contains('_')
282 if let Ok(url) = Url::parse(word) {
283 // try to get around the fact that `foo::bar` parses as a valid URL
284 if !url.cannot_be_a_base() {
289 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
296 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
301 &format!("you should put `{}` between ticks in the documentation", word),