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 declare_clippy_lint! {
13 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
14 /// outside ticks in documentation.
16 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
17 /// camel-case probably indicates some code which should be included between
18 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
21 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
22 /// for is limited, and there are still false positives.
26 /// /// Do something with the foo_bar parameter. See also
27 /// /// that::other::module::foo.
28 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
29 /// fn doit(foo_bar) { .. }
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]
52 fn name(&self) -> &'static str {
57 impl EarlyLintPass for Doc {
58 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
59 check_attrs(cx, &self.valid_idents, &krate.attrs);
62 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
63 check_attrs(cx, &self.valid_idents, &item.attrs);
68 parser: pulldown_cmark::Parser<'a>,
72 fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
77 impl<'a> Iterator for Parser<'a> {
78 type Item = (usize, pulldown_cmark::Event<'a>);
80 fn next(&mut self) -> Option<Self::Item> {
81 let offset = self.parser.get_offset();
82 self.parser.next().map(|event| (offset, event))
86 /// Cleanup documentation decoration (`///` and such).
88 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
89 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
90 /// need to keep track of
91 /// the spans but this function is inspired from the later.
92 #[allow(clippy::cast_possible_truncation)]
93 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
94 // one-line comments lose their prefix
95 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
96 for prefix in ONELINERS {
97 if comment.starts_with(*prefix) {
98 let doc = &comment[prefix.len()..];
99 let mut doc = doc.to_owned();
103 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
108 if comment.starts_with("/*") {
109 let doc = &comment[3..comment.len() - 2];
110 let mut sizes = vec![];
111 let mut contains_initial_stars = false;
112 for line in doc.lines() {
113 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
114 debug_assert_eq!(offset as u32 as usize, offset);
115 contains_initial_stars |= line.trim_start().starts_with('*');
116 // +1 for the newline
117 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
119 if !contains_initial_stars {
120 return (doc.to_string(), sizes);
122 // remove the initial '*'s if any
123 let mut no_stars = String::with_capacity(doc.len());
124 for line in doc.lines() {
125 let mut chars = line.chars();
126 while let Some(c) = chars.next() {
127 if c.is_whitespace() {
130 no_stars.push(if c == '*' { ' ' } else { c });
134 no_stars.push_str(chars.as_str());
137 return (no_stars, sizes);
140 panic!("not a doc-comment: {}", comment);
143 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [ast::Attribute]) {
144 let mut doc = String::new();
145 let mut spans = vec![];
148 if attr.is_sugared_doc {
149 if let Some(ref current) = attr.value_str() {
150 let current = current.to_string();
151 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
152 spans.extend_from_slice(¤t_spans);
153 doc.push_str(¤t);
155 } else if attr.name() == "doc" {
156 // 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>)>>(
190 cx: &EarlyContext<'_>,
191 valid_idents: &FxHashSet<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
209 SoftBreak | HardBreak => (),
210 FootnoteReference(text) | Text(text) => {
211 if Some(&text) == in_link.as_ref() {
212 // Probably a link of the form `<http://example.com>`
213 // Which are represented as a link to "http://example.com" with
214 // text "http://example.com" by pulldown-cmark
219 let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
224 let (begin, span) = spans[index];
226 // Adjust for the beginning of the current `Event`
227 let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
229 check_text(cx, valid_idents, &text, span);
236 fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
237 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
238 // Trim punctuation as in `some comment (see foo::bar).`
240 // Or even as in `_foo bar_` which is emphasized.
241 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
243 if valid_idents.contains(word) {
247 // Adjust for the current word
248 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
249 let span = Span::new(
250 span.lo() + BytePos::from_usize(offset),
251 span.lo() + BytePos::from_usize(offset + word.len()),
255 check_word(cx, word, span);
259 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
260 /// Checks if a string is camel-case, ie. contains at least two uppercase
261 /// letter (`Clippy` is
262 /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
264 fn is_camel_case(s: &str) -> bool {
265 if s.starts_with(|c: char| c.is_digit(10)) {
269 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
271 s.chars().all(char::is_alphanumeric)
272 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
273 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
276 fn has_underscore(s: &str) -> bool {
277 s != "_" && !s.contains("\\_") && s.contains('_')
280 fn has_hyphen(s: &str) -> bool {
281 s != "-" && 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 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
299 if has_underscore(word) && has_hyphen(word) {
303 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
308 &format!("you should put `{}` between ticks in the documentation", word),