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::passes::source_span_for_markdown_range;
9 use pulldown_cmark::{Event, Parser, Tag};
11 use rustc_errors::Applicability;
13 use std::sync::LazyLock;
15 pub(super) fn visit_item(cx: &DocContext<'_>, item: &Item) {
16 let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id)
18 // If non-local, no need to check anything.
21 let dox = item.attrs.collapsed_doc_value().unwrap_or_default();
23 let report_diag = |cx: &DocContext<'_>, msg: &str, url: &str, range: Range<usize>| {
24 let sp = source_span_for_markdown_range(cx.tcx, &dox, &range, &item.attrs)
25 .unwrap_or_else(|| item.attr_span(cx.tcx));
26 cx.tcx.struct_span_lint_hir(crate::lint::BARE_URLS, hir_id, sp, msg, |lint| {
27 lint.note("bare URLs are not automatically turned into clickable links")
30 "use an automatic link instead",
32 Applicability::MachineApplicable,
37 let mut p = Parser::new_ext(&dox, main_body_opts()).into_offset_iter();
39 while let Some((event, range)) = p.next() {
41 Event::Text(s) => find_raw_urls(cx, &s, range, &report_diag),
42 // We don't want to check the text inside code blocks or links.
43 Event::Start(tag @ (Tag::CodeBlock(_) | Tag::Link(..))) => {
44 while let Some((event, _)) = p.next() {
47 if mem::discriminant(&end) == mem::discriminant(&tag) =>
61 static URL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
63 r"https?://", // url scheme
64 r"([-a-zA-Z0-9@:%._\+~#=]{2,256}\.)+", // one or more subdomains
65 r"[a-zA-Z]{2,63}", // root domain
66 r"\b([-a-zA-Z0-9@:%_\+.~#?&/=]*)" // optional query or url fragments
68 .expect("failed to build regex")
75 f: &impl Fn(&DocContext<'_>, &str, &str, Range<usize>),
77 trace!("looking for raw urls in {}", text);
78 // For now, we only check "full" URLs (meaning, starting with "http://" or "https://").
79 for match_ in URL_REGEX.find_iter(text) {
80 let url = match_.as_str();
81 let url_range = match_.range();
84 "this URL is not a hyperlink",
86 Range { start: range.start + url_range.start, end: range.start + url_range.end },