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