1 use crate::utils::span_lint;
3 use itertools::Itertools;
5 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, impl_lint_pass};
7 use rustc_data_structures::fx::FxHashSet;
10 use syntax::source_map::{BytePos, Span};
14 declare_clippy_lint! {
15 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
16 /// outside ticks in documentation.
18 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
19 /// camel-case probably indicates some code which should be included between
20 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
23 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
24 /// for is limited, and there are still false positives.
28 /// /// Do something with the foo_bar parameter. See also
29 /// /// that::other::module::foo.
30 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
31 /// fn doit(foo_bar) { .. }
35 "presence of `_`, `::` or camel-case outside backticks in documentation"
38 #[allow(clippy::module_name_repetitions)]
40 pub struct DocMarkdown {
41 valid_idents: FxHashSet<String>,
45 pub fn new(valid_idents: FxHashSet<String>) -> Self {
50 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN]);
52 impl EarlyLintPass for DocMarkdown {
53 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
54 check_attrs(cx, &self.valid_idents, &krate.attrs);
57 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
58 check_attrs(cx, &self.valid_idents, &item.attrs);
62 /// Cleanup documentation decoration (`///` and such).
64 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
65 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
66 /// need to keep track of
67 /// the spans but this function is inspired from the later.
68 #[allow(clippy::cast_possible_truncation)]
69 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
70 // one-line comments lose their prefix
71 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
72 for prefix in ONELINERS {
73 if comment.starts_with(*prefix) {
74 let doc = &comment[prefix.len()..];
75 let mut doc = doc.to_owned();
79 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
84 if comment.starts_with("/*") {
85 let doc = &comment[3..comment.len() - 2];
86 let mut sizes = vec![];
87 let mut contains_initial_stars = false;
88 for line in doc.lines() {
89 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
90 debug_assert_eq!(offset as u32 as usize, offset);
91 contains_initial_stars |= line.trim_start().starts_with('*');
93 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
95 if !contains_initial_stars {
96 return (doc.to_string(), sizes);
98 // remove the initial '*'s if any
99 let mut no_stars = String::with_capacity(doc.len());
100 for line in doc.lines() {
101 let mut chars = line.chars();
102 while let Some(c) = chars.next() {
103 if c.is_whitespace() {
106 no_stars.push(if c == '*' { ' ' } else { c });
110 no_stars.push_str(chars.as_str());
113 return (no_stars, sizes);
116 panic!("not a doc-comment: {}", comment);
119 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [ast::Attribute]) {
120 let mut doc = String::new();
121 let mut spans = vec![];
124 if attr.is_sugared_doc {
125 if let Some(ref current) = attr.value_str() {
126 let current = current.to_string();
127 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
128 spans.extend_from_slice(¤t_spans);
129 doc.push_str(¤t);
131 } else if attr.check_name(*sym::doc) {
132 // ignore mix of sugared and non-sugared doc
138 for &mut (ref mut offset, _) in &mut spans {
139 let offset_copy = *offset;
141 current += offset_copy;
145 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
146 // Iterate over all `Events` and combine consecutive events into one
147 let events = parser.coalesce(|previous, current| {
148 use pulldown_cmark::Event::*;
150 let previous_range = previous.1;
151 let current_range = current.1;
153 match (previous.0, current.0) {
154 (Text(previous), Text(current)) => {
155 let mut previous = previous.to_string();
156 previous.push_str(¤t);
157 Ok((Text(previous.into()), previous_range))
159 (previous, current) => Err(((previous, previous_range), (current, current_range))),
162 check_doc(cx, valid_idents, events, &spans);
166 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
167 cx: &EarlyContext<'_>,
168 valid_idents: &FxHashSet<String>,
170 spans: &[(usize, Span)],
172 use pulldown_cmark::Event::*;
173 use pulldown_cmark::Tag::*;
175 let mut in_code = false;
176 let mut in_link = None;
178 for (event, range) in events {
180 Start(CodeBlock(_)) => in_code = true,
181 End(CodeBlock(_)) => in_code = false,
182 Start(Link(_, url, _)) => in_link = Some(url),
183 End(Link(..)) => in_link = None,
184 Start(_tag) | End(_tag) => (), // We don't care about other tags
185 Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
186 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) => (),
187 FootnoteReference(text) | Text(text) => {
188 if Some(&text) == in_link.as_ref() {
189 // Probably a link of the form `<http://example.com>`
190 // Which are represented as a link to "http://example.com" with
191 // text "http://example.com" by pulldown-cmark
196 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
201 let (begin, span) = spans[index];
203 // Adjust for the beginning of the current `Event`
204 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
206 check_text(cx, valid_idents, &text, span);
213 fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
214 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
215 // Trim punctuation as in `some comment (see foo::bar).`
217 // Or even as in `_foo bar_` which is emphasized.
218 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
220 if valid_idents.contains(word) {
224 // Adjust for the current word
225 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
226 let span = Span::new(
227 span.lo() + BytePos::from_usize(offset),
228 span.lo() + BytePos::from_usize(offset + word.len()),
232 check_word(cx, word, span);
236 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
237 /// Checks if a string is camel-case, i.e., contains at least two uppercase
238 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
239 /// Plurals are also excluded (`IDs` is ok).
240 fn is_camel_case(s: &str) -> bool {
241 if s.starts_with(|c: char| c.is_digit(10)) {
245 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
247 s.chars().all(char::is_alphanumeric)
248 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
249 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
252 fn has_underscore(s: &str) -> bool {
253 s != "_" && !s.contains("\\_") && s.contains('_')
256 fn has_hyphen(s: &str) -> bool {
257 s != "-" && s.contains('-')
260 if let Ok(url) = Url::parse(word) {
261 // try to get around the fact that `foo::bar` parses as a valid URL
262 if !url.cannot_be_a_base() {
267 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
274 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
275 if has_underscore(word) && has_hyphen(word) {
279 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
284 &format!("you should put `{}` between ticks in the documentation", word),