]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/doc.rs
Rollup merge of #87582 - tmiasko:symbol-printer, r=michaelwoerister
[rust.git] / src / tools / clippy / clippy_lints / src / doc.rs
1 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_note};
2 use clippy_utils::source::first_line_of_span;
3 use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
4 use clippy_utils::{is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty};
5 use if_chain::if_chain;
6 use itertools::Itertools;
7 use rustc_ast::ast::{Async, AttrKind, Attribute, FnKind, FnRetTy, ItemKind};
8 use rustc_ast::token::CommentKind;
9 use rustc_data_structures::fx::FxHashSet;
10 use rustc_data_structures::sync::Lrc;
11 use rustc_errors::emitter::EmitterWriter;
12 use rustc_errors::Handler;
13 use rustc_hir as hir;
14 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
15 use rustc_hir::{AnonConst, Expr, ExprKind, QPath};
16 use rustc_lint::{LateContext, LateLintPass};
17 use rustc_middle::hir::map::Map;
18 use rustc_middle::lint::in_external_macro;
19 use rustc_middle::ty;
20 use rustc_parse::maybe_new_parser_from_source_str;
21 use rustc_parse::parser::ForceCollect;
22 use rustc_session::parse::ParseSess;
23 use rustc_session::{declare_tool_lint, impl_lint_pass};
24 use rustc_span::def_id::LocalDefId;
25 use rustc_span::edition::Edition;
26 use rustc_span::source_map::{BytePos, FilePathMapping, MultiSpan, SourceMap, Span};
27 use rustc_span::{sym, FileName, Pos};
28 use std::io;
29 use std::ops::Range;
30 use std::thread;
31 use url::Url;
32
33 declare_clippy_lint! {
34     /// ### What it does
35     /// Checks for the presence of `_`, `::` or camel-case words
36     /// outside ticks in documentation.
37     ///
38     /// ### Why is this bad?
39     /// *Rustdoc* supports markdown formatting, `_`, `::` and
40     /// camel-case probably indicates some code which should be included between
41     /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
42     /// consider that.
43     ///
44     /// ### Known problems
45     /// Lots of bad docs won’t be fixed, what the lint checks
46     /// for is limited, and there are still false positives. HTML elements and their
47     /// content are not linted.
48     ///
49     /// In addition, when writing documentation comments, including `[]` brackets
50     /// inside a link text would trip the parser. Therfore, documenting link with
51     /// `[`SmallVec<[T; INLINE_CAPACITY]>`]` and then [`SmallVec<[T; INLINE_CAPACITY]>`]: SmallVec
52     /// would fail.
53     ///
54     /// ### Examples
55     /// ```rust
56     /// /// Do something with the foo_bar parameter. See also
57     /// /// that::other::module::foo.
58     /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
59     /// fn doit(foo_bar: usize) {}
60     /// ```
61     ///
62     /// ```rust
63     /// // Link text with `[]` brackets should be written as following:
64     /// /// Consume the array and return the inner
65     /// /// [`SmallVec<[T; INLINE_CAPACITY]>`][SmallVec].
66     /// /// [SmallVec]: SmallVec
67     /// fn main() {}
68     /// ```
69     pub DOC_MARKDOWN,
70     pedantic,
71     "presence of `_`, `::` or camel-case outside backticks in documentation"
72 }
73
74 declare_clippy_lint! {
75     /// ### What it does
76     /// Checks for the doc comments of publicly visible
77     /// unsafe functions and warns if there is no `# Safety` section.
78     ///
79     /// ### Why is this bad?
80     /// Unsafe functions should document their safety
81     /// preconditions, so that users can be sure they are using them safely.
82     ///
83     /// ### Examples
84     /// ```rust
85     ///# type Universe = ();
86     /// /// This function should really be documented
87     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
88     ///     unimplemented!();
89     /// }
90     /// ```
91     ///
92     /// At least write a line about safety:
93     ///
94     /// ```rust
95     ///# type Universe = ();
96     /// /// # Safety
97     /// ///
98     /// /// This function should not be called before the horsemen are ready.
99     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
100     ///     unimplemented!();
101     /// }
102     /// ```
103     pub MISSING_SAFETY_DOC,
104     style,
105     "`pub unsafe fn` without `# Safety` docs"
106 }
107
108 declare_clippy_lint! {
109     /// ### What it does
110     /// Checks the doc comments of publicly visible functions that
111     /// return a `Result` type and warns if there is no `# Errors` section.
112     ///
113     /// ### Why is this bad?
114     /// Documenting the type of errors that can be returned from a
115     /// function can help callers write code to handle the errors appropriately.
116     ///
117     /// ### Examples
118     /// Since the following function returns a `Result` it has an `# Errors` section in
119     /// its doc comment:
120     ///
121     /// ```rust
122     ///# use std::io;
123     /// /// # Errors
124     /// ///
125     /// /// Will return `Err` if `filename` does not exist or the user does not have
126     /// /// permission to read it.
127     /// pub fn read(filename: String) -> io::Result<String> {
128     ///     unimplemented!();
129     /// }
130     /// ```
131     pub MISSING_ERRORS_DOC,
132     pedantic,
133     "`pub fn` returns `Result` without `# Errors` in doc comment"
134 }
135
136 declare_clippy_lint! {
137     /// ### What it does
138     /// Checks the doc comments of publicly visible functions that
139     /// may panic and warns if there is no `# Panics` section.
140     ///
141     /// ### Why is this bad?
142     /// Documenting the scenarios in which panicking occurs
143     /// can help callers who do not want to panic to avoid those situations.
144     ///
145     /// ### Examples
146     /// Since the following function may panic it has a `# Panics` section in
147     /// its doc comment:
148     ///
149     /// ```rust
150     /// /// # Panics
151     /// ///
152     /// /// Will panic if y is 0
153     /// pub fn divide_by(x: i32, y: i32) -> i32 {
154     ///     if y == 0 {
155     ///         panic!("Cannot divide by 0")
156     ///     } else {
157     ///         x / y
158     ///     }
159     /// }
160     /// ```
161     pub MISSING_PANICS_DOC,
162     pedantic,
163     "`pub fn` may panic without `# Panics` in doc comment"
164 }
165
166 declare_clippy_lint! {
167     /// ### What it does
168     /// Checks for `fn main() { .. }` in doctests
169     ///
170     /// ### Why is this bad?
171     /// The test can be shorter (and likely more readable)
172     /// if the `fn main()` is left implicit.
173     ///
174     /// ### Examples
175     /// ``````rust
176     /// /// An example of a doctest with a `main()` function
177     /// ///
178     /// /// # Examples
179     /// ///
180     /// /// ```
181     /// /// fn main() {
182     /// ///     // this needs not be in an `fn`
183     /// /// }
184     /// /// ```
185     /// fn needless_main() {
186     ///     unimplemented!();
187     /// }
188     /// ``````
189     pub NEEDLESS_DOCTEST_MAIN,
190     style,
191     "presence of `fn main() {` in code examples"
192 }
193
194 #[allow(clippy::module_name_repetitions)]
195 #[derive(Clone)]
196 pub struct DocMarkdown {
197     valid_idents: FxHashSet<String>,
198     in_trait_impl: bool,
199 }
200
201 impl DocMarkdown {
202     pub fn new(valid_idents: FxHashSet<String>) -> Self {
203         Self {
204             valid_idents,
205             in_trait_impl: false,
206         }
207     }
208 }
209
210 impl_lint_pass!(DocMarkdown =>
211     [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, MISSING_PANICS_DOC, NEEDLESS_DOCTEST_MAIN]
212 );
213
214 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
215     fn check_crate(&mut self, cx: &LateContext<'tcx>, _: &'tcx hir::Crate<'_>) {
216         let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID);
217         check_attrs(cx, &self.valid_idents, attrs);
218     }
219
220     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
221         let attrs = cx.tcx.hir().attrs(item.hir_id());
222         let headers = check_attrs(cx, &self.valid_idents, attrs);
223         match item.kind {
224             hir::ItemKind::Fn(ref sig, _, body_id) => {
225                 if !(is_entrypoint_fn(cx, item.def_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) {
226                     let body = cx.tcx.hir().body(body_id);
227                     let mut fpu = FindPanicUnwrap {
228                         cx,
229                         typeck_results: cx.tcx.typeck(item.def_id),
230                         panic_span: None,
231                     };
232                     fpu.visit_expr(&body.value);
233                     lint_for_missing_headers(
234                         cx,
235                         item.def_id,
236                         item.span,
237                         sig,
238                         headers,
239                         Some(body_id),
240                         fpu.panic_span,
241                     );
242                 }
243             },
244             hir::ItemKind::Impl(ref impl_) => {
245                 self.in_trait_impl = impl_.of_trait.is_some();
246             },
247             _ => {},
248         }
249     }
250
251     fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
252         if let hir::ItemKind::Impl { .. } = item.kind {
253             self.in_trait_impl = false;
254         }
255     }
256
257     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
258         let attrs = cx.tcx.hir().attrs(item.hir_id());
259         let headers = check_attrs(cx, &self.valid_idents, attrs);
260         if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
261             if !in_external_macro(cx.tcx.sess, item.span) {
262                 lint_for_missing_headers(cx, item.def_id, item.span, sig, headers, None, None);
263             }
264         }
265     }
266
267     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
268         let attrs = cx.tcx.hir().attrs(item.hir_id());
269         let headers = check_attrs(cx, &self.valid_idents, attrs);
270         if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
271             return;
272         }
273         if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
274             let body = cx.tcx.hir().body(body_id);
275             let mut fpu = FindPanicUnwrap {
276                 cx,
277                 typeck_results: cx.tcx.typeck(item.def_id),
278                 panic_span: None,
279             };
280             fpu.visit_expr(&body.value);
281             lint_for_missing_headers(
282                 cx,
283                 item.def_id,
284                 item.span,
285                 sig,
286                 headers,
287                 Some(body_id),
288                 fpu.panic_span,
289             );
290         }
291     }
292 }
293
294 fn lint_for_missing_headers<'tcx>(
295     cx: &LateContext<'tcx>,
296     def_id: LocalDefId,
297     span: impl Into<MultiSpan> + Copy,
298     sig: &hir::FnSig<'_>,
299     headers: DocHeaders,
300     body_id: Option<hir::BodyId>,
301     panic_span: Option<Span>,
302 ) {
303     if !cx.access_levels.is_exported(def_id) {
304         return; // Private functions do not require doc comments
305     }
306     if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
307         span_lint(
308             cx,
309             MISSING_SAFETY_DOC,
310             span,
311             "unsafe function's docs miss `# Safety` section",
312         );
313     }
314     if !headers.panics && panic_span.is_some() {
315         span_lint_and_note(
316             cx,
317             MISSING_PANICS_DOC,
318             span,
319             "docs for function which may panic missing `# Panics` section",
320             panic_span,
321             "first possible panic found here",
322         );
323     }
324     if !headers.errors {
325         let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
326         if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
327             span_lint(
328                 cx,
329                 MISSING_ERRORS_DOC,
330                 span,
331                 "docs for function returning `Result` missing `# Errors` section",
332             );
333         } else {
334             if_chain! {
335                 if let Some(body_id) = body_id;
336                 if let Some(future) = cx.tcx.lang_items().future_trait();
337                 let typeck = cx.tcx.typeck_body(body_id);
338                 let body = cx.tcx.hir().body(body_id);
339                 let ret_ty = typeck.expr_ty(&body.value);
340                 if implements_trait(cx, ret_ty, future, &[]);
341                 if let ty::Opaque(_, subs) = ret_ty.kind();
342                 if let Some(gen) = subs.types().next();
343                 if let ty::Generator(_, subs, _) = gen.kind();
344                 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
345                 then {
346                     span_lint(
347                         cx,
348                         MISSING_ERRORS_DOC,
349                         span,
350                         "docs for function returning `Result` missing `# Errors` section",
351                     );
352                 }
353             }
354         }
355     }
356 }
357
358 /// Cleanup documentation decoration.
359 ///
360 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
361 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
362 /// need to keep track of
363 /// the spans but this function is inspired from the later.
364 #[allow(clippy::cast_possible_truncation)]
365 #[must_use]
366 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
367     // one-line comments lose their prefix
368     if comment_kind == CommentKind::Line {
369         let mut doc = doc.to_owned();
370         doc.push('\n');
371         let len = doc.len();
372         // +3 skips the opening delimiter
373         return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
374     }
375
376     let mut sizes = vec![];
377     let mut contains_initial_stars = false;
378     for line in doc.lines() {
379         let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
380         debug_assert_eq!(offset as u32 as usize, offset);
381         contains_initial_stars |= line.trim_start().starts_with('*');
382         // +1 adds the newline, +3 skips the opening delimiter
383         sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
384     }
385     if !contains_initial_stars {
386         return (doc.to_string(), sizes);
387     }
388     // remove the initial '*'s if any
389     let mut no_stars = String::with_capacity(doc.len());
390     for line in doc.lines() {
391         let mut chars = line.chars();
392         for c in &mut chars {
393             if c.is_whitespace() {
394                 no_stars.push(c);
395             } else {
396                 no_stars.push(if c == '*' { ' ' } else { c });
397                 break;
398             }
399         }
400         no_stars.push_str(chars.as_str());
401         no_stars.push('\n');
402     }
403
404     (no_stars, sizes)
405 }
406
407 #[derive(Copy, Clone)]
408 struct DocHeaders {
409     safety: bool,
410     errors: bool,
411     panics: bool,
412 }
413
414 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
415     let mut doc = String::new();
416     let mut spans = vec![];
417
418     for attr in attrs {
419         if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
420             let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
421             spans.extend_from_slice(&current_spans);
422             doc.push_str(&comment);
423         } else if attr.has_name(sym::doc) {
424             // ignore mix of sugared and non-sugared doc
425             // don't trigger the safety or errors check
426             return DocHeaders {
427                 safety: true,
428                 errors: true,
429                 panics: true,
430             };
431         }
432     }
433
434     let mut current = 0;
435     for &mut (ref mut offset, _) in &mut spans {
436         let offset_copy = *offset;
437         *offset = current;
438         current += offset_copy;
439     }
440
441     if doc.is_empty() {
442         return DocHeaders {
443             safety: false,
444             errors: false,
445             panics: false,
446         };
447     }
448
449     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
450     // Iterate over all `Events` and combine consecutive events into one
451     let events = parser.coalesce(|previous, current| {
452         use pulldown_cmark::Event::Text;
453
454         let previous_range = previous.1;
455         let current_range = current.1;
456
457         match (previous.0, current.0) {
458             (Text(previous), Text(current)) => {
459                 let mut previous = previous.to_string();
460                 previous.push_str(&current);
461                 Ok((Text(previous.into()), previous_range))
462             },
463             (previous, current) => Err(((previous, previous_range), (current, current_range))),
464         }
465     });
466     check_doc(cx, valid_idents, events, &spans)
467 }
468
469 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
470
471 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
472     cx: &LateContext<'_>,
473     valid_idents: &FxHashSet<String>,
474     events: Events,
475     spans: &[(usize, Span)],
476 ) -> DocHeaders {
477     // true if a safety header was found
478     use pulldown_cmark::Event::{
479         Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
480     };
481     use pulldown_cmark::Tag::{CodeBlock, Heading, Item, Link, Paragraph};
482     use pulldown_cmark::{CodeBlockKind, CowStr};
483
484     let mut headers = DocHeaders {
485         safety: false,
486         errors: false,
487         panics: false,
488     };
489     let mut in_code = false;
490     let mut in_link = None;
491     let mut in_heading = false;
492     let mut is_rust = false;
493     let mut edition = None;
494     let mut ticks_unbalanced = false;
495     let mut text_to_check: Vec<(CowStr<'_>, Span)> = Vec::new();
496     let mut paragraph_span = spans.get(0).expect("function isn't called if doc comment is empty").1;
497     for (event, range) in events {
498         match event {
499             Start(CodeBlock(ref kind)) => {
500                 in_code = true;
501                 if let CodeBlockKind::Fenced(lang) = kind {
502                     for item in lang.split(',') {
503                         if item == "ignore" {
504                             is_rust = false;
505                             break;
506                         }
507                         if let Some(stripped) = item.strip_prefix("edition") {
508                             is_rust = true;
509                             edition = stripped.parse::<Edition>().ok();
510                         } else if item.is_empty() || RUST_CODE.contains(&item) {
511                             is_rust = true;
512                         }
513                     }
514                 }
515             },
516             End(CodeBlock(_)) => {
517                 in_code = false;
518                 is_rust = false;
519             },
520             Start(Link(_, url, _)) => in_link = Some(url),
521             End(Link(..)) => in_link = None,
522             Start(Heading(_) | Paragraph | Item) => {
523                 if let Start(Heading(_)) = event {
524                     in_heading = true;
525                 }
526                 ticks_unbalanced = false;
527                 let (_, span) = get_current_span(spans, range.start);
528                 paragraph_span = first_line_of_span(cx, span);
529             },
530             End(Heading(_) | Paragraph | Item) => {
531                 if let End(Heading(_)) = event {
532                     in_heading = false;
533                 }
534                 if ticks_unbalanced {
535                     span_lint_and_help(
536                         cx,
537                         DOC_MARKDOWN,
538                         paragraph_span,
539                         "backticks are unbalanced",
540                         None,
541                         "a backtick may be missing a pair",
542                     );
543                 } else {
544                     for (text, span) in text_to_check {
545                         check_text(cx, valid_idents, &text, span);
546                     }
547                 }
548                 text_to_check = Vec::new();
549             },
550             Start(_tag) | End(_tag) => (), // We don't care about other tags
551             Html(_html) => (),             // HTML is weird, just ignore it
552             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
553             FootnoteReference(text) | Text(text) => {
554                 let (begin, span) = get_current_span(spans, range.start);
555                 paragraph_span = paragraph_span.with_hi(span.hi());
556                 ticks_unbalanced |= text.contains('`') && !in_code;
557                 if Some(&text) == in_link.as_ref() || ticks_unbalanced {
558                     // Probably a link of the form `<http://example.com>`
559                     // Which are represented as a link to "http://example.com" with
560                     // text "http://example.com" by pulldown-cmark
561                     continue;
562                 }
563                 headers.safety |= in_heading && text.trim() == "Safety";
564                 headers.errors |= in_heading && text.trim() == "Errors";
565                 headers.panics |= in_heading && text.trim() == "Panics";
566                 if in_code {
567                     if is_rust {
568                         let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
569                         check_code(cx, &text, edition, span);
570                     }
571                 } else {
572                     // Adjust for the beginning of the current `Event`
573                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
574                     text_to_check.push((text, span));
575                 }
576             },
577         }
578     }
579     headers
580 }
581
582 fn get_current_span(spans: &[(usize, Span)], idx: usize) -> (usize, Span) {
583     let index = match spans.binary_search_by(|c| c.0.cmp(&idx)) {
584         Ok(o) => o,
585         Err(e) => e - 1,
586     };
587     spans[index]
588 }
589
590 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
591     fn has_needless_main(code: String, edition: Edition) -> bool {
592         rustc_driver::catch_fatal_errors(|| {
593             rustc_span::create_session_globals_then(edition, || {
594                 let filename = FileName::anon_source_code(&code);
595
596                 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
597                 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
598                 let handler = Handler::with_emitter(false, None, box emitter);
599                 let sess = ParseSess::with_span_handler(handler, sm);
600
601                 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) {
602                     Ok(p) => p,
603                     Err(errs) => {
604                         for mut err in errs {
605                             err.cancel();
606                         }
607                         return false;
608                     },
609                 };
610
611                 let mut relevant_main_found = false;
612                 loop {
613                     match parser.parse_item(ForceCollect::No) {
614                         Ok(Some(item)) => match &item.kind {
615                             // Tests with one of these items are ignored
616                             ItemKind::Static(..)
617                             | ItemKind::Const(..)
618                             | ItemKind::ExternCrate(..)
619                             | ItemKind::ForeignMod(..) => return false,
620                             // We found a main function ...
621                             ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => {
622                                 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
623                                 let returns_nothing = match &sig.decl.output {
624                                     FnRetTy::Default(..) => true,
625                                     FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
626                                     FnRetTy::Ty(_) => false,
627                                 };
628
629                                 if returns_nothing && !is_async && !block.stmts.is_empty() {
630                                     // This main function should be linted, but only if there are no other functions
631                                     relevant_main_found = true;
632                                 } else {
633                                     // This main function should not be linted, we're done
634                                     return false;
635                                 }
636                             },
637                             // Another function was found; this case is ignored too
638                             ItemKind::Fn(..) => return false,
639                             _ => {},
640                         },
641                         Ok(None) => break,
642                         Err(mut e) => {
643                             e.cancel();
644                             return false;
645                         },
646                     }
647                 }
648
649                 relevant_main_found
650             })
651         })
652         .ok()
653         .unwrap_or_default()
654     }
655
656     // Because of the global session, we need to create a new session in a different thread with
657     // the edition we need.
658     let text = text.to_owned();
659     if thread::spawn(move || has_needless_main(text, edition))
660         .join()
661         .expect("thread::spawn failed")
662     {
663         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
664     }
665 }
666
667 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
668     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
669         // Trim punctuation as in `some comment (see foo::bar).`
670         //                                                   ^^
671         // Or even as in `_foo bar_` which is emphasized.
672         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
673
674         if valid_idents.contains(word) {
675             continue;
676         }
677
678         // Adjust for the current word
679         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
680         let span = Span::new(
681             span.lo() + BytePos::from_usize(offset),
682             span.lo() + BytePos::from_usize(offset + word.len()),
683             span.ctxt(),
684         );
685
686         check_word(cx, word, span);
687     }
688 }
689
690 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
691     /// Checks if a string is camel-case, i.e., contains at least two uppercase
692     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
693     /// Plurals are also excluded (`IDs` is ok).
694     fn is_camel_case(s: &str) -> bool {
695         if s.starts_with(|c: char| c.is_digit(10)) {
696             return false;
697         }
698
699         let s = s.strip_suffix('s').unwrap_or(s);
700
701         s.chars().all(char::is_alphanumeric)
702             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
703             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
704     }
705
706     fn has_underscore(s: &str) -> bool {
707         s != "_" && !s.contains("\\_") && s.contains('_')
708     }
709
710     fn has_hyphen(s: &str) -> bool {
711         s != "-" && s.contains('-')
712     }
713
714     if let Ok(url) = Url::parse(word) {
715         // try to get around the fact that `foo::bar` parses as a valid URL
716         if !url.cannot_be_a_base() {
717             span_lint(
718                 cx,
719                 DOC_MARKDOWN,
720                 span,
721                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
722             );
723
724             return;
725         }
726     }
727
728     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
729     if has_underscore(word) && has_hyphen(word) {
730         return;
731     }
732
733     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
734         span_lint(
735             cx,
736             DOC_MARKDOWN,
737             span,
738             &format!("you should put `{}` between ticks in the documentation", word),
739         );
740     }
741 }
742
743 struct FindPanicUnwrap<'a, 'tcx> {
744     cx: &'a LateContext<'tcx>,
745     panic_span: Option<Span>,
746     typeck_results: &'tcx ty::TypeckResults<'tcx>,
747 }
748
749 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
750     type Map = Map<'tcx>;
751
752     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
753         if self.panic_span.is_some() {
754             return;
755         }
756
757         // check for `begin_panic`
758         if_chain! {
759             if let ExprKind::Call(func_expr, _) = expr.kind;
760             if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
761             if let Some(path_def_id) = path.res.opt_def_id();
762             if match_panic_def_id(self.cx, path_def_id);
763             if is_expn_of(expr.span, "unreachable").is_none();
764             if !is_expn_of_debug_assertions(expr.span);
765             then {
766                 self.panic_span = Some(expr.span);
767             }
768         }
769
770         // check for `assert_eq` or `assert_ne`
771         if is_expn_of(expr.span, "assert_eq").is_some() || is_expn_of(expr.span, "assert_ne").is_some() {
772             self.panic_span = Some(expr.span);
773         }
774
775         // check for `unwrap`
776         if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
777             let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
778             if is_type_diagnostic_item(self.cx, reciever_ty, sym::option_type)
779                 || is_type_diagnostic_item(self.cx, reciever_ty, sym::result_type)
780             {
781                 self.panic_span = Some(expr.span);
782             }
783         }
784
785         // and check sub-expressions
786         intravisit::walk_expr(self, expr);
787     }
788
789     // Panics in const blocks will cause compilation to fail.
790     fn visit_anon_const(&mut self, _: &'tcx AnonConst) {}
791
792     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
793         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
794     }
795 }
796
797 fn is_expn_of_debug_assertions(span: Span) -> bool {
798     const MACRO_NAMES: &[&str] = &["debug_assert", "debug_assert_eq", "debug_assert_ne"];
799     MACRO_NAMES.iter().any(|name| is_expn_of(span, name).is_some())
800 }