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