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