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 declare_clippy_lint! {
38 /// **What it does:** Checks for the doc comments of publicly visible
39 /// unsafe functions and warns if there is no `# Safety` section.
41 /// **Why is this bad?** Unsafe functions should document their safety
42 /// preconditions, so that users can be sure they are using them safely.
44 /// **Known problems:** None.
48 ///# type Universe = ();
49 /// /// This function should really be documented
50 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
55 /// At least write a line about safety:
58 ///# type Universe = ();
61 /// /// This function should not be called before the horsemen are ready.
62 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
66 pub MISSING_SAFETY_DOC,
68 "`pub unsafe fn` without `# Safety` docs"
71 #[allow(clippy::module_name_repetitions)]
73 pub struct DocMarkdown {
74 valid_idents: FxHashSet<String>,
78 pub fn new(valid_idents: FxHashSet<String>) -> Self {
83 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC]);
85 impl EarlyLintPass for DocMarkdown {
86 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
87 check_attrs(cx, &self.valid_idents, &krate.attrs);
90 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
91 if check_attrs(cx, &self.valid_idents, &item.attrs) {
95 if let ast::ItemKind::Fn(_, ref header, ..) = item.kind {
96 if item.vis.node.is_pub() && header.unsafety == ast::Unsafety::Unsafe {
101 "unsafe function's docs miss `# Safety` section",
108 /// Cleanup documentation decoration (`///` and such).
110 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
111 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
112 /// need to keep track of
113 /// the spans but this function is inspired from the later.
114 #[allow(clippy::cast_possible_truncation)]
115 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
116 // one-line comments lose their prefix
117 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
118 for prefix in ONELINERS {
119 if comment.starts_with(*prefix) {
120 let doc = &comment[prefix.len()..];
121 let mut doc = doc.to_owned();
125 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
130 if comment.starts_with("/*") {
131 let doc = &comment[3..comment.len() - 2];
132 let mut sizes = vec![];
133 let mut contains_initial_stars = false;
134 for line in doc.lines() {
135 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
136 debug_assert_eq!(offset as u32 as usize, offset);
137 contains_initial_stars |= line.trim_start().starts_with('*');
138 // +1 for the newline
139 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
141 if !contains_initial_stars {
142 return (doc.to_string(), sizes);
144 // remove the initial '*'s if any
145 let mut no_stars = String::with_capacity(doc.len());
146 for line in doc.lines() {
147 let mut chars = line.chars();
148 while let Some(c) = chars.next() {
149 if c.is_whitespace() {
152 no_stars.push(if c == '*' { ' ' } else { c });
156 no_stars.push_str(chars.as_str());
159 return (no_stars, sizes);
162 panic!("not a doc-comment: {}", comment);
165 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [ast::Attribute]) -> bool {
166 let mut doc = String::new();
167 let mut spans = vec![];
170 if attr.is_sugared_doc {
171 if let Some(ref current) = attr.value_str() {
172 let current = current.to_string();
173 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
174 spans.extend_from_slice(¤t_spans);
175 doc.push_str(¤t);
177 } else if attr.check_name(sym!(doc)) {
178 // ignore mix of sugared and non-sugared doc
179 return true; // don't trigger the safety check
184 for &mut (ref mut offset, _) in &mut spans {
185 let offset_copy = *offset;
187 current += offset_copy;
194 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
195 // Iterate over all `Events` and combine consecutive events into one
196 let events = parser.coalesce(|previous, current| {
197 use pulldown_cmark::Event::*;
199 let previous_range = previous.1;
200 let current_range = current.1;
202 match (previous.0, current.0) {
203 (Text(previous), Text(current)) => {
204 let mut previous = previous.to_string();
205 previous.push_str(¤t);
206 Ok((Text(previous.into()), previous_range))
208 (previous, current) => Err(((previous, previous_range), (current, current_range))),
211 check_doc(cx, valid_idents, events, &spans)
214 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
215 cx: &EarlyContext<'_>,
216 valid_idents: &FxHashSet<String>,
218 spans: &[(usize, Span)],
220 // true if a safety header was found
221 use pulldown_cmark::Event::*;
222 use pulldown_cmark::Tag::*;
224 let mut safety_header = false;
225 let mut in_code = false;
226 let mut in_link = None;
227 let mut in_heading = false;
229 for (event, range) in events {
231 Start(CodeBlock(_)) => in_code = true,
232 End(CodeBlock(_)) => in_code = false,
233 Start(Link(_, url, _)) => in_link = Some(url),
234 End(Link(..)) => in_link = None,
235 Start(Heading(_)) => in_heading = true,
236 End(Heading(_)) => in_heading = false,
237 Start(_tag) | End(_tag) => (), // We don't care about other tags
238 Html(_html) => (), // HTML is weird, just ignore it
239 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
240 FootnoteReference(text) | Text(text) => {
241 if Some(&text) == in_link.as_ref() {
242 // Probably a link of the form `<http://example.com>`
243 // Which are represented as a link to "http://example.com" with
244 // text "http://example.com" by pulldown-cmark
247 safety_header |= in_heading && text.trim() == "Safety";
249 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
254 let (begin, span) = spans[index];
256 // Adjust for the beginning of the current `Event`
257 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
259 check_text(cx, valid_idents, &text, span);
267 fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
268 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
269 // Trim punctuation as in `some comment (see foo::bar).`
271 // Or even as in `_foo bar_` which is emphasized.
272 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
274 if valid_idents.contains(word) {
278 // Adjust for the current word
279 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
280 let span = Span::new(
281 span.lo() + BytePos::from_usize(offset),
282 span.lo() + BytePos::from_usize(offset + word.len()),
286 check_word(cx, word, span);
290 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
291 /// Checks if a string is camel-case, i.e., contains at least two uppercase
292 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
293 /// Plurals are also excluded (`IDs` is ok).
294 fn is_camel_case(s: &str) -> bool {
295 if s.starts_with(|c: char| c.is_digit(10)) {
299 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
301 s.chars().all(char::is_alphanumeric)
302 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
303 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
306 fn has_underscore(s: &str) -> bool {
307 s != "_" && !s.contains("\\_") && s.contains('_')
310 fn has_hyphen(s: &str) -> bool {
311 s != "-" && s.contains('-')
314 if let Ok(url) = Url::parse(word) {
315 // try to get around the fact that `foo::bar` parses as a valid URL
316 if !url.cannot_be_a_base() {
321 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
328 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
329 if has_underscore(word) && has_hyphen(word) {
333 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
338 &format!("you should put `{}` between ticks in the documentation", word),