1 use crate::utils::span_lint;
2 use itertools::Itertools;
4 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_data_structures::fx::FxHashSet;
8 use syntax::source_map::{BytePos, Span};
12 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
13 /// outside ticks in documentation.
15 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
16 /// camel-case probably indicates some code which should be included between
17 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
20 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
21 /// for is limited, and there are still false positives.
25 /// /// Do something with the foo_bar parameter. See also
26 /// /// that::other::module::foo.
27 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
28 /// fn doit(foo_bar) { .. }
30 declare_clippy_lint! {
33 "presence of `_`, `::` or camel-case outside backticks in documentation"
38 valid_idents: FxHashSet<String>,
42 pub fn new(valid_idents: FxHashSet<String>) -> Self {
47 impl LintPass for Doc {
48 fn get_lints(&self) -> LintArray {
49 lint_array![DOC_MARKDOWN]
53 impl EarlyLintPass for Doc {
54 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
55 check_attrs(cx, &self.valid_idents, &krate.attrs);
58 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
59 check_attrs(cx, &self.valid_idents, &item.attrs);
64 parser: pulldown_cmark::Parser<'a>,
68 fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
73 impl<'a> Iterator for Parser<'a> {
74 type Item = (usize, pulldown_cmark::Event<'a>);
76 fn next(&mut self) -> Option<Self::Item> {
77 let offset = self.parser.get_offset();
78 self.parser.next().map(|event| (offset, event))
82 /// Cleanup documentation decoration (`///` and such).
84 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
85 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
86 /// need to keep track of
87 /// the spans but this function is inspired from the later.
88 #[allow(clippy::cast_possible_truncation)]
89 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
90 // one-line comments lose their prefix
91 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
92 for prefix in ONELINERS {
93 if comment.starts_with(*prefix) {
94 let doc = &comment[prefix.len()..];
95 let mut doc = doc.to_owned();
99 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
104 if comment.starts_with("/*") {
105 let doc = &comment[3..comment.len() - 2];
106 let mut sizes = vec![];
107 let mut contains_initial_stars = false;
108 for line in doc.lines() {
109 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
110 debug_assert_eq!(offset as u32 as usize, offset);
111 contains_initial_stars |= line.trim_start().starts_with('*');
112 // +1 for the newline
113 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
115 if !contains_initial_stars {
116 return (doc.to_string(), sizes);
118 // remove the initial '*'s if any
119 let mut no_stars = String::with_capacity(doc.len());
120 for line in doc.lines() {
121 let mut chars = line.chars();
122 while let Some(c) = chars.next() {
123 if c.is_whitespace() {
126 no_stars.push(if c == '*' { ' ' } else { c });
130 no_stars.push_str(chars.as_str());
133 return (no_stars, sizes);
136 panic!("not a doc-comment: {}", comment);
139 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [ast::Attribute]) {
140 let mut doc = String::new();
141 let mut spans = vec![];
144 if attr.is_sugared_doc {
145 if let Some(ref current) = attr.value_str() {
146 let current = current.to_string();
147 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
148 spans.extend_from_slice(¤t_spans);
149 doc.push_str(¤t);
151 } else if attr.name() == "doc" {
152 // ignore mix of sugared and non-sugared doc
158 for &mut (ref mut offset, _) in &mut spans {
159 let offset_copy = *offset;
161 current += offset_copy;
165 let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
166 let parser = parser.coalesce(|x, y| {
167 use pulldown_cmark::Event::*;
173 (Text(x), Text(y)) => {
174 let mut x = x.into_owned();
176 Ok((x_offset, Text(x.into())))
178 (x, y) => Err(((x_offset, x), (y_offset, y))),
181 check_doc(cx, valid_idents, parser, &spans);
185 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
186 cx: &EarlyContext<'_>,
187 valid_idents: &FxHashSet<String>,
189 spans: &[(usize, Span)],
191 use pulldown_cmark::Event::*;
192 use pulldown_cmark::Tag::*;
194 let mut in_code = false;
195 let mut in_link = None;
197 for (offset, event) in docs {
199 Start(CodeBlock(_)) | Start(Code) => in_code = true,
200 End(CodeBlock(_)) | End(Code) => in_code = false,
201 Start(Link(link, _)) => in_link = Some(link),
202 End(Link(_, _)) => in_link = None,
203 Start(_tag) | End(_tag) => (), // We don't care about other tags
204 Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
205 SoftBreak | HardBreak => (),
206 FootnoteReference(text) | Text(text) => {
207 if Some(&text) == in_link.as_ref() {
208 // Probably a link of the form `<http://example.com>`
209 // Which are represented as a link to "http://example.com" with
210 // text "http://example.com" by pulldown-cmark
215 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
220 let (begin, span) = spans[index];
222 // Adjust for the beginning of the current `Event`
223 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
225 check_text(cx, valid_idents, &text, span);
232 fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
233 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
234 // Trim punctuation as in `some comment (see foo::bar).`
236 // Or even as in `_foo bar_` which is emphasized.
237 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
239 if valid_idents.contains(word) {
243 // Adjust for the current word
244 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
245 let span = Span::new(
246 span.lo() + BytePos::from_usize(offset),
247 span.lo() + BytePos::from_usize(offset + word.len()),
251 check_word(cx, word, span);
255 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
256 /// Checks if a string is camel-case, ie. contains at least two uppercase
257 /// letter (`Clippy` is
258 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
260 fn is_camel_case(s: &str) -> bool {
261 if s.starts_with(|c: char| c.is_digit(10)) {
265 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
267 s.chars().all(char::is_alphanumeric)
268 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
269 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
272 fn has_underscore(s: &str) -> bool {
273 s != "_" && !s.contains("\\_") && s.contains('_')
276 fn has_hyphen(s: &str) -> bool {
277 s != "-" && s.contains('-')
280 if let Ok(url) = Url::parse(word) {
281 // try to get around the fact that `foo::bar` parses as a valid URL
282 if !url.cannot_be_a_base() {
287 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
294 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
295 if has_underscore(word) && has_hyphen(word) {
299 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
304 &format!("you should put `{}` between ticks in the documentation", word),