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.
10 use crate::rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
11 use crate::rustc::{declare_tool_lint, lint_array};
12 use crate::syntax::ast;
13 use crate::syntax::source_map::{BytePos, Span};
14 use crate::syntax_pos::Pos;
15 use crate::utils::span_lint;
16 use itertools::Itertools;
20 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
21 /// outside ticks in documentation.
23 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
24 /// camel-case probably indicates some code which should be included between
25 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
28 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
29 /// for is limited, and there are still false positives.
33 /// /// Do something with the foo_bar parameter. See also
34 /// /// that::other::module::foo.
35 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
36 /// fn doit(foo_bar) { .. }
38 declare_clippy_lint! {
41 "presence of `_`, `::` or camel-case outside backticks in documentation"
46 valid_idents: Vec<String>,
50 pub fn new(valid_idents: Vec<String>) -> Self {
55 impl LintPass for Doc {
56 fn get_lints(&self) -> LintArray {
57 lint_array![DOC_MARKDOWN]
61 impl EarlyLintPass for Doc {
62 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
63 check_attrs(cx, &self.valid_idents, &krate.attrs);
66 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
67 check_attrs(cx, &self.valid_idents, &item.attrs);
72 parser: pulldown_cmark::Parser<'a>,
76 fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
81 impl<'a> Iterator for Parser<'a> {
82 type Item = (usize, pulldown_cmark::Event<'a>);
84 fn next(&mut self) -> Option<Self::Item> {
85 let offset = self.parser.get_offset();
86 self.parser.next().map(|event| (offset, event))
90 /// Cleanup documentation decoration (`///` and such).
92 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
93 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
94 /// need to keep track of
95 /// the spans but this function is inspired from the later.
96 #[allow(clippy::cast_possible_truncation)]
97 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
98 // one-line comments lose their prefix
99 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
100 for prefix in ONELINERS {
101 if comment.starts_with(*prefix) {
102 let doc = &comment[prefix.len()..];
103 let mut doc = doc.to_owned();
107 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
112 if comment.starts_with("/*") {
113 let doc = &comment[3..comment.len() - 2];
114 let mut sizes = vec![];
115 let mut contains_initial_stars = false;
116 for line in doc.lines() {
117 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
118 debug_assert_eq!(offset as u32 as usize, offset);
119 contains_initial_stars |= line.trim_left().starts_with('*');
120 // +1 for the newline
121 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
123 if !contains_initial_stars {
124 return (doc.to_string(), sizes);
126 // remove the initial '*'s if any
127 let mut no_stars = String::with_capacity(doc.len());
128 for line in doc.lines() {
129 let mut chars = line.chars();
130 while let Some(c) = chars.next() {
131 if c.is_whitespace() {
134 no_stars.push(if c == '*' { ' ' } else { c });
138 no_stars.push_str(chars.as_str());
141 return (no_stars, sizes);
144 panic!("not a doc-comment: {}", comment);
147 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
148 let mut doc = String::new();
149 let mut spans = vec![];
152 if attr.is_sugared_doc {
153 if let Some(ref current) = attr.value_str() {
154 let current = current.to_string();
155 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
156 spans.extend_from_slice(¤t_spans);
157 doc.push_str(¤t);
159 } else if attr.name() == "doc" {
160 // ignore mix of sugared and non-sugared doc
166 for &mut (ref mut offset, _) in &mut spans {
167 let offset_copy = *offset;
169 current += offset_copy;
173 let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
174 let parser = parser.coalesce(|x, y| {
175 use pulldown_cmark::Event::*;
181 (Text(x), Text(y)) => {
182 let mut x = x.into_owned();
184 Ok((x_offset, Text(x.into())))
186 (x, y) => Err(((x_offset, x), (y_offset, y))),
189 check_doc(cx, valid_idents, parser, &spans);
193 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
194 cx: &EarlyContext<'_>,
195 valid_idents: &[String],
197 spans: &[(usize, Span)],
199 use pulldown_cmark::Event::*;
200 use pulldown_cmark::Tag::*;
202 let mut in_code = false;
203 let mut in_link = None;
205 for (offset, event) in docs {
207 Start(CodeBlock(_)) | Start(Code) => in_code = true,
208 End(CodeBlock(_)) | End(Code) => in_code = false,
209 Start(Link(link, _)) => in_link = Some(link),
210 End(Link(_, _)) => in_link = None,
211 Start(_tag) | End(_tag) => (), // We don't care about other tags
212 Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
213 SoftBreak | HardBreak => (),
214 FootnoteReference(text) | Text(text) => {
215 if Some(&text) == in_link.as_ref() {
216 // Probably a link of the form `<http://example.com>`
217 // Which are represented as a link to "http://example.com" with
218 // text "http://example.com" by pulldown-cmark
223 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
228 let (begin, span) = spans[index];
230 // Adjust for the beginning of the current `Event`
231 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
233 check_text(cx, valid_idents, &text, span);
240 fn check_text(cx: &EarlyContext<'_>, valid_idents: &[String], text: &str, span: Span) {
241 for word in text.split_whitespace() {
242 // Trim punctuation as in `some comment (see foo::bar).`
244 // Or even as in `_foo bar_` which is emphasized.
245 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
247 if valid_idents.iter().any(|i| i == word) {
251 // Adjust for the current word
252 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
253 let span = Span::new(
254 span.lo() + BytePos::from_usize(offset),
255 span.lo() + BytePos::from_usize(offset + word.len()),
259 check_word(cx, word, span);
263 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
264 /// Checks if a string is camel-case, ie. contains at least two uppercase
265 /// letter (`Clippy` is
266 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
268 fn is_camel_case(s: &str) -> bool {
269 if s.starts_with(|c: char| c.is_digit(10)) {
273 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
275 s.chars().all(char::is_alphanumeric)
276 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
277 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
280 fn has_underscore(s: &str) -> bool {
281 s != "_" && !s.contains("\\_") && s.contains('_')
284 if let Ok(url) = Url::parse(word) {
285 // try to get around the fact that `foo::bar` parses as a valid URL
286 if !url.cannot_be_a_base() {
291 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
298 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
303 &format!("you should put `{}` between ticks in the documentation", word),