]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/automatic_links.rs
Fix automatic_links warnings
[rust.git] / src / librustdoc / passes / automatic_links.rs
1 use super::{span_of_attrs, Pass};
2 use crate::clean::*;
3 use crate::core::DocContext;
4 use crate::fold::DocFolder;
5 use crate::html::markdown::opts;
6 use core::ops::Range;
7 use pulldown_cmark::{Event, LinkType, Parser, Tag};
8 use regex::Regex;
9 use rustc_errors::Applicability;
10 use rustc_feature::UnstableFeatures;
11 use rustc_session::lint;
12
13 pub const CHECK_AUTOMATIC_LINKS: Pass = Pass {
14     name: "check-automatic-links",
15     run: check_automatic_links,
16     description: "detects URLS that could be written using angle brackets",
17 };
18
19 const URL_REGEX: &str = concat!(
20     r"https?://",                          // url scheme
21     r"([-a-zA-Z0-9@:%._\+~#=]{2,256}\.)+", // one or more subdomains
22     r"[a-zA-Z]{2,4}",                      // root domain
23     r"\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)"     // optional query or url fragments
24 );
25
26 struct AutomaticLinksLinter<'a, 'tcx> {
27     cx: &'a DocContext<'tcx>,
28     regex: Regex,
29 }
30
31 impl<'a, 'tcx> AutomaticLinksLinter<'a, 'tcx> {
32     fn new(cx: &'a DocContext<'tcx>) -> Self {
33         AutomaticLinksLinter { cx, regex: Regex::new(URL_REGEX).expect("failed to build regex") }
34     }
35
36     fn find_raw_urls(
37         &self,
38         text: &str,
39         range: Range<usize>,
40         f: &impl Fn(&DocContext<'_>, &str, &str, Range<usize>),
41     ) {
42         // For now, we only check "full" URLs (meaning, starting with "http://" or "https://").
43         for match_ in self.regex.find_iter(&text) {
44             let url = match_.as_str();
45             let url_range = match_.range();
46             f(
47                 self.cx,
48                 "this URL is not a hyperlink",
49                 url,
50                 Range { start: range.start + url_range.start, end: range.start + url_range.end },
51             );
52         }
53     }
54 }
55
56 pub fn check_automatic_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
57     if !UnstableFeatures::from_environment().is_nightly_build() {
58         krate
59     } else {
60         let mut coll = AutomaticLinksLinter::new(cx);
61
62         coll.fold_crate(krate)
63     }
64 }
65
66 impl<'a, 'tcx> DocFolder for AutomaticLinksLinter<'a, 'tcx> {
67     fn fold_item(&mut self, item: Item) -> Option<Item> {
68         let hir_id = match self.cx.as_local_hir_id(item.def_id) {
69             Some(hir_id) => hir_id,
70             None => {
71                 // If non-local, no need to check anything.
72                 return self.fold_item_recur(item);
73             }
74         };
75         let dox = item.attrs.collapsed_doc_value().unwrap_or_default();
76         if !dox.is_empty() {
77             let report_diag = |cx: &DocContext<'_>, msg: &str, url: &str, range: Range<usize>| {
78                 let sp = super::source_span_for_markdown_range(cx, &dox, &range, &item.attrs)
79                     .or_else(|| span_of_attrs(&item.attrs))
80                     .unwrap_or(item.source.span());
81                 cx.tcx.struct_span_lint_hir(lint::builtin::AUTOMATIC_LINKS, hir_id, sp, |lint| {
82                     lint.build(msg)
83                         .span_suggestion(
84                             sp,
85                             "use an automatic link instead",
86                             format!("<{}>", url),
87                             Applicability::MachineApplicable,
88                         )
89                         .emit()
90                 });
91             };
92
93             let p = Parser::new_ext(&dox, opts()).into_offset_iter();
94
95             let mut title = String::new();
96             let mut in_link = false;
97             let mut ignore = false;
98
99             for (event, range) in p {
100                 match event {
101                     Event::Start(Tag::Link(kind, _, _)) => {
102                         in_link = true;
103                         ignore = matches!(kind, LinkType::Autolink | LinkType::Email);
104                     }
105                     Event::End(Tag::Link(_, url, _)) => {
106                         in_link = false;
107                         // NOTE: links cannot be nested, so we don't need to check `kind`
108                         if url.as_ref() == title && !ignore {
109                             report_diag(self.cx, "unneeded long form for URL", &url, range);
110                         }
111                         title.clear();
112                         ignore = false;
113                     }
114                     Event::Text(s) if in_link => {
115                         if !ignore {
116                             title.push_str(&s);
117                         }
118                     }
119                     Event::Text(s) => self.find_raw_urls(&s, range, &report_diag),
120                     _ => {}
121                 }
122             }
123         }
124
125         self.fold_item_recur(item)
126     }
127 }