Skip to content

Commit 791fdff

Browse files
Better handling of paths in link to def feature
1 parent bcd4e2e commit 791fdff

7 files changed

+172
-89
lines changed

src/librustdoc/html/highlight.rs

+76-48
Original file line numberDiff line numberDiff line change
@@ -944,6 +944,65 @@ fn string<T: Display>(
944944
}
945945
}
946946

947+
fn generate_link_to_def(
948+
out: &mut impl Write,
949+
text_s: &str,
950+
klass: Class,
951+
href_context: &Option<HrefContext<'_, '_>>,
952+
def_span: Span,
953+
open_tag: bool,
954+
) -> bool {
955+
if let Some(href_context) = href_context {
956+
if let Some(href) =
957+
href_context.context.shared.span_correspondence_map.get(&def_span).and_then(|href| {
958+
let context = href_context.context;
959+
// FIXME: later on, it'd be nice to provide two links (if possible) for all items:
960+
// one to the documentation page and one to the source definition.
961+
// FIXME: currently, external items only generate a link to their documentation,
962+
// a link to their definition can be generated using this:
963+
// https://github.com/rust-lang/rust/blob/60f1a2fc4b535ead9c85ce085fdce49b1b097531/src/librustdoc/html/render/context.rs#L315-L338
964+
match href {
965+
LinkFromSrc::Local(span) => {
966+
context.href_from_span_relative(*span, &href_context.current_href)
967+
}
968+
LinkFromSrc::External(def_id) => {
969+
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
970+
.ok()
971+
.map(|(url, _, _)| url)
972+
}
973+
LinkFromSrc::Primitive(prim) => format::href_with_root_path(
974+
PrimitiveType::primitive_locations(context.tcx())[prim],
975+
context,
976+
Some(href_context.root_path),
977+
)
978+
.ok()
979+
.map(|(url, _, _)| url),
980+
LinkFromSrc::Doc(def_id) => {
981+
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
982+
.ok()
983+
.map(|(doc_link, _, _)| doc_link)
984+
}
985+
}
986+
})
987+
{
988+
if !open_tag {
989+
// We're already inside an element which has the same klass, no need to give it
990+
// again.
991+
write!(out, "<a href=\"{href}\">{text_s}").unwrap();
992+
} else {
993+
let klass_s = klass.as_html();
994+
if klass_s.is_empty() {
995+
write!(out, "<a href=\"{href}\">{text_s}").unwrap();
996+
} else {
997+
write!(out, "<a class=\"{klass_s}\" href=\"{href}\">{text_s}").unwrap();
998+
}
999+
}
1000+
return true;
1001+
}
1002+
}
1003+
false
1004+
}
1005+
9471006
/// This function writes `text` into `out` with some modifications depending on `klass`:
9481007
///
9491008
/// * If `klass` is `None`, `text` is written into `out` with no modification.
@@ -973,10 +1032,14 @@ fn string_without_closing_tag<T: Display>(
9731032
return Some("</span>");
9741033
};
9751034

1035+
let mut added_links = false;
9761036
let mut text_s = text.to_string();
9771037
if text_s.contains("::") {
1038+
let mut span = def_span.with_hi(def_span.lo());
9781039
text_s = text_s.split("::").intersperse("::").fold(String::new(), |mut path, t| {
1040+
span = span.with_hi(span.hi() + BytePos(t.len() as _));
9791041
match t {
1042+
"::" => write!(&mut path, "::"),
9801043
"self" | "Self" => write!(
9811044
&mut path,
9821045
"<span class=\"{klass}\">{t}</span>",
@@ -989,60 +1052,25 @@ fn string_without_closing_tag<T: Display>(
9891052
klass = Class::KeyWord.as_html(),
9901053
)
9911054
}
992-
t => write!(&mut path, "{t}"),
1055+
t => {
1056+
if !t.is_empty()
1057+
&& generate_link_to_def(&mut path, t, klass, href_context, span, open_tag)
1058+
{
1059+
added_links = true;
1060+
write!(&mut path, "</a>")
1061+
} else {
1062+
write!(&mut path, "{t}")
1063+
}
1064+
}
9931065
}
9941066
.expect("Failed to build source HTML path");
1067+
span = span.with_lo(span.lo() + BytePos(t.len() as _));
9951068
path
9961069
});
9971070
}
9981071

