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();
99 span.with_lo(span.lo() + BytePos(prefix.len() as u32)),
106 if comment.starts_with("/*") {
107 let doc = &comment[3..comment.len() - 2];
108 let mut sizes = vec![];
109 let mut contains_initial_stars = false;
110 for line in doc.lines() {
111 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
112 debug_assert_eq!(offset as u32 as usize, offset);
113 contains_initial_stars |= line.trim_left().starts_with('*');
114 // +1 for the newline
117 span.with_lo(span.lo() + BytePos(offset as u32)),
120 if !contains_initial_stars {
121 return (doc.to_string(), sizes);
123 // remove the initial '*'s if any
124 let mut no_stars = String::with_capacity(doc.len());
125 for line in doc.lines() {
126 let mut chars = line.chars();
127 while let Some(c) = chars.next() {
128 if c.is_whitespace() {
131 no_stars.push(if c == '*' { ' ' } else { c });
135 no_stars.push_str(chars.as_str());
138 return (no_stars, sizes);
141 panic!("not a doc-comment: {}", comment);
144 pub fn check_attrs<'a>(cx: &EarlyContext, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
145 let mut doc = String::new();
146 let mut spans = vec![];
149 if attr.is_sugared_doc {
150 if let Some(ref current) = attr.value_str() {
151 let current = current.to_string();
152 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
153 spans.extend_from_slice(¤t_spans);
154 doc.push_str(¤t);
156 } else if let Some(name) = attr.name() {
157 // ignore mix of sugared and non-sugared doc
165 for &mut (ref mut offset, _) in &mut spans {
166 let offset_copy = *offset;
168 current += offset_copy;
172 let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
173 let parser = parser.coalesce(|x, y| {
174 use pulldown_cmark::Event::*;
180 (Text(x), Text(y)) => {
181 let mut x = x.into_owned();
183 Ok((x_offset, Text(x.into())))
185 (x, y) => Err(((x_offset, x), (y_offset, y))),
188 check_doc(cx, valid_idents, parser, &spans);
192 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
194 valid_idents: &[String],
196 spans: &[(usize, Span)],
198 use pulldown_cmark::Event::*;
199 use pulldown_cmark::Tag::*;
201 let mut in_code = false;
203 for (offset, event) in docs {
205 Start(CodeBlock(_)) |
206 Start(Code) => in_code = true,
208 End(Code) => in_code = false,
209 Start(_tag) | End(_tag) => (), // We don't care about other tags
211 InlineHtml(_html) => (), // HTML is weird, just ignore it
214 FootnoteReference(text) |
217 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
222 let (begin, span) = spans[index];
224 // Adjust for the begining of the current `Event`
225 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
227 check_text(cx, valid_idents, &text, span);
234 fn check_text(cx: &EarlyContext, valid_idents: &[String], text: &str, span: Span) {
235 for word in text.split_whitespace() {
236 // Trim punctuation as in `some comment (see foo::bar).`
238 // Or even as in `_foo bar_` which is emphasized.
239 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
241 if valid_idents.iter().any(|i| i == word) {
245 // Adjust for the current word
246 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
247 let span = Span::new(
248 span.lo() + BytePos::from_usize(offset),
249 span.lo() + BytePos::from_usize(offset + word.len()),
253 check_word(cx, word, span);
257 fn check_word(cx: &EarlyContext, word: &str, span: Span) {
258 /// Checks if a string is camel-case, ie. contains at least two uppercase
259 /// letter (`Clippy` is
260 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
262 fn is_camel_case(s: &str) -> bool {
263 if s.starts_with(|c: char| c.is_digit(10)) {
267 let s = if s.ends_with('s') {
273 s.chars().all(char::is_alphanumeric) && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1 &&
274 s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
277 fn has_underscore(s: &str) -> bool {
278 s != "_" && !s.contains("\\_") && s.contains('_')
281 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
286 &format!("you should put `{}` between ticks in the documentation", word),