Skip to content

Commit a6470c7

Browse files
committed
Auto merge of #86662 - mockersf:fix-86620-link-unknown-location, r=jyn514
fix dead link for method in trait of blanket impl from third party crate fix #86620 * changes `href` method to raise the actual error it had instead of an `Option` * set the href link correctly in case of an error I did not manage to make a small reproducer, I think it happens in a situation where * crate A expose a trait with a blanket impl * crate B use the trait from crate A * crate C use types from crate B * building docs for crate C without dependencies r? `@jyn514`
2 parents 057050a + 450c28a commit a6470c7

File tree

6 files changed

+71
-31
lines changed

6 files changed

+71
-31
lines changed

Diff for: src/librustdoc/clean/types.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -459,7 +459,7 @@ impl Item {
459459
.filter_map(|ItemLink { link: s, link_text, did, ref fragment }| {
460460
match did {
461461
Some(did) => {
462-
if let Some((mut href, ..)) = href(did.clone(), cx) {
462+
if let Ok((mut href, ..)) = href(did.clone(), cx) {
463463
if let Some(ref fragment) = *fragment {
464464
href.push('#');
465465
href.push_str(fragment);

Diff for: src/librustdoc/html/format.rs

+37-22
Original file line numberDiff line numberDiff line change
@@ -472,15 +472,27 @@ impl clean::GenericArgs {
472472
}
473473
}
474474

475-
crate fn href(did: DefId, cx: &Context<'_>) -> Option<(String, ItemType, Vec<String>)> {
475+
// Possible errors when computing href link source for a `DefId`
476+
crate enum HrefError {
477+
/// This item is known to rustdoc, but from a crate that does not have documentation generated.
478+
///
479+
/// This can only happen for non-local items.
480+
DocumentationNotBuilt,
481+
/// This can only happen for non-local items when `--document-private-items` is not passed.
482+
Private,
483+
// Not in external cache, href link should be in same page
484+
NotInExternalCache,
485+
}
486+
487+
crate fn href(did: DefId, cx: &Context<'_>) -> Result<(String, ItemType, Vec<String>), HrefError> {
476488
let cache = &cx.cache();
477489
let relative_to = &cx.current;
478490
fn to_module_fqp(shortty: ItemType, fqp: &[String]) -> &[String] {
479491
if shortty == ItemType::Module { &fqp[..] } else { &fqp[..fqp.len() - 1] }
480492
}
481493

482494
if !did.is_local() && !cache.access_levels.is_public(did) && !cache.document_private {
483-
return None;
495+
return Err(HrefError::Private);
484496
}
485497

486498
let (fqp, shortty, mut url_parts) = match cache.paths.get(&did) {
@@ -489,22 +501,25 @@ crate fn href(did: DefId, cx: &Context<'_>) -> Option<(String, ItemType, Vec<Str
489501
href_relative_parts(module_fqp, relative_to)
490502
}),
491503
None => {
492-
let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
493-
let module_fqp = to_module_fqp(shortty, fqp);
494-
(
495-
fqp,
496-
shortty,
497-
match cache.extern_locations[&did.krate] {
498-
ExternalLocation::Remote(ref s) => {
499-
let s = s.trim_end_matches('/');
500-
let mut s = vec![&s[..]];
501-
s.extend(module_fqp[..].iter().map(String::as_str));
502-
s
503-
}
504-
ExternalLocation::Local => href_relative_parts(module_fqp, relative_to),
505-
ExternalLocation::Unknown => return None,
506-
},
507-
)
504+
if let Some(&(ref fqp, shortty)) = cache.external_paths.get(&did) {
505+
let module_fqp = to_module_fqp(shortty, fqp);
506+
(
507+
fqp,
508+
shortty,
509+
match cache.extern_locations[&did.krate] {
510+
ExternalLocation::Remote(ref s) => {
511+
let s = s.trim_end_matches('/');
512+
let mut s = vec![&s[..]];
513+
s.extend(module_fqp[..].iter().map(String::as_str));
514+
s
515+
}
516+
ExternalLocation::Local => href_relative_parts(module_fqp, relative_to),
517+
ExternalLocation::Unknown => return Err(HrefError::DocumentationNotBuilt),
518+
},
519+
)
520+
} else {
521+
return Err(HrefError::NotInExternalCache);
522+
}
508523
}
509524
};
510525
let last = &fqp.last().unwrap()[..];
@@ -518,7 +533,7 @@ crate fn href(did: DefId, cx: &Context<'_>) -> Option<(String, ItemType, Vec<Str
518533
url_parts.push(&filename);
519534
}
520535
}
521-
Some((url_parts.join("/"), shortty, fqp.to_vec()))
536+
Ok((url_parts.join("/"), shortty, fqp.to_vec()))
522537
}
523538

524539
/// Both paths should only be modules.
@@ -567,7 +582,7 @@ fn resolved_path<'a, 'cx: 'a>(
567582
write!(w, "{}{:#}", &last.name, last.args.print(cx))?;
568583
} else {
569584
let path = if use_absolute {
570-
if let Some((_, _, fqp)) = href(did, cx) {
585+
if let Ok((_, _, fqp)) = href(did, cx) {
571586
format!(
572587
"{}::{}",
573588
fqp[..fqp.len() - 1].join("::"),
@@ -675,7 +690,7 @@ crate fn anchor<'a, 'cx: 'a>(
675690
) -> impl fmt::Display + 'a {
676691
let parts = href(did.into(), cx);
677692
display_fn(move |f| {
678-
if let Some((url, short_ty, fqp)) = parts {
693+
if let Ok((url, short_ty, fqp)) = parts {
679694
write!(
680695
f,
681696
r#"<a class="{}" href="{}" title="{} {}">{}</a>"#,
@@ -907,7 +922,7 @@ fn fmt_type<'cx>(
907922
// look at).
908923
box clean::ResolvedPath { did, .. } => {
909924
match href(did.into(), cx) {
910-
Some((ref url, _, ref path)) if !f.alternate() => {
925+
Ok((ref url, _, ref path)) if !f.alternate() => {
911926
write!(
912927
f,
913928
"<a class=\"type\" href=\"{url}#{shortty}.{name}\" \

Diff for: src/librustdoc/html/render/mod.rs

+11-8
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ use crate::formats::{AssocItemRender, Impl, RenderMode};
6262
use crate::html::escape::Escape;
6363
use crate::html::format::{
6464
href, print_abi_with_space, print_constness_with_space, print_default_space,
65-
print_generic_bounds, print_where_clause, Buffer, PrintWithSpace,
65+
print_generic_bounds, print_where_clause, Buffer, HrefError, PrintWithSpace,
6666
};
6767
use crate::html::markdown::{Markdown, MarkdownHtml, MarkdownSummaryLine};
6868

@@ -856,8 +856,8 @@ fn render_assoc_item(
856856
) {
857857
let name = meth.name.as_ref().unwrap();
858858
let href = match link {
859-
AssocItemLink::Anchor(Some(ref id)) => format!("#{}", id),
860-
AssocItemLink::Anchor(None) => format!("#{}.{}", meth.type_(), name),
859+
AssocItemLink::Anchor(Some(ref id)) => Some(format!("#{}", id)),
860+
AssocItemLink::Anchor(None) => Some(format!("#{}.{}", meth.type_(), name)),
861861
AssocItemLink::GotoSource(did, provided_methods) => {
862862
// We're creating a link from an impl-item to the corresponding
863863
// trait-item and need to map the anchored type accordingly.
@@ -867,9 +867,11 @@ fn render_assoc_item(
867867
ItemType::TyMethod
868868
};
869869

870-
href(did.expect_def_id(), cx)
871-
.map(|p| format!("{}#{}.{}", p.0, ty, name))
872-
.unwrap_or_else(|| format!("#{}.{}", ty, name))
870+
match (href(did.expect_def_id(), cx), ty) {
871+
(Ok(p), ty) => Some(format!("{}#{}.{}", p.0, ty, name)),
872+
(Err(HrefError::DocumentationNotBuilt), ItemType::TyMethod) => None,
873+
(Err(_), ty) => Some(format!("#{}.{}", ty, name)),
874+
}
873875
}
874876
};
875877
let vis = meth.visibility.print_with_space(meth.def_id, cx).to_string();
@@ -904,7 +906,7 @@ fn render_assoc_item(
904906
w.reserve(header_len + "<a href=\"\" class=\"fnname\">{".len() + "</a>".len());
905907
write!(
906908
w,
907-
"{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a href=\"{href}\" class=\"fnname\">{name}</a>\
909+
"{indent}{vis}{constness}{asyncness}{unsafety}{defaultness}{abi}fn <a {href} class=\"fnname\">{name}</a>\
908910
{generics}{decl}{notable_traits}{where_clause}",
909911
indent = indent_str,
910912
vis = vis,
@@ -913,7 +915,8 @@ fn render_assoc_item(
913915
unsafety = unsafety,
914916
defaultness = defaultness,
915917
abi = abi,
916-
href = href,
918+
// links without a href are valid - https://www.w3schools.com/tags/att_a_href.asp
919+
href = href.map(|href| format!("href=\"{}\"", href)).unwrap_or_else(|| "".to_string()),
917920
name = name,
918921
generics = g.print(cx),
919922
decl = d.full_print(header_len, indent, header.asyncness, cx),

Diff for: src/test/rustdoc/auxiliary/issue-86620-1.rs

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#![crate_name = "issue_86620_1"]
2+
3+
pub trait VZip {
4+
fn vzip() -> usize;
5+
}
6+
7+
impl<T> VZip for T {
8+
fn vzip() -> usize {
9+
0
10+
}
11+
}

Diff for: src/test/rustdoc/extern-default-method.rs

+2
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,6 @@
44
extern crate rustdoc_extern_default_method as ext;
55

66
// @count extern_default_method/struct.Struct.html '//*[@id="method.provided"]' 1
7+
// @has extern_default_method/struct.Struct.html '//div[@id="method.provided"]//a[@class="fnname"]/@href' #method.provided
8+
// @has extern_default_method/struct.Struct.html '//div[@id="method.provided"]//a[@class="anchor"]/@href' #method.provided
79
pub use ext::Struct;

Diff for: src/test/rustdoc/issue-86620.rs

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// aux-build:issue-86620-1.rs
2+
3+
extern crate issue_86620_1;
4+
5+
use issue_86620_1::*;
6+
7+
// @!has issue_86620/struct.S.html '//div[@id="method.vzip"]//a[@class="fnname"]/@href' #tymethod.vzip
8+
// @has issue_86620/struct.S.html '//div[@id="method.vzip"]//a[@class="anchor"]/@href' #method.vzip
9+
pub struct S;

0 commit comments

Comments
 (0)