-
Notifications
You must be signed in to change notification settings - Fork 14k
[rustdoc] Fix invalid jump to def macro link generation #148080
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,10 +17,10 @@ use rustc_abi::ExternAbi; | |
| use rustc_ast::join_path_syms; | ||
| use rustc_data_structures::fx::FxHashSet; | ||
| use rustc_hir as hir; | ||
| use rustc_hir::def::DefKind; | ||
| use rustc_hir::def::{DefKind, MacroKinds}; | ||
| use rustc_hir::def_id::{DefId, LOCAL_CRATE}; | ||
| use rustc_hir::{ConstStability, StabilityLevel, StableSince}; | ||
| use rustc_metadata::creader::{CStore, LoadedMacro}; | ||
| use rustc_metadata::creader::CStore; | ||
| use rustc_middle::ty::{self, TyCtxt, TypingMode}; | ||
| use rustc_span::symbol::kw; | ||
| use rustc_span::{Symbol, sym}; | ||
|
|
@@ -349,47 +349,56 @@ pub(crate) enum HrefError { | |
| UnnamableItem, | ||
| } | ||
|
|
||
| /// Type representing information of an `href` attribute. | ||
| pub(crate) struct HrefInfo { | ||
| /// URL to the item page. | ||
| pub(crate) url: String, | ||
| /// Kind of the item (used to generate the `title` attribute). | ||
| pub(crate) kind: ItemType, | ||
| /// Rust path to the item (used to generate the `title` attribute). | ||
| pub(crate) rust_path: Vec<Symbol>, | ||
| } | ||
|
|
||
| /// This function is to get the external macro path because they are not in the cache used in | ||
| /// `href_with_root_path`. | ||
| fn generate_macro_def_id_path( | ||
| def_id: DefId, | ||
| cx: &Context<'_>, | ||
| root_path: Option<&str>, | ||
| ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> { | ||
| ) -> Result<HrefInfo, HrefError> { | ||
| let tcx = cx.tcx(); | ||
| let crate_name = tcx.crate_name(def_id.krate); | ||
| let cache = cx.cache(); | ||
|
|
||
| let fqp = clean::inline::item_relative_path(tcx, def_id); | ||
| let mut relative = fqp.iter().copied(); | ||
| let cstore = CStore::from_tcx(tcx); | ||
| // We need this to prevent a `panic` when this function is used from intra doc links... | ||
| if !cstore.has_crate_data(def_id.krate) { | ||
| debug!("No data for crate {crate_name}"); | ||
| return Err(HrefError::NotInExternalCache); | ||
| } | ||
| // Check to see if it is a macro 2.0 or built-in macro. | ||
| // More information in <https://rust-lang.github.io/rfcs/1584-macros.html>. | ||
| let is_macro_2 = match cstore.load_macro_untracked(def_id, tcx) { | ||
| // If `def.macro_rules` is `true`, then it's not a macro 2.0. | ||
| LoadedMacro::MacroDef { def, .. } => !def.macro_rules, | ||
| _ => false, | ||
| let DefKind::Macro(kinds) = tcx.def_kind(def_id) else { | ||
| unreachable!(); | ||
| }; | ||
|
|
||
| let mut path = if is_macro_2 { | ||
| once(crate_name).chain(relative).collect() | ||
| let item_type = if kinds == MacroKinds::DERIVE { | ||
| ItemType::ProcDerive | ||
| } else if kinds == MacroKinds::ATTR { | ||
| ItemType::ProcAttribute | ||
| } else { | ||
| vec![crate_name, relative.next_back().unwrap()] | ||
| ItemType::Macro | ||
| }; | ||
| let mut path = clean::inline::get_item_path(tcx, def_id, item_type); | ||
| if path.len() < 2 { | ||
| // The minimum we can have is the crate name followed by the macro name. If shorter, then | ||
| // it means that `relative` was empty, which is an error. | ||
| debug!("macro path cannot be empty!"); | ||
| return Err(HrefError::NotInExternalCache); | ||
| } | ||
|
|
||
| if let Some(last) = path.last_mut() { | ||
| *last = Symbol::intern(&format!("macro.{last}.html")); | ||
| // FIXME: Try to use `iter().chain().once()` instead. | ||
| let mut prev = None; | ||
| if let Some(last) = path.pop() { | ||
| path.push(Symbol::intern(&format!("{}.{last}.html", item_type.as_str()))); | ||
| prev = Some(last); | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. maybe a bit excessive, but the clone isn't actually needed since we only need we could do something like no idea if this would be worth it, but it is possible.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is surprisingly complex to do because of |
||
|
|
||
| let url = match cache.extern_locations[&def_id.krate] { | ||
|
|
@@ -410,7 +419,11 @@ fn generate_macro_def_id_path( | |
| return Err(HrefError::NotInExternalCache); | ||
| } | ||
| }; | ||
| Ok((url, ItemType::Macro, fqp)) | ||
| if let Some(prev) = prev { | ||
| path.pop(); | ||
| path.push(prev); | ||
| } | ||
| Ok(HrefInfo { url, kind: item_type, rust_path: path }) | ||
| } | ||
|
|
||
| fn generate_item_def_id_path( | ||
|
|
@@ -419,7 +432,7 @@ fn generate_item_def_id_path( | |
| cx: &Context<'_>, | ||
| root_path: Option<&str>, | ||
| original_def_kind: DefKind, | ||
| ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> { | ||
| ) -> Result<HrefInfo, HrefError> { | ||
| use rustc_middle::traits::ObligationCause; | ||
| use rustc_trait_selection::infer::TyCtxtInferExt; | ||
| use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt; | ||
|
|
@@ -455,7 +468,7 @@ fn generate_item_def_id_path( | |
| let kind = ItemType::from_def_kind(original_def_kind, Some(def_kind)); | ||
| url_parts = format!("{url_parts}#{kind}.{}", tcx.item_name(original_def_id)) | ||
| }; | ||
| Ok((url_parts, shortty, fqp)) | ||
| Ok(HrefInfo { url: url_parts, kind: shortty, rust_path: fqp }) | ||
| } | ||
|
|
||
| /// Checks if the given defid refers to an item that is unnamable, such as one defined in a const block. | ||
|
|
@@ -530,7 +543,7 @@ pub(crate) fn href_with_root_path( | |
| original_did: DefId, | ||
| cx: &Context<'_>, | ||
| root_path: Option<&str>, | ||
| ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> { | ||
| ) -> Result<HrefInfo, HrefError> { | ||
| let tcx = cx.tcx(); | ||
| let def_kind = tcx.def_kind(original_did); | ||
| let did = match def_kind { | ||
|
|
@@ -596,14 +609,14 @@ pub(crate) fn href_with_root_path( | |
| } | ||
| } | ||
| }; | ||
| let url_parts = make_href(root_path, shortty, url_parts, fqp, is_remote); | ||
| Ok((url_parts, shortty, fqp.clone())) | ||
| Ok(HrefInfo { | ||
| url: make_href(root_path, shortty, url_parts, fqp, is_remote), | ||
| kind: shortty, | ||
| rust_path: fqp.clone(), | ||
| }) | ||
| } | ||
|
|
||
| pub(crate) fn href( | ||
| did: DefId, | ||
| cx: &Context<'_>, | ||
| ) -> Result<(String, ItemType, Vec<Symbol>), HrefError> { | ||
| pub(crate) fn href(did: DefId, cx: &Context<'_>) -> Result<HrefInfo, HrefError> { | ||
| href_with_root_path(did, cx, None) | ||
| } | ||
|
|
||
|
|
@@ -690,12 +703,12 @@ fn resolved_path( | |
| } else { | ||
| let path = fmt::from_fn(|f| { | ||
| if use_absolute { | ||
| if let Ok((_, _, fqp)) = href(did, cx) { | ||
| if let Ok(HrefInfo { rust_path, .. }) = href(did, cx) { | ||
| write!( | ||
| f, | ||
| "{path}::{anchor}", | ||
| path = join_path_syms(&fqp[..fqp.len() - 1]), | ||
| anchor = print_anchor(did, *fqp.last().unwrap(), cx) | ||
| path = join_path_syms(&rust_path[..rust_path.len() - 1]), | ||
| anchor = print_anchor(did, *rust_path.last().unwrap(), cx) | ||
| ) | ||
| } else { | ||
| write!(f, "{}", last.name) | ||
|
|
@@ -824,12 +837,11 @@ fn print_higher_ranked_params_with_space( | |
|
|
||
| pub(crate) fn print_anchor(did: DefId, text: Symbol, cx: &Context<'_>) -> impl Display { | ||
| fmt::from_fn(move |f| { | ||
| let parts = href(did, cx); | ||
| if let Ok((url, short_ty, fqp)) = parts { | ||
| if let Ok(HrefInfo { url, kind, rust_path }) = href(did, cx) { | ||
| write!( | ||
| f, | ||
| r#"<a class="{short_ty}" href="{url}" title="{short_ty} {path}">{text}</a>"#, | ||
| path = join_path_syms(fqp), | ||
| r#"<a class="{kind}" href="{url}" title="{kind} {path}">{text}</a>"#, | ||
| path = join_path_syms(rust_path), | ||
| text = EscapeBodyText(text.as_str()), | ||
| ) | ||
| } else { | ||
|
|
@@ -1056,14 +1068,14 @@ fn print_qpath_data(qpath_data: &clean::QPathData, cx: &Context<'_>) -> impl Dis | |
| None => self_type.def_id(cx.cache()).and_then(|did| href(did, cx).ok()), | ||
| }; | ||
|
|
||
| if let Some((url, _, path)) = parent_href { | ||
| if let Some(HrefInfo { url, rust_path, .. }) = parent_href { | ||
| write!( | ||
| f, | ||
| "<a class=\"associatedtype\" href=\"{url}#{shortty}.{name}\" \ | ||
| title=\"type {path}::{name}\">{name}</a>", | ||
| shortty = ItemType::AssocType, | ||
| name = assoc.name, | ||
| path = join_path_syms(path), | ||
| path = join_path_syms(rust_path), | ||
| ) | ||
| } else { | ||
| write!(f, "{}", assoc.name) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,8 +26,9 @@ impl C { | |
| pub fn wat() {} | ||
| } | ||
|
|
||
| //@ has - '//a[@href="{{channel}}/core/fmt/macros/macro.Debug.html"]' 'Debug' | ||
| //@ has - '//a[@href="{{channel}}/core/cmp/macro.PartialEq.html"]' 'PartialEq' | ||
| // These two links must not change and in particular must contain `/derive.`! | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why must they not change? Seems like an odd thing to say without explanation considering this PR is changing them.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Because they are valid as is and since it's derive macros, "derive" must be in the URL.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I mean, they're obviously the best thing to do currently, but that's the case for most things in tests, "must not" seems a bit strong for "this is the current best" Also, does changing this break any existing links to these pages? It doesn't look like there are redirects. |
||
| //@ has - '//a[@href="{{channel}}/core/fmt/macros/derive.Debug.html"]' 'Debug' | ||
| //@ has - '//a[@href="{{channel}}/core/cmp/derive.PartialEq.html"]' 'PartialEq' | ||
| #[derive(Debug, PartialEq)] | ||
| pub struct Bar; | ||
| impl Trait for Bar { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| // This test ensures that the same link is generated in both intra-doc links | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please put this file in the existing Also, I'm slightly confused as to how this test works, and what it's testing, as the PR description says "I realized that when there was no intra-doc link linking to the same item, then the generated link for macros in jump to def would be invalid.", but that's not what's happening here, and trying to run this test against current nightly actually results in an ICE, not an invalid link.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Well, there is no intra-doc link linking to Also, that might be a newer change because originally, it didn't ICE but generated invalid links.
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do you mean "there's no intra-doc link linking to Debug and PartialEq in core"? Because line 10 and 11 literally test that a link exists. Or are you not counting those as intra-doc because they aren't written as a doc comment? If that's the case, you should probably remove the comment on line 9 that describes them as doc comments.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Arf, I'm so bad at explaining. So: //! [PartialEq] [Debug]
#[derive(Debug, PartialEq)]
pub struct Foo;Before this PR, if the
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, that makes sense, it's just that the PR description and the code comments in the test have conflicting definitions of "intra-doc link", which was very confusing at first. |
||
| // and in jump to def links. | ||
|
|
||
| //@ compile-flags: -Zunstable-options --generate-link-to-definition | ||
|
|
||
| #![crate_name = "foo"] | ||
|
|
||
| // First we check intra-doc links. | ||
| //@ has 'foo/struct.Bar.html' | ||
| //@ has - '//a[@href="{{channel}}/core/fmt/macros/derive.Debug.html"]' 'Debug' | ||
| //@ has - '//a[@href="{{channel}}/core/cmp/derive.PartialEq.html"]' 'PartialEq' | ||
|
|
||
| // We also check the "title" attributes. | ||
| //@ has - '//a[@href="{{channel}}/core/fmt/macros/derive.Debug.html"]/@title' 'derive core::fmt::macros::Debug' | ||
| //@ has - '//a[@href="{{channel}}/core/cmp/derive.PartialEq.html"]/@title' 'derive core::cmp::PartialEq' | ||
|
|
||
| // Then we check that they are the same in jump to def. | ||
|
|
||
| /// [Debug][derive@Debug] and [PartialEq][derive@PartialEq] | ||
| //@ has 'src/foo/derive-macro.rs.html' | ||
| //@ has - '//a[@href="{{channel}}/core/fmt/macros/derive.Debug.html"]' 'Debug' | ||
| //@ has - '//a[@href="{{channel}}/core/cmp/derive.PartialEq.html"]' 'PartialEq' | ||
| #[derive(Debug, PartialEq)] | ||
| pub struct Bar; | ||
Uh oh!
There was an error while loading. Please reload this page.