1 use itertools::Itertools;
5 use syntax::codemap::{BytePos, Span};
10 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
11 /// outside ticks in documentation.
13 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
14 /// camel-case probably indicates some code which should be included between
15 /// ticks. `_` can also be used for empasis in markdown, this lint tries to
18 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
19 /// for is limited, and there are still false positives.
23 /// /// Do something with the foo_bar parameter. See also
24 /// that::other::module::foo.
25 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
26 /// fn doit(foo_bar) { .. }
31 "presence of `_`, `::` or camel-case outside backticks in documentation"
36 valid_idents: Vec<String>,
40 pub fn new(valid_idents: Vec<String>) -> Self {
42 valid_idents: valid_idents,
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 {
69 Self { parser: parser }
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(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();
100 (doc.len(), 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
115 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
117 if !contains_initial_stars {
118 return (doc.to_string(), sizes);
120 // remove the initial '*'s if any
121 let mut no_stars = String::with_capacity(doc.len());
122 for line in doc.lines() {
123 let mut chars = line.chars();
124 while let Some(c) = chars.next() {
125 if c.is_whitespace() {
128 no_stars.push(if c == '*' { ' ' } else { c });
132 no_stars.push_str(chars.as_str());
135 return (no_stars, sizes);
138 panic!("not a doc-comment: {}", comment);
141 pub fn check_attrs<'a>(cx: &EarlyContext, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
142 let mut doc = String::new();
143 let mut spans = vec![];
146 if attr.is_sugared_doc {
147 if let Some(ref current) = attr.value_str() {
148 let current = current.to_string();
149 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
150 spans.extend_from_slice(¤t_spans);
151 doc.push_str(¤t);
153 } else if let Some(name) = attr.name() {
154 // ignore mix of sugared and non-sugared doc
162 for &mut (ref mut offset, _) in &mut spans {
163 let offset_copy = *offset;
165 current += offset_copy;
169 let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
170 let parser = parser.coalesce(|x, y| {
171 use pulldown_cmark::Event::*;
177 (Text(x), Text(y)) => {
178 let mut x = x.into_owned();
180 Ok((x_offset, Text(x.into())))
182 (x, y) => Err(((x_offset, x), (y_offset, y))),
185 check_doc(cx, valid_idents, parser, &spans);
189 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
191 valid_idents: &[String],
193 spans: &[(usize, Span)],
195 use pulldown_cmark::Event::*;
196 use pulldown_cmark::Tag::*;
198 let mut in_code = false;
199 let mut in_link = None;
201 for (offset, event) in docs {
203 Start(CodeBlock(_)) | Start(Code) => in_code = true,
204 End(CodeBlock(_)) | End(Code) => in_code = false,
205 Start(Link(link, _)) => in_link = Some(link),
206 End(Link(_, _)) => in_link = None,
207 Start(_tag) | End(_tag) => (), // We don't care about other tags
208 Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
211 FootnoteReference(text) | Text(text) => {
212 if Some(&text) == in_link.as_ref() {
213 // Probably a link of the form `<http://example.com>`
214 // Which are represented as a link to "http://example.com" with
215 // text "http://example.com" by pulldown-cmark
220 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
225 let (begin, span) = spans[index];
227 // Adjust for the beginning of the current `Event`
228 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
230 check_text(cx, valid_idents, &text, span);
237 fn check_text(cx: &EarlyContext, valid_idents: &[String], text: &str, span: Span) {
238 for word in text.split_whitespace() {
239 // Trim punctuation as in `some comment (see foo::bar).`
241 // Or even as in `_foo bar_` which is emphasized.
242 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
244 if valid_idents.iter().any(|i| i == word) {
248 // Adjust for the current word
249 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
250 let span = Span::new(
251 span.lo() + BytePos::from_usize(offset),
252 span.lo() + BytePos::from_usize(offset + word.len()),
256 check_word(cx, word, span);
260 fn check_word(cx: &EarlyContext, word: &str, span: Span) {
261 /// Checks if a string is camel-case, ie. contains at least two uppercase
262 /// letter (`Clippy` is
263 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
265 fn is_camel_case(s: &str) -> bool {
266 if s.starts_with(|c: char| c.is_digit(10)) {
270 let s = if s.ends_with('s') {
276 s.chars().all(char::is_alphanumeric) && 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),