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