]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Auto merge of #9963 - ehuss:highfive-triagebot, r=xFrednet
[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, 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 declare_clippy_lint! {
202     /// ### What it does
203     /// Detects the syntax `['foo']` in documentation comments (notice quotes instead of backticks)
204     /// outside of code blocks
205     /// ### Why is this bad?
206     /// It is likely a typo when defining an intra-doc link
207     ///
208     /// ### Example
209     /// ```rust
210     /// /// See also: ['foo']
211     /// fn bar() {}
212     /// ```
213     /// Use instead:
214     /// ```rust
215     /// /// See also: [`foo`]
216     /// fn bar() {}
217     /// ```
218     #[clippy::version = "1.63.0"]
219     pub DOC_LINK_WITH_QUOTES,
220     pedantic,
221     "possible typo for an intra-doc link"
222 }
223
224 declare_clippy_lint! {
225     /// ### What it does
226     /// Checks for the doc comments of publicly visible
227     /// safe functions and traits and warns if there is a `# Safety` section.
228     ///
229     /// ### Why is this bad?
230     /// Safe functions and traits are safe to implement and therefore do not
231     /// need to describe safety preconditions that users are required to uphold.
232     ///
233     /// ### Examples
234     /// ```rust
235     ///# type Universe = ();
236     /// /// # Safety
237     /// ///
238     /// /// This function should not be called before the horsemen are ready.
239     /// pub fn start_apocalypse_but_safely(u: &mut Universe) {
240     ///     unimplemented!();
241     /// }
242     /// ```
243     ///
244     /// The function is safe, so there shouldn't be any preconditions
245     /// that have to be explained for safety reasons.
246     ///
247     /// ```rust
248     ///# type Universe = ();
249     /// /// This function should really be documented
250     /// pub fn start_apocalypse(u: &mut Universe) {
251     ///     unimplemented!();
252     /// }
253     /// ```
254     #[clippy::version = "1.66.0"]
255     pub UNNECESSARY_SAFETY_DOC,
256     style,
257     "`pub fn` or `pub trait` with `# Safety` docs"
258 }
259
260 #[expect(clippy::module_name_repetitions)]
261 #[derive(Clone)]
262 pub struct DocMarkdown {
263     valid_idents: FxHashSet<String>,
264     in_trait_impl: bool,
265 }
266
267 impl DocMarkdown {
268     pub fn new(valid_idents: FxHashSet<String>) -> Self {
269         Self {
270             valid_idents,
271             in_trait_impl: false,
272         }
273     }
274 }
275
276 impl_lint_pass!(DocMarkdown => [
277     DOC_LINK_WITH_QUOTES,
278     DOC_MARKDOWN,
279     MISSING_SAFETY_DOC,
280     MISSING_ERRORS_DOC,
281     MISSING_PANICS_DOC,
282     NEEDLESS_DOCTEST_MAIN,
283     UNNECESSARY_SAFETY_DOC,
284 ]);
285
286 impl<'tcx> LateLintPass<'tcx> for DocMarkdown {
287     fn check_crate(&mut self, cx: &LateContext<'tcx>) {
288         let attrs = cx.tcx.hir().attrs(hir::CRATE_HIR_ID);
289         check_attrs(cx, &self.valid_idents, attrs);
290     }
291
292     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
293         let attrs = cx.tcx.hir().attrs(item.hir_id());
294         let Some(headers) = check_attrs(cx, &self.valid_idents, attrs) else { return };
295         match item.kind {
296             hir::ItemKind::Fn(ref sig, _, body_id) => {
297                 if !(is_entrypoint_fn(cx, item.owner_id.to_def_id()) || in_external_macro(cx.tcx.sess, item.span)) {
298                     let body = cx.tcx.hir().body(body_id);
299                     let mut fpu = FindPanicUnwrap {
300                         cx,
301                         typeck_results: cx.tcx.typeck(item.owner_id.def_id),
302                         panic_span: None,
303                     };
304                     fpu.visit_expr(body.value);
305                     lint_for_missing_headers(cx, item.owner_id.def_id, sig, headers, Some(body_id), fpu.panic_span);
306                 }
307             },
308             hir::ItemKind::Impl(impl_) => {
309                 self.in_trait_impl = impl_.of_trait.is_some();
310             },
311             hir::ItemKind::Trait(_, unsafety, ..) => match (headers.safety, unsafety) {
312                 (false, hir::Unsafety::Unsafe) => span_lint(
313                     cx,
314                     MISSING_SAFETY_DOC,
315                     cx.tcx.def_span(item.owner_id),
316                     "docs for unsafe trait missing `# Safety` section",
317                 ),
318                 (true, hir::Unsafety::Normal) => span_lint(
319                     cx,
320                     UNNECESSARY_SAFETY_DOC,
321                     cx.tcx.def_span(item.owner_id),
322                     "docs for safe trait have unnecessary `# Safety` section",
323                 ),
324                 _ => (),
325             },
326             _ => (),
327         }
328     }
329
330     fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
331         if let hir::ItemKind::Impl { .. } = item.kind {
332             self.in_trait_impl = false;
333         }
334     }
335
336     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
337         let attrs = cx.tcx.hir().attrs(item.hir_id());
338         let Some(headers) = check_attrs(cx, &self.valid_idents, attrs) else { return };
339         if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
340             if !in_external_macro(cx.tcx.sess, item.span) {
341                 lint_for_missing_headers(cx, item.owner_id.def_id, sig, headers, None, None);
342             }
343         }
344     }
345
346     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
347         let attrs = cx.tcx.hir().attrs(item.hir_id());
348         let Some(headers) = check_attrs(cx, &self.valid_idents, attrs) else { return };
349         if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
350             return;
351         }
352         if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
353             let body = cx.tcx.hir().body(body_id);
354             let mut fpu = FindPanicUnwrap {
355                 cx,
356                 typeck_results: cx.tcx.typeck(item.owner_id.def_id),
357                 panic_span: None,
358             };
359             fpu.visit_expr(body.value);
360             lint_for_missing_headers(cx, item.owner_id.def_id, sig, headers, Some(body_id), fpu.panic_span);
361         }
362     }
363 }
364
365 fn lint_for_missing_headers(
366     cx: &LateContext<'_>,
367     def_id: LocalDefId,
368     sig: &hir::FnSig<'_>,
369     headers: DocHeaders,
370     body_id: Option<hir::BodyId>,
371     panic_span: Option<Span>,
372 ) {
373     if !cx.effective_visibilities.is_exported(def_id) {
374         return; // Private functions do not require doc comments
375     }
376
377     // do not lint if any parent has `#[doc(hidden)]` attribute (#7347)
378     if cx
379         .tcx
380         .hir()
381         .parent_iter(cx.tcx.hir().local_def_id_to_hir_id(def_id))
382         .any(|(id, _node)| is_doc_hidden(cx.tcx.hir().attrs(id)))
383     {
384         return;
385     }
386
387     let span = cx.tcx.def_span(def_id);
388     match (headers.safety, sig.header.unsafety) {
389         (false, hir::Unsafety::Unsafe) => span_lint(
390             cx,
391             MISSING_SAFETY_DOC,
392             span,
393             "unsafe function's docs miss `# Safety` section",
394         ),
395         (true, hir::Unsafety::Normal) => span_lint(
396             cx,
397             UNNECESSARY_SAFETY_DOC,
398             span,
399             "safe function's docs have unnecessary `# Safety` section",
400         ),
401         _ => (),
402     }
403     if !headers.panics && panic_span.is_some() {
404         span_lint_and_note(
405             cx,
406             MISSING_PANICS_DOC,
407             span,
408             "docs for function which may panic missing `# Panics` section",
409             panic_span,
410             "first possible panic found here",
411         );
412     }
413     if !headers.errors {
414         let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
415         if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::Result) {
416             span_lint(
417                 cx,
418                 MISSING_ERRORS_DOC,
419                 span,
420                 "docs for function returning `Result` missing `# Errors` section",
421             );
422         } else {
423             if_chain! {
424                 if let Some(body_id) = body_id;
425                 if let Some(future) = cx.tcx.lang_items().future_trait();
426                 let typeck = cx.tcx.typeck_body(body_id);
427                 let body = cx.tcx.hir().body(body_id);
428                 let ret_ty = typeck.expr_ty(body.value);
429                 if implements_trait(cx, ret_ty, future, &[]);
430                 if let ty::Opaque(_, subs) = ret_ty.kind();
431                 if let Some(gen) = subs.types().next();
432                 if let ty::Generator(_, subs, _) = gen.kind();
433                 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::Result);
434                 then {
435                     span_lint(
436                         cx,
437                         MISSING_ERRORS_DOC,
438                         span,
439                         "docs for function returning `Result` missing `# Errors` section",
440                     );
441                 }
442             }
443         }
444     }
445 }
446
447 /// Cleanup documentation decoration.
448 ///
449 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
450 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
451 /// need to keep track of
452 /// the spans but this function is inspired from the later.
453 #[expect(clippy::cast_possible_truncation)]
454 #[must_use]
455 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
456     // one-line comments lose their prefix
457     if comment_kind == CommentKind::Line {
458         let mut doc = doc.to_owned();
459         doc.push('\n');
460         let len = doc.len();
461         // +3 skips the opening delimiter
462         return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
463     }
464
465     let mut sizes = vec![];
466     let mut contains_initial_stars = false;
467     for line in doc.lines() {
468         let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
469         debug_assert_eq!(offset as u32 as usize, offset);
470         contains_initial_stars |= line.trim_start().starts_with('*');
471         // +1 adds the newline, +3 skips the opening delimiter
472         sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
473     }
474     if !contains_initial_stars {
475         return (doc.to_string(), sizes);
476     }
477     // remove the initial '*'s if any
478     let mut no_stars = String::with_capacity(doc.len());
479     for line in doc.lines() {
480         let mut chars = line.chars();
481         for c in &mut chars {
482             if c.is_whitespace() {
483                 no_stars.push(c);
484             } else {
485                 no_stars.push(if c == '*' { ' ' } else { c });
486                 break;
487             }
488         }
489         no_stars.push_str(chars.as_str());
490         no_stars.push('\n');
491     }
492
493     (no_stars, sizes)
494 }
495
496 #[derive(Copy, Clone, Default)]
497 struct DocHeaders {
498     safety: bool,
499     errors: bool,
500     panics: bool,
501 }
502
503 fn check_attrs(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &[Attribute]) -> Option<DocHeaders> {
504     use pulldown_cmark::{BrokenLink, CowStr, Options};
505     /// We don't want the parser to choke on intra doc links. Since we don't
506     /// actually care about rendering them, just pretend that all broken links are
507     /// point to a fake address.
508     #[expect(clippy::unnecessary_wraps)] // we're following a type signature
509     fn fake_broken_link_callback<'a>(_: BrokenLink<'_>) -> Option<(CowStr<'a>, CowStr<'a>)> {
510         Some(("fake".into(), "fake".into()))
511     }
512
513     let mut doc = String::new();
514     let mut spans = vec![];
515
516     for attr in attrs {
517         if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
518             let (comment, current_spans) = strip_doc_comment_decoration(comment.as_str(), comment_kind, attr.span);
519             spans.extend_from_slice(&current_spans);
520             doc.push_str(&comment);
521         } else if attr.has_name(sym::doc) {
522             // ignore mix of sugared and non-sugared doc
523             // don't trigger the safety or errors check
524             return None;
525         }
526     }
527
528     let mut current = 0;
529     for &mut (ref mut offset, _) in &mut spans {
530         let offset_copy = *offset;
531         *offset = current;
532         current += offset_copy;
533     }
534
535     if doc.is_empty() {
536         return Some(DocHeaders::default());
537     }
538
539     let mut cb = fake_broken_link_callback;
540
541     let parser =
542         pulldown_cmark::Parser::new_with_broken_link_callback(&doc, Options::empty(), Some(&mut cb)).into_offset_iter();
543     // Iterate over all `Events` and combine consecutive events into one
544     let events = parser.coalesce(|previous, current| {
545         use pulldown_cmark::Event::Text;
546
547         let previous_range = previous.1;
548         let current_range = current.1;
549
550         match (previous.0, current.0) {
551             (Text(previous), Text(current)) => {
552                 let mut previous = previous.to_string();
553                 previous.push_str(&current);
554                 Ok((Text(previous.into()), previous_range))
555             },
556             (previous, current) => Err(((previous, previous_range), (current, current_range))),
557         }
558     });
559     Some(check_doc(cx, valid_idents, events, &spans))
560 }
561
562 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
563
564 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
565     cx: &LateContext<'_>,
566     valid_idents: &FxHashSet<String>,
567     events: Events,
568     spans: &[(usize, Span)],
569 ) -> DocHeaders {
570     // true if a safety header was found
571     use pulldown_cmark::Event::{
572         Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
573     };
574     use pulldown_cmark::Tag::{CodeBlock, Heading, Item, Link, Paragraph};
575     use pulldown_cmark::{CodeBlockKind, CowStr};
576
577     let mut headers = DocHeaders::default();
578     let mut in_code = false;
579     let mut in_link = None;
580     let mut in_heading = false;
581     let mut is_rust = false;
582     let mut edition = None;
583     let mut ticks_unbalanced = false;
584     let mut text_to_check: Vec<(CowStr<'_>, Span)> = Vec::new();
585     let mut paragraph_span = spans.get(0).expect("function isn't called if doc comment is empty").1;
586     for (event, range) in events {
587         match event {
588             Start(CodeBlock(ref kind)) => {
589                 in_code = true;
590                 if let CodeBlockKind::Fenced(lang) = kind {
591                     for item in lang.split(',') {
592                         if item == "ignore" {
593                             is_rust = false;
594                             break;
595                         }
596                         if let Some(stripped) = item.strip_prefix("edition") {
597                             is_rust = true;
598                             edition = stripped.parse::<Edition>().ok();
599                         } else if item.is_empty() || RUST_CODE.contains(&item) {
600                             is_rust = true;
601                         }
602                     }
603                 }
604             },
605             End(CodeBlock(_)) => {
606                 in_code = false;
607                 is_rust = false;
608             },
609             Start(Link(_, url, _)) => in_link = Some(url),
610             End(Link(..)) => in_link = None,
611             Start(Heading(_, _, _) | Paragraph | Item) => {
612                 if let Start(Heading(_, _, _)) = event {
613                     in_heading = true;
614                 }
615                 ticks_unbalanced = false;
616                 let (_, span) = get_current_span(spans, range.start);
617                 paragraph_span = first_line_of_span(cx, span);
618             },
619             End(Heading(_, _, _) | Paragraph | Item) => {
620                 if let End(Heading(_, _, _)) = event {
621                     in_heading = false;
622                 }
623                 if ticks_unbalanced {
624                     span_lint_and_help(
625                         cx,
626                         DOC_MARKDOWN,
627                         paragraph_span,
628                         "backticks are unbalanced",
629                         None,
630                         "a backtick may be missing a pair",
631                     );
632                 } else {
633                     for (text, span) in text_to_check {
634                         check_text(cx, valid_idents, &text, span);
635                     }
636                 }
637                 text_to_check = Vec::new();
638             },
639             Start(_tag) | End(_tag) => (), // We don't care about other tags
640             Html(_html) => (),             // HTML is weird, just ignore it
641             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
642             FootnoteReference(text) | Text(text) => {
643                 let (begin, span) = get_current_span(spans, range.start);
644                 paragraph_span = paragraph_span.with_hi(span.hi());
645                 ticks_unbalanced |= text.contains('`') && !in_code;
646                 if Some(&text) == in_link.as_ref() || ticks_unbalanced {
647                     // Probably a link of the form `<http://example.com>`
648                     // Which are represented as a link to "http://example.com" with
649                     // text "http://example.com" by pulldown-cmark
650                     continue;
651                 }
652                 let trimmed_text = text.trim();
653                 headers.safety |= in_heading && trimmed_text == "Safety";
654                 headers.safety |= in_heading && trimmed_text == "Implementation safety";
655                 headers.safety |= in_heading && trimmed_text == "Implementation Safety";
656                 headers.errors |= in_heading && trimmed_text == "Errors";
657                 headers.panics |= in_heading && trimmed_text == "Panics";
658                 if in_code {
659                     if is_rust {
660                         let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
661                         check_code(cx, &text, edition, span);
662                     }
663                 } else {
664                     check_link_quotes(cx, in_link.is_some(), trimmed_text, span, &range, begin, text.len());
665                     // Adjust for the beginning of the current `Event`
666                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
667                     text_to_check.push((text, span));
668                 }
669             },
670         }
671     }
672     headers
673 }
674
675 fn check_link_quotes(
676     cx: &LateContext<'_>,
677     in_link: bool,
678     trimmed_text: &str,
679     span: Span,
680     range: &Range<usize>,
681     begin: usize,
682     text_len: usize,
683 ) {
684     if in_link && trimmed_text.starts_with('\'') && trimmed_text.ends_with('\'') {
685         // fix the span to only point at the text within the link
686         let lo = span.lo() + BytePos::from_usize(range.start - begin);
687         span_lint(
688             cx,
689             DOC_LINK_WITH_QUOTES,
690             span.with_lo(lo).with_hi(lo + BytePos::from_usize(text_len)),
691             "possible intra-doc link using quotes instead of backticks",
692         );
693     }
694 }
695
696 fn get_current_span(spans: &[(usize, Span)], idx: usize) -> (usize, Span) {
697     let index = match spans.binary_search_by(|c| c.0.cmp(&idx)) {
698         Ok(o) => o,
699         Err(e) => e - 1,
700     };
701     spans[index]
702 }
703
704 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
705     fn has_needless_main(code: String, edition: Edition) -> bool {
706         rustc_driver::catch_fatal_errors(|| {
707             rustc_span::create_session_globals_then(edition, || {
708                 let filename = FileName::anon_source_code(&code);
709
710                 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
711                 let fallback_bundle =
712                     rustc_errors::fallback_fluent_bundle(rustc_errors::DEFAULT_LOCALE_RESOURCES, false);
713                 let emitter = EmitterWriter::new(
714                     Box::new(io::sink()),
715                     None,
716                     None,
717                     fallback_bundle,
718                     false,
719                     false,
720                     false,
721                     None,
722                     false,
723                     false,
724                 );
725                 let handler = Handler::with_emitter(false, None, Box::new(emitter));
726                 let sess = ParseSess::with_span_handler(handler, sm);
727
728                 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) {
729                     Ok(p) => p,
730                     Err(errs) => {
731                         drop(errs);
732                         return false;
733                     },
734                 };
735
736                 let mut relevant_main_found = false;
737                 loop {
738                     match parser.parse_item(ForceCollect::No) {
739                         Ok(Some(item)) => match &item.kind {
740                             ItemKind::Fn(box Fn {
741                                 sig, body: Some(block), ..
742                             }) if item.ident.name == sym::main => {
743                                 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
744                                 let returns_nothing = match &sig.decl.output {
745                                     FnRetTy::Default(..) => true,
746                                     FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
747                                     FnRetTy::Ty(_) => false,
748                                 };
749
750                                 if returns_nothing && !is_async && !block.stmts.is_empty() {
751                                     // This main function should be linted, but only if there are no other functions
752                                     relevant_main_found = true;
753                                 } else {
754                                     // This main function should not be linted, we're done
755                                     return false;
756                                 }
757                             },
758                             // Tests with one of these items are ignored
759                             ItemKind::Static(..)
760                             | ItemKind::Const(..)
761                             | ItemKind::ExternCrate(..)
762                             | ItemKind::ForeignMod(..)
763                             // Another function was found; this case is ignored
764                             | ItemKind::Fn(..) => return false,
765                             _ => {},
766                         },
767                         Ok(None) => break,
768                         Err(e) => {
769                             e.cancel();
770                             return false;
771                         },
772                     }
773                 }
774
775                 relevant_main_found
776             })
777         })
778         .ok()
779         .unwrap_or_default()
780     }
781
782     // Because of the global session, we need to create a new session in a different thread with
783     // the edition we need.
784     let text = text.to_owned();
785     if thread::spawn(move || has_needless_main(text, edition))
786         .join()
787         .expect("thread::spawn failed")
788     {
789         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
790     }
791 }
792
793 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
794     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
795         // Trim punctuation as in `some comment (see foo::bar).`
796         //                                                   ^^
797         // Or even as in `_foo bar_` which is emphasized. Also preserve `::` as a prefix/suffix.
798         let mut word = word.trim_matches(|c: char| !c.is_alphanumeric() && c != ':');
799
800         // Remove leading or trailing single `:` which may be part of a sentence.
801         if word.starts_with(':') && !word.starts_with("::") {
802             word = word.trim_start_matches(':');
803         }
804         if word.ends_with(':') && !word.ends_with("::") {
805             word = word.trim_end_matches(':');
806         }
807
808         if valid_idents.contains(word) || word.chars().all(|c| c == ':') {
809             continue;
810         }
811
812         // Adjust for the current word
813         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
814         let span = Span::new(
815             span.lo() + BytePos::from_usize(offset),
816             span.lo() + BytePos::from_usize(offset + word.len()),
817             span.ctxt(),
818             span.parent(),
819         );
820
821         check_word(cx, word, span);
822     }
823 }
824
825 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
826     /// Checks if a string is camel-case, i.e., contains at least two uppercase
827     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
828     /// Plurals are also excluded (`IDs` is ok).
829     fn is_camel_case(s: &str) -> bool {
830         if s.starts_with(|c: char| c.is_ascii_digit()) {
831             return false;
832         }
833
834         let s = s.strip_suffix('s').unwrap_or(s);
835
836         s.chars().all(char::is_alphanumeric)
837             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
838             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
839     }
840
841     fn has_underscore(s: &str) -> bool {
842         s != "_" && !s.contains("\\_") && s.contains('_')
843     }
844
845     fn has_hyphen(s: &str) -> bool {
846         s != "-" && s.contains('-')
847     }
848
849     if let Ok(url) = Url::parse(word) {
850         // try to get around the fact that `foo::bar` parses as a valid URL
851         if !url.cannot_be_a_base() {
852             span_lint(
853                 cx,
854                 DOC_MARKDOWN,
855                 span,
856                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
857             );
858
859             return;
860         }
861     }
862
863     // We assume that mixed-case words are not meant to be put inside backticks. (Issue #2343)
864     if has_underscore(word) && has_hyphen(word) {
865         return;
866     }
867
868     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
869         let mut applicability = Applicability::MachineApplicable;
870
871         span_lint_and_then(
872             cx,
873             DOC_MARKDOWN,
874             span,
875             "item in documentation is missing backticks",
876             |diag| {
877                 let snippet = snippet_with_applicability(cx, span, "..", &mut applicability);
878                 diag.span_suggestion_with_style(
879                     span,
880                     "try",
881                     format!("`{snippet}`"),
882                     applicability,
883                     // always show the suggestion in a separate line, since the
884                     // inline presentation adds another pair of backticks
885                     SuggestionStyle::ShowAlways,
886                 );
887             },
888         );
889     }
890 }
891
892 struct FindPanicUnwrap<'a, 'tcx> {
893     cx: &'a LateContext<'tcx>,
894     panic_span: Option<Span>,
895     typeck_results: &'tcx ty::TypeckResults<'tcx>,
896 }
897
898 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
899     type NestedFilter = nested_filter::OnlyBodies;
900
901     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
902         if self.panic_span.is_some() {
903             return;
904         }
905
906         if let Some(macro_call) = root_macro_call_first_node(self.cx, expr) {
907             if is_panic(self.cx, macro_call.def_id)
908                 || matches!(
909                     self.cx.tcx.item_name(macro_call.def_id).as_str(),
910                     "assert" | "assert_eq" | "assert_ne" | "todo"
911                 )
912             {
913                 self.panic_span = Some(macro_call.span);
914             }
915         }
916
917         // check for `unwrap`
918         if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
919             let receiver_ty = self.typeck_results.expr_ty(arglists[0].0).peel_refs();
920             if is_type_diagnostic_item(self.cx, receiver_ty, sym::Option)
921                 || is_type_diagnostic_item(self.cx, receiver_ty, sym::Result)
922             {
923                 self.panic_span = Some(expr.span);
924             }
925         }
926
927         // and check sub-expressions
928         intravisit::walk_expr(self, expr);
929     }
930
931     // Panics in const blocks will cause compilation to fail.
932     fn visit_anon_const(&mut self, _: &'tcx AnonConst) {}
933
934     fn nested_visit_map(&mut self) -> Self::Map {
935         self.cx.tcx.hir()
936     }
937 }