Fix intra doc link resolution when a doc comment is composed of both inner and outer doc comment

This commit is contained in:
Guillaume Gomez
2026-09-16 20:34:55 +02:00
parent 51c768aa5c
commit 2e58a77da4
8 changed files with 132 additions and 50 deletions

View File

@@ -12,6 +12,7 @@ use std::debug_assert_matches;
use std::mem::{replace, swap, take};
use std::ops::{ControlFlow, Range};
use rustc_ast::attr::AttributeExt;
use rustc_ast::visit::{
AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, try_visit, visit_opt, walk_list,
};
@@ -2860,10 +2861,22 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
}
fn resolve_item(&mut self, item: &'ast Item) {
let mod_inner_docs =
matches!(item.kind, ItemKind::Mod(..)) && rustdoc::inner_docs(&item.attrs);
if !mod_inner_docs && !matches!(item.kind, ItemKind::Impl(..) | ItemKind::Use(..)) {
self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
match item.kind {
ItemKind::Mod(..) => {
// We only handle outer doc comments for modules here.
let attrs = if let Some(pos) = item.attrs.iter().position(|a| {
a.doc_resolution_scope().is_some_and(|style| style == AttrStyle::Inner)
}) {
&item.attrs[..pos]
} else {
&item.attrs
};
self.resolve_doc_links(attrs, MaybeExported::Ok(item.id));
}
ItemKind::Impl(..) | ItemKind::Use(..) => {}
_ => {
self.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
}
}
debug!("(resolving item) resolving {:?} ({:?})", item.kind.ident(), item.kind);
@@ -2957,9 +2970,16 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
let orig_module = replace(&mut self.parent_scope.module, module);
self.with_rib(ValueNS, RibKind::Module(module.expect_local()), |this| {
this.with_rib(TypeNS, RibKind::Module(module.expect_local()), |this| {
if mod_inner_docs {
this.resolve_doc_links(&item.attrs, MaybeExported::Ok(item.id));
}
// Outer doc comments were already handled above, now we handle
// inner doc comments.
let attrs = if let Some(pos) = item.attrs.iter().position(|a| {
a.doc_resolution_scope().is_some_and(|style| style == AttrStyle::Inner)
}) {
&item.attrs[pos..]
} else {
&[]
};
this.resolve_doc_links(attrs, MaybeExported::Ok(item.id));
let old_macro_rules = this.parent_scope.macro_rules;
visit::walk_item(this, item);
// Maintain macro_rules scopes in the same way as during early resolution

View File

@@ -9,9 +9,9 @@ use pulldown_cmark::{
};
use rustc_ast as ast;
use rustc_ast::attr::AttributeExt;
use rustc_ast::join_path_syms;
use rustc_ast::token::DocFragmentKind;
use rustc_ast::util::comments::beautify_doc_string;
use rustc_ast::{AttrStyle, join_path_syms};
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::unord::UnordSet;
use rustc_middle::ty::TyCtxt;
@@ -48,6 +48,7 @@ pub struct DocFragment {
/// Because we tamper with the spans context, this information cannot be correctly retrieved
/// later on. So instead, we compute it and store it here.
pub from_expansion: bool,
pub style: AttrStyle,
}
#[derive(Clone, Copy, Debug)]
@@ -215,8 +216,15 @@ pub fn attrs_to_doc_fragments<'a, A: AttributeExt + Clone + 'a>(
(value_span.with_ctxt(attr_span.ctxt()), value_span.from_expansion())
}
};
let fragment =
DocFragment { span, doc, kind: fragment_kind, item_id, indent: 0, from_expansion };
let fragment = DocFragment {
span,
doc,
kind: fragment_kind,
item_id,
indent: 0,
from_expansion,
style: attr.doc_resolution_scope().unwrap(),
};
doc_fragments.push(fragment);
} else if !doc_only {
other_attrs.push(attr.clone());
@@ -231,6 +239,14 @@ pub fn attrs_to_doc_fragments<'a, A: AttributeExt + Clone + 'a>(
(doc_fragments, other_attrs)
}
/// Represents a doc comment, split in two parts, outer and inner attributes. It's needed for
/// the intra-doc link resolution context.
#[derive(Default)]
pub struct DocStrings {
pub outer: String,
pub inner: String,
}
/// Return the doc-comments on this item, grouped by the module they came from.
/// The module can be different if this is a re-export with added documentation.
///
@@ -238,11 +254,16 @@ pub fn attrs_to_doc_fragments<'a, A: AttributeExt + Clone + 'a>(
/// early and late doc link resolution regardless of their position.
pub fn prepare_to_doc_link_resolution(
doc_fragments: &[DocFragment],
) -> FxIndexMap<Option<DefId>, String> {
let mut res = FxIndexMap::default();
) -> FxIndexMap<Option<DefId>, DocStrings> {
let mut res: FxIndexMap<Option<DefId>, DocStrings> = FxIndexMap::default();
for fragment in doc_fragments {
let out_str = res.entry(fragment.item_id).or_default();
add_doc_fragment(out_str, fragment);
let out_strs = res.entry(fragment.item_id).or_default();
let out = if fragment.style == AttrStyle::Inner {
&mut out_strs.inner
} else {
&mut out_strs.outer
};
add_doc_fragment(out, fragment);
}
res
}
@@ -351,19 +372,6 @@ pub fn strip_generics_from_path(path_str: &str) -> Result<Box<str>, MalformedGen
}
}
/// Returns whether the first doc-comment is an inner attribute.
///
/// If there are no doc-comments, return true.
/// FIXME(#78591): Support both inner and outer attributes on the same item.
pub fn inner_docs(attrs: &[impl AttributeExt]) -> bool {
for attr in attrs {
if let Some(attr_style) = attr.doc_resolution_scope() {
return attr_style == ast::AttrStyle::Inner;
}
}
true
}
/// Has `#[rustc_doc_primitive]` or `#[doc(keyword)]` or `#[doc(attribute)]`.
pub fn has_primitive_or_keyword_or_attribute_docs(attrs: &[impl AttributeExt]) -> bool {
for attr in attrs {
@@ -413,7 +421,10 @@ pub(crate) fn attrs_to_preprocessed_links(attrs: &[ast::Attribute]) -> Vec<Box<s
let (doc_fragments, other_attrs) =
attrs_to_doc_fragments(attrs.iter().map(|attr| (attr, None)), false);
let doc = prepare_to_doc_link_resolution(&doc_fragments).into_values().next();
let mut links = doc.as_deref().map(parse_links).unwrap_or_default();
let mut links = doc
.as_ref()
.map(|doc| parse_links(&format!("{}{}", doc.outer, doc.inner)))
.unwrap_or_default();
for attr in other_attrs {
if let Some(note) = attr.deprecation_note() {

View File

@@ -1,5 +1,6 @@
use std::path::PathBuf;
use rustc_ast::AttrStyle;
use rustc_span::source_map::{FilePathMapping, SourceMap};
use rustc_span::symbol::sym;
use rustc_span::{BytePos, DUMMY_SP, FileName, Span};
@@ -25,6 +26,7 @@ fn single_backtick() {
doc: sym::empty, // unused placeholder
indent: 0,
from_expansion: false,
style: AttrStyle::Outer,
}],
)
.unwrap();
@@ -48,6 +50,7 @@ fn utf8() {
doc: sym::empty, // unused placeholder
indent: 0,
from_expansion: false,
style: AttrStyle::Outer,
}],
)
.unwrap();

View File

@@ -24,7 +24,7 @@ use rustc_metadata::rendered_const;
use rustc_middle::ty::fast_reject::SimplifiedType;
use rustc_middle::ty::{self, Ty, TyCtxt, Visibility};
use rustc_resolve::rustdoc::{
DocFragment, add_doc_fragment, attrs_to_doc_fragments, inner_docs, span_of_fragments,
DocFragment, add_doc_fragment, attrs_to_doc_fragments, span_of_fragments,
};
use rustc_session::Session;
use rustc_span::def_id::{CRATE_DEF_ID, ModId};
@@ -461,13 +461,15 @@ impl Item {
}
pub(crate) fn inner_docs(&self, tcx: TyCtxt<'_>) -> bool {
use rustc_ast::attr::AttributeExt;
self.item_id
.as_def_id()
.map(|did| {
inner_docs(
#[allow(deprecated)]
tcx.get_all_attrs(did),
)
#[allow(deprecated)]
tcx.get_all_attrs(did).iter().any(|attr| {
attr.doc_resolution_scope().is_some_and(|style| style == ast::AttrStyle::Inner)
})
})
.unwrap_or(false)
}

View File

@@ -12,6 +12,7 @@ fn create_doc_fragment(s: &str) -> Vec<DocFragment> {
kind: DocFragmentKind::Sugared(CommentKind::Line),
indent: 0,
from_expansion: false,
style: rustc_ast::AttrStyle::Outer,
}]
}

View File

@@ -21,8 +21,8 @@ use rustc_middle::ty;
use rustc_middle::ty::{Ty, TyCtxt};
use rustc_resolve::rustdoc::pulldown_cmark::LinkType;
use rustc_resolve::rustdoc::{
MalformedGenerics, has_primitive_or_keyword_or_attribute_docs, prepare_to_doc_link_resolution,
source_span_for_markdown_range, strip_generics_from_path,
DocStrings, MalformedGenerics, has_primitive_or_keyword_or_attribute_docs,
prepare_to_doc_link_resolution, source_span_for_markdown_range, strip_generics_from_path,
};
use rustc_span::def_id::ModId;
use rustc_span::edit_distance::find_best_match_for_name;
@@ -1091,14 +1091,7 @@ impl LinkCollector<'_, '_> {
return;
}
let mut try_insert_links = |item_id, doc: &str| {
if should_skip_link_resolution(item_id) {
return;
}
let module_id = match tcx.def_kind(item_id) {
DefKind::Mod if item.inner_docs(tcx) => ModId::new_unchecked(item_id),
_ => find_nearest_parent_module(tcx, item_id).unwrap(),
};
let mut try_insert_links_inner = |item_id, module_id, doc: &str| {
for md_link in preprocessed_markdown_links(&doc) {
let link = self.resolve_link(&doc, item, item_id, module_id, &md_link);
if let Some(link) = link {
@@ -1112,16 +1105,45 @@ impl LinkCollector<'_, '_> {
}
};
let mut try_insert_links = |item_id, docs: &DocStrings| {
if should_skip_link_resolution(item_id) {
return;
}
match tcx.def_kind(item_id) {
DefKind::Mod => {
if !docs.outer.is_empty() {
try_insert_links_inner(
item_id,
find_nearest_parent_module(tcx, item_id).unwrap(),
&docs.outer,
);
}
if !docs.inner.is_empty() {
try_insert_links_inner(item_id, ModId::new_unchecked(item_id), &docs.inner);
}
}
_ => {
// It's the same handling for non-module items.
let module_id = find_nearest_parent_module(tcx, item_id).unwrap();
try_insert_links_inner(
item_id,
module_id,
&format!("{}{}", docs.outer, docs.inner),
);
}
}
};
// We want to resolve in the lexical scope of the documentation.
// In the presence of re-exports, this is not the same as the module of the item.
// Rather than merging all documentation into one, resolve it one attribute at a time
// so we know which module it came from.
for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
if !may_have_doc_links(&doc) {
if !may_have_doc_links(&doc.inner) && !may_have_doc_links(&doc.outer) {
continue;
}
debug!("combined_docs={doc}");
debug!("combined_docs=outer: {} inner: {}", doc.outer, doc.inner);
// NOTE: if there are links that start in one crate and end in another, this will not resolve them.
// This is a degenerate case and it's not supported by rustdoc.
let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
@@ -1163,7 +1185,7 @@ impl LinkCollector<'_, '_> {
} else {
item.item_id.expect_def_id()
};
try_insert_links(item_id, note)
try_insert_links(item_id, &DocStrings { outer: note.to_owned(), inner: String::new() });
}
}

View File

@@ -30,10 +30,11 @@ struct LinkData {
pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item, hir_id: HirId) {
let hunks = prepare_to_doc_link_resolution(&item.attrs.doc_strings);
for (item_id, doc) in hunks {
if let Some(item_id) = item_id.or(item.def_id())
&& !doc.is_empty()
{
check_redundant_explicit_link_for_did(cx, item, item_id, hir_id, &doc);
if let Some(item_id) = item_id.or(item.def_id()) {
if !doc.outer.is_empty() || !doc.inner.is_empty() {
let doc = format!("{}{}", doc.outer, doc.inner);
check_redundant_explicit_link_for_did(cx, item, item_id, hir_id, &doc);
}
}
}
}

View File

@@ -0,0 +1,22 @@
// This test ensures that when a documentation is composed of both inner and outer
// doc comments, the intra-doc link resolution still works as expected.
// Regression test for <https://github.com/rust-lang/rust/issues/78591>.
// Regression test for <https://github.com/rust-lang/rust/issues/119965>.
// Regression test for <https://github.com/rust-lang/rust/issues/134904>.
#![crate_name = "foo"]
#![deny(rustdoc::broken_intra_doc_links)]
//@ has foo/demo/index.html
//@ has - '//a[@href="../struct.Foo.html"]' 'Foo'
//@ has - '//a[@href="struct.DemoStruct.html"]' 'DemoStruct'
/// Outer doc-comment [`Foo`].
pub mod demo {
//!
//! Inner doc-comment with link: [`DemoStruct`]
pub struct DemoStruct;
}
pub struct Foo;