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