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