1 //! Detects links that are not linkified, e.g., in Markdown such as `Go to https://example.com/.`
2 //! Suggests wrapping the link with angle brackets: `Go to <https://example.com/>.` to linkify it.
5 use crate::core::DocContext;
6 use crate::html::markdown::main_body_opts;
7 use crate::visit::DocVisitor;
9 use pulldown_cmark::{Event, Parser, Tag};
11 use rustc_errors::Applicability;
13 use std::sync::LazyLock;
15 pub(crate) const CHECK_BARE_URLS: Pass = Pass {
16 name: "check-bare-urls",
18 description: "detects URLs that are not hyperlinks",
21 static URL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
23 r"https?://", // url scheme
24 r"([-a-zA-Z0-9@:%._\+~#=]{2,256}\.)+", // one or more subdomains
25 r"[a-zA-Z]{2,63}", // root domain
26 r"\b([-a-zA-Z0-9@:%_\+.~#?&/=]*)" // optional query or url fragments
28 .expect("failed to build regex")
31 struct BareUrlsLinter<'a, 'tcx> {
32 cx: &'a mut DocContext<'tcx>,
35 impl<'a, 'tcx> BareUrlsLinter<'a, 'tcx> {
40 f: &impl Fn(&DocContext<'_>, &str, &str, Range<usize>),
42 trace!("looking for raw urls in {}", text);
43 // For now, we only check "full" URLs (meaning, starting with "http://" or "https://").
44 for match_ in URL_REGEX.find_iter(text) {
45 let url = match_.as_str();
46 let url_range = match_.range();
49 "this URL is not a hyperlink",
51 Range { start: range.start + url_range.start, end: range.start + url_range.end },
57 pub(crate) fn check_bare_urls(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
58 BareUrlsLinter { cx }.visit_crate(&krate);
62 impl<'a, 'tcx> DocVisitor for BareUrlsLinter<'a, 'tcx> {
63 fn visit_item(&mut self, item: &Item) {
64 let Some(hir_id) = DocContext::as_local_hir_id(self.cx.tcx, item.item_id)
66 // If non-local, no need to check anything.
69 let dox = item.attrs.collapsed_doc_value().unwrap_or_default();
71 let report_diag = |cx: &DocContext<'_>, msg: &str, url: &str, range: Range<usize>| {
72 let sp = super::source_span_for_markdown_range(cx.tcx, &dox, &range, &item.attrs)
73 .unwrap_or_else(|| item.attr_span(cx.tcx));
74 cx.tcx.struct_span_lint_hir(crate::lint::BARE_URLS, hir_id, sp, msg, |lint| {
75 lint.note("bare URLs are not automatically turned into clickable links")
78 "use an automatic link instead",
80 Applicability::MachineApplicable,
85 let mut p = Parser::new_ext(&dox, main_body_opts()).into_offset_iter();
87 while let Some((event, range)) = p.next() {
89 Event::Text(s) => self.find_raw_urls(&s, range, &report_diag),
90 // We don't want to check the text inside code blocks or links.
91 Event::Start(tag @ (Tag::CodeBlock(_) | Tag::Link(..))) => {
92 while let Some((event, _)) = p.next() {
95 if mem::discriminant(&end) == mem::discriminant(&tag) =>
108 self.visit_item_recur(item)