]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Rollup merge of #81680 - camsteffen:primty, r=oli-obk
[rust.git] / clippy_lints / src / doc.rs
1 use crate::utils::{
2     implements_trait, is_entrypoint_fn, is_type_diagnostic_item, match_panic_def_id, method_chain_args, return_ty,
3     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>, krate: &'tcx hir::Crate<'_>) {
212         check_attrs(cx, &self.valid_idents, &krate.item.attrs);
213     }
214
215     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
216         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
217         match item.kind {
218             hir::ItemKind::Fn(ref sig, _, body_id) => {
219                 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id).to_def_id())
220                     || in_external_macro(cx.tcx.sess, item.span))
221                 {
222                     let body = cx.tcx.hir().body(body_id);
223                     let impl_item_def_id = cx.tcx.hir().local_def_id(item.hir_id);
224                     let mut fpu = FindPanicUnwrap {
225                         cx,
226                         typeck_results: cx.tcx.typeck(impl_item_def_id),
227                         panic_span: None,
228                     };
229                     fpu.visit_expr(&body.value);
230                     lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id), fpu.panic_span);
231                 }
232             },
233             hir::ItemKind::Impl(ref impl_) => {
234                 self.in_trait_impl = impl_.of_trait.is_some();
235             },
236             _ => {},
237         }
238     }
239
240     fn check_item_post(&mut self, _cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
241         if let hir::ItemKind::Impl { .. } = item.kind {
242             self.in_trait_impl = false;
243         }
244     }
245
246     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
247         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
248         if let hir::TraitItemKind::Fn(ref sig, ..) = item.kind {
249             if !in_external_macro(cx.tcx.sess, item.span) {
250                 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, None, None);
251             }
252         }
253     }
254
255     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::ImplItem<'_>) {
256         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
257         if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
258             return;
259         }
260         if let hir::ImplItemKind::Fn(ref sig, body_id) = item.kind {
261             let body = cx.tcx.hir().body(body_id);
262             let impl_item_def_id = cx.tcx.hir().local_def_id(item.hir_id);
263             let mut fpu = FindPanicUnwrap {
264                 cx,
265                 typeck_results: cx.tcx.typeck(impl_item_def_id),
266                 panic_span: None,
267             };
268             fpu.visit_expr(&body.value);
269             lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers, Some(body_id), fpu.panic_span);
270         }
271     }
272 }
273
274 fn lint_for_missing_headers<'tcx>(
275     cx: &LateContext<'tcx>,
276     hir_id: hir::HirId,
277     span: impl Into<MultiSpan> + Copy,
278     sig: &hir::FnSig<'_>,
279     headers: DocHeaders,
280     body_id: Option<hir::BodyId>,
281     panic_span: Option<Span>,
282 ) {
283     if !cx.access_levels.is_exported(hir_id) {
284         return; // Private functions do not require doc comments
285     }
286     if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
287         span_lint(
288             cx,
289             MISSING_SAFETY_DOC,
290             span,
291             "unsafe function's docs miss `# Safety` section",
292         );
293     }
294     if !headers.panics && panic_span.is_some() {
295         span_lint_and_note(
296             cx,
297             MISSING_PANICS_DOC,
298             span,
299             "docs for function which may panic missing `# Panics` section",
300             panic_span,
301             "first possible panic found here",
302         );
303     }
304     if !headers.errors {
305         if is_type_diagnostic_item(cx, return_ty(cx, hir_id), sym::result_type) {
306             span_lint(
307                 cx,
308                 MISSING_ERRORS_DOC,
309                 span,
310                 "docs for function returning `Result` missing `# Errors` section",
311             );
312         } else {
313             if_chain! {
314                 if let Some(body_id) = body_id;
315                 if let Some(future) = cx.tcx.lang_items().future_trait();
316                 let def_id = cx.tcx.hir().body_owner_def_id(body_id);
317                 let mir = cx.tcx.optimized_mir(def_id.to_def_id());
318                 let ret_ty = mir.return_ty();
319                 if implements_trait(cx, ret_ty, future, &[]);
320                 if let ty::Opaque(_, subs) = ret_ty.kind();
321                 if let Some(gen) = subs.types().next();
322                 if let ty::Generator(_, subs, _) = gen.kind();
323                 if is_type_diagnostic_item(cx, subs.as_generator().return_ty(), sym::result_type);
324                 then {
325                     span_lint(
326                         cx,
327                         MISSING_ERRORS_DOC,
328                         span,
329                         "docs for function returning `Result` missing `# Errors` section",
330                     );
331                 }
332             }
333         }
334     }
335 }
336
337 /// Cleanup documentation decoration.
338 ///
339 /// We can't use `rustc_ast::attr::AttributeMethods::with_desugared_doc` or
340 /// `rustc_ast::parse::lexer::comments::strip_doc_comment_decoration` because we
341 /// need to keep track of
342 /// the spans but this function is inspired from the later.
343 #[allow(clippy::cast_possible_truncation)]
344 #[must_use]
345 pub fn strip_doc_comment_decoration(doc: &str, comment_kind: CommentKind, span: Span) -> (String, Vec<(usize, Span)>) {
346     // one-line comments lose their prefix
347     if comment_kind == CommentKind::Line {
348         let mut doc = doc.to_owned();
349         doc.push('\n');
350         let len = doc.len();
351         // +3 skips the opening delimiter
352         return (doc, vec![(len, span.with_lo(span.lo() + BytePos(3)))]);
353     }
354
355     let mut sizes = vec![];
356     let mut contains_initial_stars = false;
357     for line in doc.lines() {
358         let offset = line.as_ptr() as usize - doc.as_ptr() as usize;
359         debug_assert_eq!(offset as u32 as usize, offset);
360         contains_initial_stars |= line.trim_start().starts_with('*');
361         // +1 adds the newline, +3 skips the opening delimiter
362         sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(3 + offset as u32))));
363     }
364     if !contains_initial_stars {
365         return (doc.to_string(), sizes);
366     }
367     // remove the initial '*'s if any
368     let mut no_stars = String::with_capacity(doc.len());
369     for line in doc.lines() {
370         let mut chars = line.chars();
371         while let Some(c) = chars.next() {
372             if c.is_whitespace() {
373                 no_stars.push(c);
374             } else {
375                 no_stars.push(if c == '*' { ' ' } else { c });
376                 break;
377             }
378         }
379         no_stars.push_str(chars.as_str());
380         no_stars.push('\n');
381     }
382
383     (no_stars, sizes)
384 }
385
386 #[derive(Copy, Clone)]
387 struct DocHeaders {
388     safety: bool,
389     errors: bool,
390     panics: bool,
391 }
392
393 fn check_attrs<'a>(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
394     let mut doc = String::new();
395     let mut spans = vec![];
396
397     for attr in attrs {
398         if let AttrKind::DocComment(comment_kind, comment) = attr.kind {
399             let (comment, current_spans) = strip_doc_comment_decoration(&comment.as_str(), comment_kind, attr.span);
400             spans.extend_from_slice(&current_spans);
401             doc.push_str(&comment);
402         } else if attr.has_name(sym::doc) {
403             // ignore mix of sugared and non-sugared doc
404             // don't trigger the safety or errors check
405             return DocHeaders {
406                 safety: true,
407                 errors: true,
408                 panics: true,
409             };
410         }
411     }
412
413     let mut current = 0;
414     for &mut (ref mut offset, _) in &mut spans {
415         let offset_copy = *offset;
416         *offset = current;
417         current += offset_copy;
418     }
419
420     if doc.is_empty() {
421         return DocHeaders {
422             safety: false,
423             errors: false,
424             panics: false,
425         };
426     }
427
428     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
429     // Iterate over all `Events` and combine consecutive events into one
430     let events = parser.coalesce(|previous, current| {
431         use pulldown_cmark::Event::Text;
432
433         let previous_range = previous.1;
434         let current_range = current.1;
435
436         match (previous.0, current.0) {
437             (Text(previous), Text(current)) => {
438                 let mut previous = previous.to_string();
439                 previous.push_str(&current);
440                 Ok((Text(previous.into()), previous_range))
441             },
442             (previous, current) => Err(((previous, previous_range), (current, current_range))),
443         }
444     });
445     check_doc(cx, valid_idents, events, &spans)
446 }
447
448 const RUST_CODE: &[&str] = &["rust", "no_run", "should_panic", "compile_fail"];
449
450 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
451     cx: &LateContext<'_>,
452     valid_idents: &FxHashSet<String>,
453     events: Events,
454     spans: &[(usize, Span)],
455 ) -> DocHeaders {
456     // true if a safety header was found
457     use pulldown_cmark::CodeBlockKind;
458     use pulldown_cmark::Event::{
459         Code, End, FootnoteReference, HardBreak, Html, Rule, SoftBreak, Start, TaskListMarker, Text,
460     };
461     use pulldown_cmark::Tag::{CodeBlock, Heading, Link};
462
463     let mut headers = DocHeaders {
464         safety: false,
465         errors: false,
466         panics: false,
467     };
468     let mut in_code = false;
469     let mut in_link = None;
470     let mut in_heading = false;
471     let mut is_rust = false;
472     let mut edition = None;
473     for (event, range) in events {
474         match event {
475             Start(CodeBlock(ref kind)) => {
476                 in_code = true;
477                 if let CodeBlockKind::Fenced(lang) = kind {
478                     for item in lang.split(',') {
479                         if item == "ignore" {
480                             is_rust = false;
481                             break;
482                         }
483                         if let Some(stripped) = item.strip_prefix("edition") {
484                             is_rust = true;
485                             edition = stripped.parse::<Edition>().ok();
486                         } else if item.is_empty() || RUST_CODE.contains(&item) {
487                             is_rust = true;
488                         }
489                     }
490                 }
491             },
492             End(CodeBlock(_)) => {
493                 in_code = false;
494                 is_rust = false;
495             },
496             Start(Link(_, url, _)) => in_link = Some(url),
497             End(Link(..)) => in_link = None,
498             Start(Heading(_)) => in_heading = true,
499             End(Heading(_)) => in_heading = false,
500             Start(_tag) | End(_tag) => (), // We don't care about other tags
501             Html(_html) => (),             // HTML is weird, just ignore it
502             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
503             FootnoteReference(text) | Text(text) => {
504                 if Some(&text) == in_link.as_ref() {
505                     // Probably a link of the form `<http://example.com>`
506                     // Which are represented as a link to "http://example.com" with
507                     // text "http://example.com" by pulldown-cmark
508                     continue;
509                 }
510                 headers.safety |= in_heading && text.trim() == "Safety";
511                 headers.errors |= in_heading && text.trim() == "Errors";
512                 headers.panics |= in_heading && text.trim() == "Panics";
513                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
514                     Ok(o) => o,
515                     Err(e) => e - 1,
516                 };
517                 let (begin, span) = spans[index];
518                 if in_code {
519                     if is_rust {
520                         let edition = edition.unwrap_or_else(|| cx.tcx.sess.edition());
521                         check_code(cx, &text, edition, span);
522                     }
523                 } else {
524                     // Adjust for the beginning of the current `Event`
525                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
526
527                     check_text(cx, valid_idents, &text, span);
528                 }
529             },
530         }
531     }
532     headers
533 }
534
535 fn check_code(cx: &LateContext<'_>, text: &str, edition: Edition, span: Span) {
536     fn has_needless_main(code: &str, edition: Edition) -> bool {
537         rustc_driver::catch_fatal_errors(|| {
538             rustc_span::with_session_globals(edition, || {
539                 let filename = FileName::anon_source_code(code);
540
541                 let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
542                 let emitter = EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
543                 let handler = Handler::with_emitter(false, None, box emitter);
544                 let sess = ParseSess::with_span_handler(handler, sm);
545
546                 let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code.into()) {
547                     Ok(p) => p,
548                     Err(errs) => {
549                         for mut err in errs {
550                             err.cancel();
551                         }
552                         return false;
553                     },
554                 };
555
556                 let mut relevant_main_found = false;
557                 loop {
558                     match parser.parse_item(ForceCollect::No) {
559                         Ok(Some(item)) => match &item.kind {
560                             // Tests with one of these items are ignored
561                             ItemKind::Static(..)
562                             | ItemKind::Const(..)
563                             | ItemKind::ExternCrate(..)
564                             | ItemKind::ForeignMod(..) => return false,
565                             // We found a main function ...
566                             ItemKind::Fn(box FnKind(_, sig, _, Some(block)))
567                                 if item.ident.name == sym::main =>
568                             {
569                                 let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
570                                 let returns_nothing = match &sig.decl.output {
571                                     FnRetTy::Default(..) => true,
572                                     FnRetTy::Ty(ty) if ty.kind.is_unit() => true,
573                                     _ => false,
574                                 };
575
576                                 if returns_nothing && !is_async && !block.stmts.is_empty() {
577                                     // This main function should be linted, but only if there are no other functions
578                                     relevant_main_found = true;
579                                 } else {
580                                     // This main function should not be linted, we're done
581                                     return false;
582                                 }
583                             },
584                             // Another function was found; this case is ignored too
585                             ItemKind::Fn(..) => return false,
586                             _ => {},
587                         },
588                         Ok(None) => break,
589                         Err(mut e) => {
590                             e.cancel();
591                             return false;
592                         },
593                     }
594                 }
595
596                 relevant_main_found
597             })
598         })
599         .ok()
600         .unwrap_or_default()
601     }
602
603     if has_needless_main(text, edition) {
604         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
605     }
606 }
607
608 fn check_text(cx: &LateContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
609     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
610         // Trim punctuation as in `some comment (see foo::bar).`
611         //                                                   ^^
612         // Or even as in `_foo bar_` which is emphasized.
613         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
614
615         if valid_idents.contains(word) {
616             continue;
617         }
618
619         // Adjust for the current word
620         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
621         let span = Span::new(
622             span.lo() + BytePos::from_usize(offset),
623             span.lo() + BytePos::from_usize(offset + word.len()),
624             span.ctxt(),
625         );
626
627         check_word(cx, word, span);
628     }
629 }
630
631 fn check_word(cx: &LateContext<'_>, word: &str, span: Span) {
632     /// Checks if a string is camel-case, i.e., contains at least two uppercase
633     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
634     /// Plurals are also excluded (`IDs` is ok).
635     fn is_camel_case(s: &str) -> bool {
636         if s.starts_with(|c: char| c.is_digit(10)) {
637             return false;
638         }
639
640         let s = s.strip_suffix('s').unwrap_or(s);
641
642         s.chars().all(char::is_alphanumeric)
643             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
644             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
645     }
646
647     fn has_underscore(s: &str) -> bool {
648         s != "_" && !s.contains("\\_") && s.contains('_')
649     }
650
651     fn has_hyphen(s: &str) -> bool {
652         s != "-" && s.contains('-')
653     }
654
655     if let Ok(url) = Url::parse(word) {
656         // try to get around the fact that `foo::bar` parses as a valid URL
657         if !url.cannot_be_a_base() {
658             span_lint(
659                 cx,
660                 DOC_MARKDOWN,
661                 span,
662                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
663             );
664
665             return;
666         }
667     }
668
669     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
670     if has_underscore(word) && has_hyphen(word) {
671         return;
672     }
673
674     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
675         span_lint(
676             cx,
677             DOC_MARKDOWN,
678             span,
679             &format!("you should put `{}` between ticks in the documentation", word),
680         );
681     }
682 }
683
684 struct FindPanicUnwrap<'a, 'tcx> {
685     cx: &'a LateContext<'tcx>,
686     panic_span: Option<Span>,
687     typeck_results: &'tcx ty::TypeckResults<'tcx>,
688 }
689
690 impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
691     type Map = Map<'tcx>;
692
693     fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
694         if self.panic_span.is_some() {
695             return;
696         }
697
698         // check for `begin_panic`
699         if_chain! {
700             if let ExprKind::Call(ref func_expr, _) = expr.kind;
701             if let ExprKind::Path(QPath::Resolved(_, ref path)) = func_expr.kind;
702             if let Some(path_def_id) = path.res.opt_def_id();
703             if match_panic_def_id(self.cx, path_def_id);
704             then {
705                 self.panic_span = Some(expr.span);
706             }
707         }
708
709         // check for `unwrap`
710         if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
711             let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
712             if is_type_diagnostic_item(self.cx, reciever_ty, sym::option_type)
713                 || is_type_diagnostic_item(self.cx, reciever_ty, sym::result_type)
714             {
715                 self.panic_span = Some(expr.span);
716             }
717         }
718
719         // and check sub-expressions
720         intravisit::walk_expr(self, expr);
721     }
722
723     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
724         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
725     }
726 }