1 use crate::utils::span_lint;
2 use itertools::Itertools;
5 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc::{declare_tool_lint, impl_lint_pass};
7 use rustc_data_structures::fx::FxHashSet;
9 use syntax::ast::Attribute;
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: usize) {}
35 "presence of `_`, `::` or camel-case outside backticks in documentation"
38 declare_clippy_lint! {
39 /// **What it does:** Checks for the doc comments of publicly visible
40 /// unsafe functions and warns if there is no `# Safety` section.
42 /// **Why is this bad?** Unsafe functions should document their safety
43 /// preconditions, so that users can be sure they are using them safely.
45 /// **Known problems:** None.
49 ///# type Universe = ();
50 /// /// This function should really be documented
51 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
56 /// At least write a line about safety:
59 ///# type Universe = ();
62 /// /// This function should not be called before the horsemen are ready.
63 /// pub unsafe fn start_apocalypse(u: &mut Universe) {
67 pub MISSING_SAFETY_DOC,
69 "`pub unsafe fn` without `# Safety` docs"
72 declare_clippy_lint! {
73 /// **What it does:** Checks for `fn main() { .. }` in doctests
75 /// **Why is this bad?** The test can be shorter (and likely more readable)
76 /// if the `fn main()` is left implicit.
78 /// **Known problems:** None.
82 /// /// An example of a doctest with a `main()` function
88 /// /// // this needs not be in an `fn`
91 /// fn needless_main() {
95 pub NEEDLESS_DOCTEST_MAIN,
97 "presence of `fn main() {` in code examples"
100 #[allow(clippy::module_name_repetitions)]
102 pub struct DocMarkdown {
103 valid_idents: FxHashSet<String>,
108 pub fn new(valid_idents: FxHashSet<String>) -> Self {
111 in_trait_impl: false,
116 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, NEEDLESS_DOCTEST_MAIN]);
118 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown {
119 fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate) {
120 check_attrs(cx, &self.valid_idents, &krate.attrs);
123 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
124 if check_attrs(cx, &self.valid_idents, &item.attrs) {
129 hir::ItemKind::Fn(_, ref header, ..) => {
130 if cx.access_levels.is_exported(item.hir_id) && header.unsafety == hir::Unsafety::Unsafe {
135 "unsafe function's docs miss `# Safety` section",
139 hir::ItemKind::Impl(_, _, _, _, ref trait_ref, ..) => {
140 self.in_trait_impl = trait_ref.is_some();
146 fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
147 if let hir::ItemKind::Impl(..) = item.kind {
148 self.in_trait_impl = false;
152 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
153 if check_attrs(cx, &self.valid_idents, &item.attrs) {
157 if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
158 if cx.access_levels.is_exported(item.hir_id) && sig.header.unsafety == hir::Unsafety::Unsafe {
163 "unsafe function's docs miss `# Safety` section",
169 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
170 if check_attrs(cx, &self.valid_idents, &item.attrs) || self.in_trait_impl {
174 if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
175 if cx.access_levels.is_exported(item.hir_id) && sig.header.unsafety == hir::Unsafety::Unsafe {
180 "unsafe function's docs miss `# Safety` section",
187 /// Cleanup documentation decoration (`///` and such).
189 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
190 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
191 /// need to keep track of
192 /// the spans but this function is inspired from the later.
193 #[allow(clippy::cast_possible_truncation)]
195 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
196 // one-line comments lose their prefix
197 const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
198 for prefix in ONELINERS {
199 if comment.starts_with(*prefix) {
200 let doc = &comment[prefix.len()..];
201 let mut doc = doc.to_owned();
205 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
210 if comment.starts_with("/*") {
211 let doc = &comment[3..comment.len() - 2];
212 let mut sizes = vec![];
213 let mut contains_initial_stars = false;
214 for line in doc.lines() {
215 let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
216 debug_assert_eq!(offset as u32 as usize, offset);
217 contains_initial_stars |= line.trim_start().starts_with('*');
218 // +1 for the newline
219 sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
221 if !contains_initial_stars {
222 return (doc.to_string(), sizes);
224 // remove the initial '*'s if any
225 let mut no_stars = String::with_capacity(doc.len());
226 for line in doc.lines() {
227 let mut chars = line.chars();
228 while let Some(c) = chars.next() {
229 if c.is_whitespace() {
232 no_stars.push(if c == '*' { ' ' } else { c });
236 no_stars.push_str(chars.as_str());
239 return (no_stars, sizes);
242 panic!("not a doc-comment: {}", comment);
245 pub fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> bool {
246 let mut doc = String::new();
247 let mut spans = vec![];
250 if attr.is_sugared_doc {
251 if let Some(ref current) = attr.value_str() {
252 let current = current.to_string();
253 let (current, current_spans) = strip_doc_comment_decoration(¤t, attr.span);
254 spans.extend_from_slice(¤t_spans);
255 doc.push_str(¤t);
257 } else if attr.check_name(sym!(doc)) {
258 // ignore mix of sugared and non-sugared doc
259 return true; // don't trigger the safety check
264 for &mut (ref mut offset, _) in &mut spans {
265 let offset_copy = *offset;
267 current += offset_copy;
274 let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
275 // Iterate over all `Events` and combine consecutive events into one
276 let events = parser.coalesce(|previous, current| {
277 use pulldown_cmark::Event::*;
279 let previous_range = previous.1;
280 let current_range = current.1;
282 match (previous.0, current.0) {
283 (Text(previous), Text(current)) => {
284 let mut previous = previous.to_string();
285 previous.push_str(¤t);
286 Ok((Text(previous.into()), previous_range))
288 (previous, current) => Err(((previous, previous_range), (current, current_range))),
291 check_doc(cx, valid_idents, events, &spans)
294 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
295 cx: &LateContext<'_, '_>,
296 valid_idents: &FxHashSet<String>,
298 spans: &[(usize, Span)],
300 // true if a safety header was found
301 use pulldown_cmark::Event::*;
302 use pulldown_cmark::Tag::*;
304 let mut safety_header = false;
305 let mut in_code = false;
306 let mut in_link = None;
307 let mut in_heading = false;
309 for (event, range) in events {
311 Start(CodeBlock(_)) => in_code = true,
312 End(CodeBlock(_)) => in_code = false,
313 Start(Link(_, url, _)) => in_link = Some(url),
314 End(Link(..)) => in_link = None,
315 Start(Heading(_)) => in_heading = true,
316 End(Heading(_)) => in_heading = false,
317 Start(_tag) | End(_tag) => (), // We don't care about other tags
318 Html(_html) => (), // HTML is weird, just ignore it
319 SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
320 FootnoteReference(text) | Text(text) => {
321 if Some(&text) == in_link.as_ref() {
322 // Probably a link of the form `<http://example.com>`
323 // Which are represented as a link to "http://example.com" with
324 // text "http://example.com" by pulldown-cmark
327 safety_header |= in_heading && text.trim() == "Safety";
328 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
332 let (begin, span) = spans[index];
334 check_code(cx, &text, span);
336 // Adjust for the beginning of the current `Event`
337 let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
339 check_text(cx, valid_idents, &text, span);
347 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
348 if text.contains("fn main() {") {
349 span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
353 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
354 for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
355 // Trim punctuation as in `some comment (see foo::bar).`
357 // Or even as in `_foo bar_` which is emphasized.
358 let word = word.trim_matches(|c: char| !c.is_alphanumeric());
360 if valid_idents.contains(word) {
364 // Adjust for the current word
365 let offset = word.as_ptr() as usize - text.as_ptr() as usize;
366 let span = Span::new(
367 span.lo() + BytePos::from_usize(offset),
368 span.lo() + BytePos::from_usize(offset + word.len()),
372 check_word(cx, word, span);
376 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
377 /// Checks if a string is camel-case, i.e., contains at least two uppercase
378 /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
379 /// Plurals are also excluded (`IDs` is ok).
380 fn is_camel_case(s: &str) -> bool {
381 if s.starts_with(|c: char| c.is_digit(10)) {
385 let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
387 s.chars().all(char::is_alphanumeric)
388 && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
389 && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
392 fn has_underscore(s: &str) -> bool {
393 s != "_" && !s.contains("\\_") && s.contains('_')
396 fn has_hyphen(s: &str) -> bool {
397 s != "-" && s.contains('-')
400 if let Ok(url) = Url::parse(word) {
401 // try to get around the fact that `foo::bar` parses as a valid URL
402 if !url.cannot_be_a_base() {
407 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
414 // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
415 if has_underscore(word) && has_hyphen(word) {
419 if has_underscore(word) || word.contains("::") || is_camel_case(word) {
424 &format!("you should put `{}` between ticks in the documentation", word),