1 use itertools::Itertools;
5 use syntax::codemap::{Span, BytePos};
9 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
10 /// outside ticks in documentation.
12 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
13 /// camel-case probably indicates some code which should be included between
14 /// ticks. `_` can also be used for empasis in markdown, this lint tries to
17 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
18 /// for is limited, and there are still false positives.
22 /// /// Do something with the foo_bar parameter. See also
23 /// that::other::module::foo.
24 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
25 /// fn doit(foo_bar) { .. }
30 "presence of `_`, `::` or camel-case outside backticks in documentation"
35 valid_idents: Vec<String>,
39 pub fn new(valid_idents: Vec<String>) -> Self {
40 Self { valid_idents: valid_idents }
44 impl LintPass for Doc {
45 fn get_lints(&self) -> LintArray {
46 lint_array![DOC_MARKDOWN]
50 impl EarlyLintPass for Doc {
51 fn check_crate(&mut self, cx: &EarlyContext, krate: &ast::Crate) {
52 check_attrs(cx, &self.valid_idents, &krate.attrs);
55 fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
56 check_attrs(cx, &self.valid_idents, &item.attrs);
61 parser: pulldown_cmark::Parser<'a>,
65 fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
66 Self { parser: parser }
70 impl<'a> Iterator for Parser<'a> {
71 type Item = (usize, pulldown_cmark::Event<'a>);
73 fn next(&mut self) -> Option<Self::Item> {
74 let offset = self.parser.get_offset();
75 self.parser.next().map(|event| (offset, event))
79 /// Cleanup documentation decoration (`///` and such).
81 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
82 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
83 /// need to keep track of
84 /// the spans but this function is inspired from the later.
85 #[allow(cast_possible_truncation)]
86 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
87 // one-line comments lose their prefix
88 const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
89 for prefix in ONELINERS {
90 if comment.starts_with(*prefix) {
91 let doc = &comment[prefix.len()..];
92 let mut doc = doc.to_owned();
97 (doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32))),
103 if comment.starts_with("/*") {
104 let doc = &comment[3..comment.len() - 2];
105 let mut sizes = vec![];
106 let mut contains_initial_stars = false;
107 for line in doc.lines() {
108 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
109 debug_assert_eq!(offset as u32 as usize, offset);
110 contains_initial_stars |= line.trim_left().starts_with('*');
111 // +1 for the newline
112 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
114 if !contains_initial_stars {
115 return (doc.to_string(), sizes);
117 // remove the initial '*'s if any
118 let mut no_stars = String::with_capacity(doc.len());
119 for line in doc.lines() {
120 let mut chars = line.chars();
121 while let Some(c) = chars.next() {
122 if c.is_whitespace() {
125 no_stars.push(if c == '*' { ' ' } else { c });
129 no_stars.push_str(chars.as_str());
132 return (no_stars, sizes);
135 panic!("not a doc-comment: {}", comment);
138 pub fn check_attrs<'a>(cx: &EarlyContext, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
139 let mut doc = String::new();
140 let mut spans = vec![];
143 if attr.is_sugared_doc {
144 if let Some(ref current) = attr.value_str() {
145 let current = current.to_string();
146 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
147 spans.extend_from_slice(¤t_spans);
148 doc.push_str(¤t);
150 } else if let Some(name) = attr.name() {
151 // ignore mix of sugared and non-sugared doc
159 for &mut (ref mut offset, _) in &mut spans {
160 let offset_copy = *offset;
162 current += offset_copy;
166 let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
167 let parser = parser.coalesce(|x, y| {
168 use pulldown_cmark::Event::*;
174 (Text(x), Text(y)) => {
175 let mut x = x.into_owned();
177 Ok((x_offset, Text(x.into())))
179 (x, y) => Err(((x_offset, x), (y_offset, y))),
182 check_doc(cx, valid_idents, parser, &spans);
186 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
188 valid_idents: &[String],
190 spans: &[(usize, Span)],
192 use pulldown_cmark::Event::*;
193 use pulldown_cmark::Tag::*;
195 let mut in_code = false;
197 for (offset, event) in docs {
199 Start(CodeBlock(_)) |
200 Start(Code) => in_code = true,
202 End(Code) => in_code = false,
203 Start(_tag) | End(_tag) => (), // We don't care about other tags
205 InlineHtml(_html) => (), // HTML is weird, just ignore it
208 FootnoteReference(text) |
211 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
216 let (begin, span) = spans[index];
218 // Adjust for the begining of the current `Event`
219 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
221 check_text(cx, valid_idents, &text, span);
228 fn check_text(cx: &EarlyContext, valid_idents: &[String], text: &str, span: Span) {
229 for word in text.split_whitespace() {
230 // Trim punctuation as in `some comment (see foo::bar).`
232 // Or even as in `_foo bar_` which is emphasized.
233 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
235 if valid_idents.iter().any(|i| i == word) {
239 // Adjust for the current word
240 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
241 let span = Span::new(
242 span.lo() + BytePos::from_usize(offset),
243 span.lo() + BytePos::from_usize(offset + word.len()),
247 check_word(cx, word, span);
251 fn check_word(cx: &EarlyContext, word: &str, span: Span) {
252 /// Checks if a string is camel-case, ie. contains at least two uppercase
253 /// letter (`Clippy` is
254 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
256 fn is_camel_case(s: &str) -> bool {
257 if s.starts_with(|c: char| c.is_digit(10)) {
261 let s = if s.ends_with('s') {
267 s.chars().all(char::is_alphanumeric) && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1 &&
268 s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
271 fn has_underscore(s: &str) -> bool {
272 s != "_" && !s.contains("\\_") && s.contains('_')
275 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
280 &format!("you should put `{}` between ticks in the documentation", word),