999-
if let Some(href_context) = href_context {
1000-
if let Some(href) =
1001-
href_context.context.shared.span_correspondence_map.get(&def_span).and_then(|href| {
1002-
let context = href_context.context;
1003-
// FIXME: later on, it'd be nice to provide two links (if possible) for all items:
1004-
// one to the documentation page and one to the source definition.
1005-
// FIXME: currently, external items only generate a link to their documentation,
1006-
// a link to their definition can be generated using this:
1007-
// https://github.com/rust-lang/rust/blob/60f1a2fc4b535ead9c85ce085fdce49b1b097531/src/librustdoc/html/render/context.rs#L315-L338
1008-
match href {
1009-
LinkFromSrc::Local(span) => {
1010-
context.href_from_span_relative(*span, &href_context.current_href)
1011-
}
1012-
LinkFromSrc::External(def_id) => {
1013-
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
1014-
.ok()
1015-
.map(|(url, _, _)| url)
1016-
}
1017-
LinkFromSrc::Primitive(prim) => format::href_with_root_path(
1018-
PrimitiveType::primitive_locations(context.tcx())[prim],
1019-
context,
1020-
Some(href_context.root_path),
1021-
)
1022-
.ok()
1023-
.map(|(url, _, _)| url),
1024-
LinkFromSrc::Doc(def_id) => {
1025-
format::href_with_root_path(*def_id, context, Some(href_context.root_path))
1026-
.ok()
1027-
.map(|(doc_link, _, _)| doc_link)
1028-
}
1029-
}
1030-
})
1031-
{
1032-
if !open_tag {
1033-
// We're already inside an element which has the same klass, no need to give it
1034-
// again.
1035-
write!(out, "<a href=\"{href}\">{text_s}").unwrap();
1036-
} else {
1037-
let klass_s = klass.as_html();
1038-
if klass_s.is_empty() {
1039-
write!(out, "<a href=\"{href}\">{text_s}").unwrap();
1040-
} else {
1041-
write!(out, "<a class=\"{klass_s}\" href=\"{href}\">{text_s}").unwrap();
1042-
}
1043-
}
1044-
return Some("</a>");
1045-
}
1072+
if !added_links && generate_link_to_def(out, &text_s, klass, href_context, def_span, open_tag) {
1073+
return Some("</a>");
10461074
}
10471075
if !open_tag {
10481076
write!(out, "{}", text_s).unwrap();

src/librustdoc/html/render/span_map.rs

+38-23
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ struct SpanMapVisitor<'tcx> {
6565

6666
impl SpanMapVisitor<'_> {
6767
/// This function is where we handle `hir::Path` elements and add them into the "span map".
68-
fn handle_path(&mut self, path: &rustc_hir::Path<'_>) {
68+
fn handle_path(&mut self, path: &rustc_hir::Path<'_>, only_use_last_segment: bool) {
6969
match path.res {
7070
// FIXME: For now, we handle `DefKind` if it's not a `DefKind::TyParam`.
7171
// Would be nice to support them too alongside the other `DefKind`
@@ -77,25 +77,38 @@ impl SpanMapVisitor<'_> {
7777
LinkFromSrc::External(def_id)
7878
};
7979
// In case the path ends with generics, we remove them from the span.
80-
let span = path
81-
.segments
82-
.last()
83-
.map(|last| {
84-
// In `use` statements, the included item is not in the path segments.
85-
// However, it doesn't matter because you can't have generics on `use`
86-
// statements.
87-
if path.span.contains(last.ident.span) {
88-
path.span.with_hi(last.ident.span.hi())
89-
} else {
90-
path.span
91-
}
92-
})
93-
.unwrap_or(path.span);
80+
let span = if only_use_last_segment
81+
&& let Some(path_span) = path.segments.last().map(|segment| segment.ident.span)
82+
{
83+
path_span
84+
} else {
85+
path.segments
86+
.last()
87+
.map(|last| {
88+
// In `use` statements, the included item is not in the path segments.
89+
// However, it doesn't matter because you can't have generics on `use`
90+
// statements.
91+
if path.span.contains(last.ident.span) {
92+
path.span.with_hi(last.ident.span.hi())
93+
} else {
94+
path.span
95+
}
96+
})
97+
.unwrap_or(path.span)
98+
};
9499
self.matches.insert(span, link);
95100
}
96101
Res::Local(_) => {
97102
if let Some(span) = self.tcx.hir().res_span(path.res) {
98-
self.matches.insert(path.span, LinkFromSrc::Local(clean::Span::new(span)));
103+
let path_span = if only_use_last_segment
104+
&& let Some(path_span) =
105+
path.segments.last().map(|segment| segment.ident.span)
106+
{
107+
path_span
108+
} else {
109+
path.span
110+
};
111+
self.matches.insert(path_span, LinkFromSrc::Local(clean::Span::new(span)));
99112
}
100113
}
101114
Res::PrimTy(p) => {
@@ -202,11 +215,11 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> {
202215
if self.handle_macro(path.span) {
203216
return;
204217
}
205-
self.handle_path(path);
218+
self.handle_path(path, false);
206219
intravisit::walk_path(self, path);
207220
}
208221

209-
fn visit_qpath(&mut self, qpath: &QPath<'tcx>, id: HirId, span: Span) {
222+
fn visit_qpath(&mut self, qpath: &QPath<'tcx>, id: HirId, _span: Span) {
210223
match *qpath {
211224
QPath::TypeRelative(qself, path) => {
212225
if matches!(path.res, Res::Err) {
@@ -216,23 +229,25 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> {
216229
let typeck_results = tcx.typeck_body(hir.body_owned_by(body_id).id());
217230
let path = rustc_hir::Path {
218231
// We change the span to not include parens.
219-
span: span.with_hi(path.ident.span.hi()),
232+
span: path.ident.span,
220233
res: typeck_results.qpath_res(qpath, id),
221234
segments: &[],
222235
};
223-
self.handle_path(&path);
236+
self.handle_path(&path, false);
224237
} else {
225-
self.infer_id(path.hir_id, Some(id), span);
238+
self.infer_id(path.hir_id, Some(id), path.ident.span);
226239
}
227240

228241
rustc_ast::visit::try_visit!(self.visit_ty(qself));
229242
self.visit_path_segment(path);
230243
}
231244
QPath::Resolved(maybe_qself, path) => {
232-
self.handle_path(path);
245+
self.handle_path(path, true);
233246

234247
rustc_ast::visit::visit_opt!(self, visit_ty, maybe_qself);
235-
self.visit_path(path, id)
248+
if !self.handle_macro(path.span) {
249+
intravisit::walk_path(self, path);
250+
}
236251
}
237252
_ => {}
238253
}

tests/rustdoc/check-source-code-urls-to-def.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ fn babar() {}
3333
//@ has - '//pre[@class="rust"]//a/@href' '/primitive.str.html'
3434
//@ count - '//pre[@class="rust"]//a[@href="#23"]' 5
3535
//@ has - '//pre[@class="rust"]//a[@href="../../source_code/struct.SourceCode.html"]' \
36-
// 'source_code::SourceCode'
36+
// 'SourceCode'
3737
pub fn foo(a: u32, b: &str, c: String, d: Foo, e: bar::Bar, f: source_code::SourceCode) {
3838
let x = 12;
3939
let y: Foo = Foo;
+46-7
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,54 @@
1+
// This test ensures that patterns also get a link generated.
2+
13
//@ compile-flags: -Zunstable-options --generate-link-to-definition
24

35
#![crate_name = "foo"]
46

5-
pub enum Ty {
6-
Var,
7+
//@ has 'src/foo/jump-to-def-assoc-items.rs.html'
8+
9+
pub trait Trait {
10+
type T;
11+
}
12+
pub trait Another {
13+
type T;
14+
const X: u32;
715
}
816

9-
//@ has 'src/foo/jump-to-def-assoc-items.rs.html'
10-
//@ has - '//a[@href="#6"]' 'Self::Var'
11-
impl Ty {
12-
fn f() {
13-
let _ = Self::Var;
17+
pub struct Foo;
18+
19+
impl Foo {
20+
pub fn new() -> Self { Foo }
21+
}
22+
23+
pub struct C;
24+
25+
impl C {
26+
pub fn wat() {}
27+
}
28+
29+
pub struct Bar;
30+
impl Trait for Bar {
31+
type T = Foo;
32+
}
33+
impl Another for Bar {
34+
type T = C;
35+
const X: u32 = 12;
36+
}
37+
38+
pub fn bar() {
39+
//@ has - '//a[@href="#20"]' 'new'
40+
<Bar as Trait>::T::new();
41+
//@ has - '//a[@href="#26"]' 'wat'
42+
<Bar as Another>::T::wat();
43+
44+
match 12u32 {
45+
//@ has - '//a[@href="#14"]' 'X'
46+
<Bar as Another>::X => {}
47+
_ => {}
1448
}
1549
}
50+
51+
pub struct Far {
52+
//@ has - '//a[@href="#10"]' 'T'
53+
x: <Bar as Trait>::T,
54+
}

tests/rustdoc/jump-to-def-doc-links-calls.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@
88
pub struct Bar;
99

1010
impl std::default::Default for Bar {
11-
//@ has - '//a[@href="#20-22"]' 'Self::new'
11+
//@ has - '//a[@href="#20-22"]' 'new'
1212
fn default() -> Self {
1313
Self::new()
1414
}
1515
}
1616

1717
//@ has - '//a[@href="#8"]' 'Bar'
1818
impl Bar {
19-
//@ has - '//a[@href="#24-26"]' 'Self::bar'
19+
//@ has - '//a[@href="#24-26"]' 'bar'
2020
pub fn new()-> Self {
2121
Self::bar()
2222
}

tests/rustdoc/jump-to-def-pats.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,13 @@ pub fn foo() -> Result<(), ()> {
3030
impl<T, E> fmt::Display for MyEnum<T, E> {
3131
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3232
match self {
33-
//@ has - '//a[@href="#12"]' 'Self::Ok'
33+
//@ has - '//a[@href="#12"]' 'Ok'
3434
Self::Ok(_) => f.write_str("MyEnum::Ok"),
35-
//@ has - '//a[@href="#13"]' 'MyEnum::Err'
35+
//@ has - '//a[@href="#13"]' 'Err'
3636
MyEnum::Err(_) => f.write_str("MyEnum::Err"),
37-
//@ has - '//a[@href="#14"]' 'Self::Some'
37+
//@ has - '//a[@href="#14"]' 'Some'
3838
Self::Some(_) => f.write_str("MyEnum::Some"),
39-
//@ has - '//a[@href="#15"]' 'Self::None'
39+
//@ has - '//a[@href="#15"]' 'None'
4040
Self::None => f.write_str("MyEnum::None"),
4141
}
4242
}
@@ -45,7 +45,7 @@ impl<T, E> fmt::Display for MyEnum<T, E> {
4545
impl X {
4646
fn p(&self) -> &str {
4747
match self {
48-
//@ has - '//a[@href="#19"]' 'Self::A'
48+
//@ has - '//a[@href="#19"]' 'A'
4949
Self::A => "X::A",
5050
}
5151
}

0 commit comments

Comments
 (0)