1 //! This module implements [RFC 1946]: Intra-rustdoc-links
3 //! [RFC 1946]: https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md
5 use pulldown_cmark::LinkType;
6 use rustc_ast::util::comments::may_have_doc_links;
7 use rustc_data_structures::{fx::FxHashMap, intern::Interned, stable_set::FxHashSet};
8 use rustc_errors::{Applicability, Diagnostic};
9 use rustc_hir::def::Namespace::*;
10 use rustc_hir::def::{DefKind, Namespace, PerNS};
11 use rustc_hir::def_id::{DefId, CRATE_DEF_ID};
12 use rustc_hir::Mutability;
13 use rustc_middle::ty::{DefIdTree, Ty, TyCtxt};
14 use rustc_middle::{bug, ty};
15 use rustc_resolve::ParentScope;
16 use rustc_session::lint::Lint;
17 use rustc_span::hygiene::MacroKind;
18 use rustc_span::symbol::{sym, Ident, Symbol};
19 use rustc_span::BytePos;
20 use smallvec::{smallvec, SmallVec};
27 use crate::clean::{self, utils::find_nearest_parent_module};
28 use crate::clean::{Crate, Item, ItemId, ItemLink, PrimitiveType};
29 use crate::core::DocContext;
30 use crate::html::markdown::{markdown_links, MarkdownLink};
31 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
32 use crate::passes::Pass;
33 use crate::visit::DocVisitor;
36 crate use early::early_resolve_intra_doc_links;
38 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
39 name: "collect-intra-doc-links",
40 run: collect_intra_doc_links,
41 description: "resolves intra-doc links",
44 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
46 LinkCollector { cx, mod_ids: Vec::new(), visited_links: FxHashMap::default() };
47 collector.visit_crate(&krate);
51 #[derive(Copy, Clone, Debug, Hash)]
54 Primitive(PrimitiveType),
57 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
60 fn descr(self) -> &'static str {
62 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
63 Res::Primitive(_) => "builtin type",
67 fn article(self) -> &'static str {
69 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
70 Res::Primitive(_) => "a",
74 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
76 Res::Def(_, id) => tcx.item_name(id),
77 Res::Primitive(prim) => prim.as_sym(),
81 fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
83 Res::Def(_, id) => id,
84 Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
88 fn from_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Res {
89 Res::Def(tcx.def_kind(def_id), def_id)
92 /// Used for error reporting.
93 fn disambiguator_suggestion(self) -> Suggestion {
94 let kind = match self {
95 Res::Primitive(_) => return Suggestion::Prefix("prim"),
96 Res::Def(kind, _) => kind,
98 if kind == DefKind::Macro(MacroKind::Bang) {
99 return Suggestion::Macro;
100 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
101 return Suggestion::Function;
102 } else if kind == DefKind::Field {
103 return Suggestion::RemoveDisambiguator;
106 let prefix = match kind {
107 DefKind::Struct => "struct",
108 DefKind::Enum => "enum",
109 DefKind::Trait => "trait",
110 DefKind::Union => "union",
111 DefKind::Mod => "mod",
112 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
115 DefKind::Static(_) => "static",
116 DefKind::Macro(MacroKind::Derive) => "derive",
117 // Now handle things that don't have a specific disambiguator
120 .expect("tried to calculate a disambiguator for a def without a namespace?")
122 Namespace::TypeNS => "type",
123 Namespace::ValueNS => "value",
124 Namespace::MacroNS => "macro",
128 Suggestion::Prefix(prefix)
132 impl TryFrom<ResolveRes> for Res {
135 fn try_from(res: ResolveRes) -> Result<Self, ()> {
136 use rustc_hir::def::Res::*;
138 Def(kind, id) => Ok(Res::Def(kind, id)),
139 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
141 NonMacroAttr(..) | Err => Result::Err(()),
142 other => bug!("unrecognized res {:?}", other),
147 /// The link failed to resolve. [`resolution_failure`] should look to see if there's
148 /// a more helpful error that can be given.
150 struct UnresolvedPath<'a> {
151 /// Item on which the link is resolved, used for resolving `Self`.
153 /// The scope the link was resolved in.
155 /// If part of the link resolved, this has the `Res`.
157 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
158 partial_res: Option<Res>,
159 /// The remaining unresolved path segments.
161 /// In `[std::io::Error::x]`, `x` would be unresolved.
162 unresolved: Cow<'a, str>,
166 enum ResolutionFailure<'a> {
167 /// This resolved, but with the wrong namespace.
169 /// What the link resolved to.
171 /// The expected namespace for the resolution, determined from the link's disambiguator.
173 /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
174 /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
175 expected_ns: Namespace,
177 NotResolved(UnresolvedPath<'a>),
180 #[derive(Clone, Copy, Debug)]
181 enum MalformedGenerics {
182 /// This link has unbalanced angle brackets.
184 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
185 UnbalancedAngleBrackets,
186 /// The generics are not attached to a type.
188 /// For example, `<T>` should trigger this.
190 /// This is detected by checking if the path is empty after the generics are stripped.
192 /// The link uses fully-qualified syntax, which is currently unsupported.
194 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
196 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
198 HasFullyQualifiedSyntax,
199 /// The link has an invalid path separator.
201 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
202 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
205 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
206 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
207 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
209 /// This is detected by checking if there is a colon followed by a non-colon in the link.
210 InvalidPathSeparator,
211 /// The link has too many angle brackets.
213 /// For example, `Vec<<T>>` should trigger this.
214 TooManyAngleBrackets,
215 /// The link has empty angle brackets.
217 /// For example, `Vec<>` should trigger this.
221 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
222 crate enum UrlFragment {
228 /// Render the fragment, including the leading `#`.
229 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
231 UrlFragment::Item(frag) => frag.render(s, tcx),
232 UrlFragment::UserWritten(raw) => write!(s, "#{}", raw),
237 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
238 crate struct ItemFragment(FragmentKind, DefId);
240 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
241 crate enum FragmentKind {
253 fn from_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> FragmentKind {
254 match tcx.def_kind(def_id) {
255 DefKind::AssocFn => {
256 if tcx.associated_item(def_id).defaultness.has_value() {
259 FragmentKind::TyMethod
262 DefKind::AssocConst => FragmentKind::AssociatedConstant,
263 DefKind::AssocTy => FragmentKind::AssociatedType,
264 DefKind::Variant => FragmentKind::Variant,
266 if tcx.def_kind(tcx.parent(def_id).unwrap()) == DefKind::Variant {
267 FragmentKind::VariantField
269 FragmentKind::StructField
272 kind => bug!("unexpected associated item kind: {:?}", kind),
278 /// Render the fragment, including the leading `#`.
279 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
282 ItemFragment(kind, def_id) => {
283 let name = tcx.item_name(def_id);
285 FragmentKind::Method => write!(s, "method.{}", name),
286 FragmentKind::TyMethod => write!(s, "tymethod.{}", name),
287 FragmentKind::AssociatedConstant => write!(s, "associatedconstant.{}", name),
288 FragmentKind::AssociatedType => write!(s, "associatedtype.{}", name),
289 FragmentKind::StructField => write!(s, "structfield.{}", name),
290 FragmentKind::Variant => write!(s, "variant.{}", name),
291 FragmentKind::VariantField => {
292 let variant = tcx.item_name(tcx.parent(def_id));
293 write!(s, "variant.{}.field.{}", variant, name)
301 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
302 struct ResolutionInfo {
305 dis: Option<Disambiguator>,
307 extra_fragment: Option<String>,
311 struct DiagnosticInfo<'a> {
315 link_range: Range<usize>,
318 #[derive(Clone, Debug, Hash)]
320 res: (Res, Option<UrlFragment>),
323 struct LinkCollector<'a, 'tcx> {
324 cx: &'a mut DocContext<'tcx>,
325 /// A stack of modules used to decide what scope to resolve in.
327 /// The last module will be used if the parent scope of the current item is
330 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
331 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
332 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
335 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
336 /// Given a full link, parse it as an [enum struct variant].
338 /// In particular, this will return an error whenever there aren't three
339 /// full path segments left in the link.
341 /// [enum struct variant]: rustc_hir::VariantData::Struct
342 fn variant_field<'path>(
344 path_str: &'path str,
347 ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
348 let tcx = self.cx.tcx;
349 let no_res = || UnresolvedPath {
353 unresolved: path_str.into(),
356 debug!("looking for enum variant {}", path_str);
357 let mut split = path_str.rsplitn(3, "::");
358 let variant_field_name = split
360 .map(|f| Symbol::intern(f))
361 .expect("fold_item should ensure link is non-empty");
363 // we're not sure this is a variant at all, so use the full string
364 // If there's no second component, the link looks like `[path]`.
365 // So there's no partial res and we should say the whole link failed to resolve.
366 split.next().map(|f| Symbol::intern(f)).ok_or_else(no_res)?;
369 .map(|f| f.to_owned())
370 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
371 // So there's no partial res.
372 .ok_or_else(no_res)?;
373 let ty_res = self.resolve_path(&path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
376 Res::Def(DefKind::Enum, did) => match tcx.type_of(did).kind() {
377 ty::Adt(def, _) if def.is_enum() => {
378 if let Some(field) = def.all_fields().find(|f| f.name == variant_field_name) {
379 Ok((ty_res, field.did))
384 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
385 unresolved: variant_field_name.to_string().into(),
391 _ => Err(UnresolvedPath {
394 partial_res: Some(ty_res),
395 unresolved: variant_name.to_string().into(),
400 /// Given a primitive type, try to resolve an associated item.
401 fn resolve_primitive_associated_item(
403 prim_ty: PrimitiveType,
406 ) -> Option<(Res, DefId)> {
407 let tcx = self.cx.tcx;
409 prim_ty.impls(tcx).find_map(|impl_| {
410 tcx.associated_items(impl_)
411 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
412 .map(|item| (Res::Primitive(prim_ty), item.def_id))
416 fn resolve_self_ty(&self, path_str: &str, ns: Namespace, item_id: ItemId) -> Option<Res> {
417 if ns != TypeNS || path_str != "Self" {
421 let tcx = self.cx.tcx;
424 .map(|def_id| match tcx.def_kind(def_id) {
425 def_kind @ (DefKind::AssocFn
426 | DefKind::AssocConst
429 | DefKind::Field) => {
430 let parent_def_id = tcx.parent(def_id);
431 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant
433 tcx.parent(parent_def_id)
440 .and_then(|self_id| match tcx.def_kind(self_id) {
441 DefKind::Impl => self.def_id_to_res(self_id),
442 def_kind => Some(Res::Def(def_kind, self_id)),
446 /// HACK: Try to search the macro name in the list of all `macro_rules` items in the crate.
447 /// Used when nothing else works, may often give an incorrect result.
448 fn resolve_macro_rules(&self, path_str: &str, ns: Namespace) -> Option<Res> {
456 .get(&Symbol::intern(path_str))
458 .and_then(|res| res.try_into().ok())
461 /// Convenience wrapper around `resolve_rustdoc_path`.
463 /// This also handles resolving `true` and `false` as booleans.
464 /// NOTE: `resolve_rustdoc_path` knows only about paths, not about types.
465 /// Associated items will never be resolved by this function.
473 if let res @ Some(..) = self.resolve_self_ty(path_str, ns, item_id) {
477 // Resolver doesn't know about true, false, and types that aren't paths (e.g. `()`).
481 .doc_link_resolutions
482 .get(&(Symbol::intern(path_str), ns, module_id))
485 self.cx.enter_resolver(|resolver| {
487 ParentScope::module(resolver.expect_module(module_id), resolver);
488 resolver.resolve_rustdoc_path(path_str, ns, parent_scope)
491 .and_then(|res| res.try_into().ok())
492 .or_else(|| resolve_primitive(path_str, ns))
493 .or_else(|| self.resolve_macro_rules(path_str, ns));
494 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
498 /// Resolves a string as a path within a particular namespace. Returns an
499 /// optional URL fragment in the case of variants and methods.
502 path_str: &'path str,
506 ) -> Result<(Res, Option<DefId>), UnresolvedPath<'path>> {
507 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
508 return Ok(match res {
510 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Variant,
513 let parent_def_id = self.cx.tcx.parent(def_id).unwrap();
514 (Res::from_def_id(self.cx.tcx, parent_def_id), Some(def_id))
518 } else if ns == MacroNS {
519 return Err(UnresolvedPath {
523 unresolved: path_str.into(),
527 // Try looking for methods and associated items.
528 let mut split = path_str.rsplitn(2, "::");
529 // NB: `split`'s first element is always defined, even if the delimiter was not present.
530 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
531 let item_str = split.next().unwrap();
532 let item_name = Symbol::intern(item_str);
533 let path_root = split
535 .map(|f| f.to_owned())
536 // If there's no `::`, it's not an associated item.
537 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
539 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
544 unresolved: item_str.into(),
548 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
549 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
550 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
552 resolve_primitive(&path_root, TypeNS)
553 .or_else(|| self.resolve_path(&path_root, TypeNS, item_id, module_id))
555 self.resolve_associated_item(ty_res, item_name, ns, module_id).map(Ok)
558 if ns == Namespace::ValueNS {
559 self.variant_field(path_str, item_id, module_id)
565 unresolved: path_root.into(),
569 .map(|(res, def_id)| (res, Some(def_id)))
572 /// Convert a DefId to a Res, where possible.
574 /// This is used for resolving type aliases.
575 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
576 use PrimitiveType::*;
577 Some(match *self.cx.tcx.type_of(ty_id).kind() {
578 ty::Bool => Res::Primitive(Bool),
579 ty::Char => Res::Primitive(Char),
580 ty::Int(ity) => Res::Primitive(ity.into()),
581 ty::Uint(uty) => Res::Primitive(uty.into()),
582 ty::Float(fty) => Res::Primitive(fty.into()),
583 ty::Str => Res::Primitive(Str),
584 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
585 ty::Tuple(_) => Res::Primitive(Tuple),
586 ty::Array(..) => Res::Primitive(Array),
587 ty::Slice(_) => Res::Primitive(Slice),
588 ty::RawPtr(_) => Res::Primitive(RawPointer),
589 ty::Ref(..) => Res::Primitive(Reference),
590 ty::FnDef(..) => panic!("type alias to a function definition"),
591 ty::FnPtr(_) => Res::Primitive(Fn),
592 ty::Never => Res::Primitive(Never),
593 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
594 Res::from_def_id(self.cx.tcx, did)
599 | ty::GeneratorWitness(_)
606 | ty::Error(_) => return None,
610 /// Convert a PrimitiveType to a Ty, where possible.
612 /// This is used for resolving trait impls for primitives
613 fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
614 use PrimitiveType::*;
615 let tcx = self.cx.tcx;
617 // FIXME: Only simple types are supported here, see if we can support
618 // other types such as Tuple, Array, Slice, etc.
619 // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
620 Some(tcx.mk_ty(match prim {
625 I8 => ty::Int(ty::IntTy::I8),
626 I16 => ty::Int(ty::IntTy::I16),
627 I32 => ty::Int(ty::IntTy::I32),
628 I64 => ty::Int(ty::IntTy::I64),
629 I128 => ty::Int(ty::IntTy::I128),
630 Isize => ty::Int(ty::IntTy::Isize),
631 F32 => ty::Float(ty::FloatTy::F32),
632 F64 => ty::Float(ty::FloatTy::F64),
633 U8 => ty::Uint(ty::UintTy::U8),
634 U16 => ty::Uint(ty::UintTy::U16),
635 U32 => ty::Uint(ty::UintTy::U32),
636 U64 => ty::Uint(ty::UintTy::U64),
637 U128 => ty::Uint(ty::UintTy::U128),
638 Usize => ty::Uint(ty::UintTy::Usize),
643 /// Resolve an associated item, returning its containing page's `Res`
644 /// and the fragment targeting the associated item on its page.
645 fn resolve_associated_item(
651 ) -> Option<(Res, DefId)> {
652 let tcx = self.cx.tcx;
655 Res::Primitive(prim) => {
656 self.resolve_primitive_associated_item(prim, ns, item_name).or_else(|| {
657 self.primitive_type_to_ty(prim)
659 resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
662 .map(|item| (root_res, item.def_id))
665 Res::Def(DefKind::TyAlias, did) => {
666 // Resolve the link on the type the alias points to.
667 // FIXME: if the associated item is defined directly on the type alias,
668 // it will show up on its documentation page, we should link there instead.
669 let res = self.def_id_to_res(did)?;
670 self.resolve_associated_item(res, item_name, ns, module_id)
673 def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
676 debug!("looking for associated item named {} for item {:?}", item_name, did);
677 // Checks if item_name is a variant of the `SomeItem` enum
678 if ns == TypeNS && def_kind == DefKind::Enum {
679 match tcx.type_of(did).kind() {
680 ty::Adt(adt_def, _) => {
681 for variant in adt_def.variants() {
682 if variant.name == item_name {
683 return Some((root_res, variant.def_id));
691 // Checks if item_name belongs to `impl SomeItem`
696 tcx.associated_items(imp).find_by_name_and_namespace(
698 Ident::with_dummy_span(item_name),
704 // There should only ever be one associated item that matches from any inherent impl
706 // Check if item_name belongs to `impl SomeTrait for SomeItem`
707 // FIXME(#74563): This gives precedence to `impl SomeItem`:
708 // Although having both would be ambiguous, use impl version for compatibility's sake.
709 // To handle that properly resolve() would have to support
710 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
712 resolve_associated_trait_item(
721 debug!("got associated item {:?}", assoc_item);
723 if let Some(item) = assoc_item {
724 return Some((root_res, item.def_id));
727 if ns != Namespace::ValueNS {
730 debug!("looking for fields named {} for {:?}", item_name, did);
731 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
732 // NOTE: it's different from variant_field because it only resolves struct fields,
733 // not variant fields (2 path segments, not 3).
735 // We need to handle struct (and union) fields in this code because
736 // syntactically their paths are identical to associated item paths:
737 // `module::Type::field` and `module::Type::Assoc`.
739 // On the other hand, variant fields can't be mistaken for associated
740 // items because they look like this: `module::Type::Variant::field`.
742 // Variants themselves don't need to be handled here, even though
743 // they also look like associated items (`module::Type::Variant`),
744 // because they are real Rust syntax (unlike the intra-doc links
745 // field syntax) and are handled by the compiler's resolver.
746 let def = match tcx.type_of(did).kind() {
747 ty::Adt(def, _) if !def.is_enum() => def,
751 def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?;
752 Some((root_res, field.did))
754 Res::Def(DefKind::Trait, did) => tcx
755 .associated_items(did)
756 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
758 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
766 fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
767 assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
770 /// Look to see if a resolved item has an associated item named `item_name`.
772 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
773 /// find `std::error::Error::source` and return
774 /// `<io::Error as error::Error>::source`.
775 fn resolve_associated_trait_item<'a>(
780 cx: &mut DocContext<'a>,
781 ) -> Option<ty::AssocItem> {
782 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
783 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
784 // meantime, just don't look for these blanket impls.
786 // Next consider explicit impls: `impl MyTrait for MyType`
787 // Give precedence to inherent impls.
788 let traits = trait_impls_for(cx, ty, module);
789 debug!("considering traits {:?}", traits);
790 let mut candidates = traits.iter().filter_map(|&(impl_, trait_)| {
792 .associated_items(trait_)
793 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
795 trait_assoc_to_impl_assoc_item(cx.tcx, impl_, trait_assoc.def_id)
796 .unwrap_or(trait_assoc)
799 // FIXME(#74563): warn about ambiguity
800 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
801 candidates.next().copied()
804 /// Find the associated item in the impl `impl_id` that corresponds to the
805 /// trait associated item `trait_assoc_id`.
807 /// This function returns `None` if no associated item was found in the impl.
808 /// This can occur when the trait associated item has a default value that is
809 /// not overridden in the impl.
811 /// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
812 /// [`TyCtxt::associated_item()`] (with some helpful logging added).
813 #[instrument(level = "debug", skip(tcx))]
814 fn trait_assoc_to_impl_assoc_item<'tcx>(
817 trait_assoc_id: DefId,
818 ) -> Option<&'tcx ty::AssocItem> {
819 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
820 debug!(?trait_to_impl_assoc_map);
821 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
822 debug!(?impl_assoc_id);
823 let impl_assoc = tcx.associated_item(impl_assoc_id);
828 /// Given a type, return all trait impls in scope in `module` for that type.
829 /// Returns a set of pairs of `(impl_id, trait_id)`.
831 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
832 /// So it is not stable to serialize cross-crate.
833 #[instrument(level = "debug", skip(cx))]
834 fn trait_impls_for<'a>(
835 cx: &mut DocContext<'a>,
838 ) -> FxHashSet<(DefId, DefId)> {
840 let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
841 let trait_ = trait_candidate.def_id;
842 trace!("considering explicit impl for trait {:?}", trait_);
844 // Look at each trait implementation to see if it's an impl for `did`
845 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
846 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
847 // Check if these are the same type.
848 let impl_type = trait_ref.self_ty();
850 "comparing type {} with kind {:?} against type {:?}",
855 // Fast path: if this is a primitive simple `==` will work
856 // NOTE: the `match` is necessary; see #92662.
857 // this allows us to ignore generics because the user input
858 // may not include the generic placeholders
859 // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
860 let saw_impl = impl_type == ty
861 || match (impl_type.kind(), ty.kind()) {
862 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
863 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
864 impl_def.did() == ty_def.did()
869 if saw_impl { Some((impl_, trait_)) } else { None }
875 /// Check for resolve collisions between a trait and its derive.
877 /// These are common and we should just resolve to the trait in that case.
878 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
882 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
883 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
889 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
890 fn visit_item(&mut self, item: &Item) {
892 item.item_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
893 if parent_node.is_some() {
894 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.item_id);
897 let inner_docs = item.inner_docs(self.cx.tcx);
899 if item.is_mod() && inner_docs {
900 self.mod_ids.push(item.item_id.expect_def_id());
903 // We want to resolve in the lexical scope of the documentation.
904 // In the presence of re-exports, this is not the same as the module of the item.
905 // Rather than merging all documentation into one, resolve it one attribute at a time
906 // so we know which module it came from.
907 for (parent_module, doc) in item.attrs.prepare_to_doc_link_resolution() {
908 if !may_have_doc_links(&doc) {
911 debug!("combined_docs={}", doc);
912 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
913 // This is a degenerate case and it's not supported by rustdoc.
914 let parent_node = parent_module.or(parent_node);
915 let mut tmp_links = self
920 .expect("`markdown_links` are already borrowed");
921 if !tmp_links.contains_key(&doc) {
922 tmp_links.insert(doc.clone(), preprocessed_markdown_links(&doc));
924 for md_link in &tmp_links[&doc] {
925 let link = self.resolve_link(&item, &doc, parent_node, md_link);
926 if let Some(link) = link {
927 self.cx.cache.intra_doc_links.entry(item.item_id).or_default().push(link);
930 self.cx.resolver_caches.markdown_links = Some(tmp_links);
935 self.mod_ids.push(item.item_id.expect_def_id());
938 self.visit_item_recur(item);
941 self.visit_item_recur(item)
946 enum PreprocessingError {
947 /// User error: `[std#x#y]` is not valid
949 Disambiguator(Range<usize>, String),
950 MalformedGenerics(MalformedGenerics, String),
953 impl PreprocessingError {
954 fn report(&self, cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
956 PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info),
957 PreprocessingError::Disambiguator(range, msg) => {
958 disambiguator_error(cx, diag_info, range.clone(), msg)
960 PreprocessingError::MalformedGenerics(err, path_str) => {
961 report_malformed_generics(cx, diag_info, *err, path_str)
968 struct PreprocessingInfo {
970 disambiguator: Option<Disambiguator>,
971 extra_fragment: Option<String>,
975 // Not a typedef to avoid leaking several private structures from this module.
976 crate struct PreprocessedMarkdownLink(Result<PreprocessingInfo, PreprocessingError>, MarkdownLink);
979 /// - `None` if the link should be ignored.
980 /// - `Some(Err)` if the link should emit an error
981 /// - `Some(Ok)` if the link is valid
983 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
985 ori_link: &MarkdownLink,
986 ) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
987 // [] is mostly likely not supposed to be a link
988 if ori_link.link.is_empty() {
992 // Bail early for real links.
993 if ori_link.link.contains('/') {
997 let stripped = ori_link.link.replace('`', "");
998 let mut parts = stripped.split('#');
1000 let link = parts.next().unwrap();
1001 if link.trim().is_empty() {
1002 // This is an anchor to an element of the current page, nothing to do in here!
1005 let extra_fragment = parts.next();
1006 if parts.next().is_some() {
1007 // A valid link can't have multiple #'s
1008 return Some(Err(PreprocessingError::MultipleAnchors));
1011 // Parse and strip the disambiguator from the link, if present.
1012 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1013 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1014 Ok(None) => (None, link.trim(), link.trim()),
1015 Err((err_msg, relative_range)) => {
1016 // Only report error if we would not have ignored this link. See issue #83859.
1017 if !should_ignore_link_with_disambiguators(link) {
1018 let no_backticks_range = range_between_backticks(ori_link);
1019 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1020 ..(no_backticks_range.start + relative_range.end);
1021 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1028 if should_ignore_link(path_str) {
1032 // Strip generics from the path.
1033 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1034 match strip_generics_from_path(path_str) {
1037 debug!("link has malformed generics: {}", path_str);
1038 return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
1045 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1046 assert!(!path_str.contains(['<', '>'].as_slice()));
1048 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1049 if path_str.contains(' ') {
1053 Some(Ok(PreprocessingInfo {
1056 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1057 link_text: link_text.to_owned(),
1061 fn preprocessed_markdown_links(s: &str) -> Vec<PreprocessedMarkdownLink> {
1062 markdown_links(s, |link| {
1063 preprocess_link(&link).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1067 impl LinkCollector<'_, '_> {
1068 /// This is the entry point for resolving an intra-doc link.
1070 /// FIXME(jynelson): this is way too many arguments
1075 parent_node: Option<DefId>,
1076 link: &PreprocessedMarkdownLink,
1077 ) -> Option<ItemLink> {
1078 let PreprocessedMarkdownLink(pp_link, ori_link) = link;
1079 trace!("considering link '{}'", ori_link.link);
1081 let diag_info = DiagnosticInfo {
1084 ori_link: &ori_link.link,
1085 link_range: ori_link.range.clone(),
1088 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1089 pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1090 let disambiguator = *disambiguator;
1092 // In order to correctly resolve intra-doc links we need to
1093 // pick a base AST node to work from. If the documentation for
1094 // this module came from an inner comment (//!) then we anchor
1095 // our name resolution *inside* the module. If, on the other
1096 // hand it was an outer comment (///) then we anchor the name
1097 // resolution in the parent module on the basis that the names
1098 // used are more likely to be intended to be parent names. For
1099 // this, we set base_node to None for inner comments since
1100 // we've already pushed this node onto the resolution stack but
1101 // for outer comments we explicitly try and resolve against the
1102 // parent_node first.
1103 let inner_docs = item.inner_docs(self.cx.tcx);
1105 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1106 let module_id = base_node.expect("doc link without parent module");
1108 let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1110 item_id: item.item_id,
1113 path_str: path_str.to_owned(),
1114 extra_fragment: extra_fragment.clone(),
1116 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1117 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1120 // Check for a primitive which might conflict with a module
1121 // Report the ambiguity and require that the user specify which one they meant.
1122 // FIXME: could there ever be a primitive not in the type namespace?
1125 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1126 ) && !matches!(res, Res::Primitive(_))
1128 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1130 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1133 // `[char]` when a `char` module is in scope
1134 let candidates = vec![res, prim];
1135 ambiguity_error(self.cx, diag_info, path_str, candidates);
1142 Res::Primitive(prim) => {
1143 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1144 // We're actually resolving an associated item of a primitive, so we need to
1145 // verify the disambiguator (if any) matches the type of the associated item.
1146 // This case should really follow the same flow as the `Res::Def` branch below,
1147 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1148 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1149 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1150 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1151 // for discussion on the matter.
1152 let kind = self.cx.tcx.def_kind(id);
1153 self.verify_disambiguator(
1163 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1164 // However I'm not sure how to check that across crates.
1165 if prim == PrimitiveType::RawPointer
1166 && item.item_id.is_local()
1167 && !self.cx.tcx.features().intra_doc_pointers
1169 self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1172 match disambiguator {
1173 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1175 self.report_disambiguator_mismatch(
1176 path_str, &ori_link, other, res, &diag_info,
1184 link: ori_link.link.clone(),
1185 link_text: link_text.clone(),
1186 did: res.def_id(self.cx.tcx),
1190 Res::Def(kind, id) => {
1191 let (kind_for_dis, id_for_dis) =
1192 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1193 (self.cx.tcx.def_kind(id), id)
1197 self.verify_disambiguator(
1206 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1208 link: ori_link.link.clone(),
1209 link_text: link_text.clone(),
1217 fn verify_disambiguator(
1220 ori_link: &MarkdownLink,
1223 disambiguator: Option<Disambiguator>,
1225 diag_info: &DiagnosticInfo<'_>,
1227 debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1229 // Disallow e.g. linking to enums with `struct@`
1230 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1231 match (kind, disambiguator) {
1232 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1233 // NOTE: this allows 'method' to mean both normal functions and associated functions
1234 // This can't cause ambiguity because both are in the same namespace.
1235 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1236 // These are namespaces; allow anything in the namespace to match
1237 | (_, Some(Disambiguator::Namespace(_)))
1238 // If no disambiguator given, allow anything
1240 // All of these are valid, so do nothing
1242 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1243 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1244 self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1249 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1250 if let Some((src_id, dst_id)) = id
1252 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1253 // would presumably panic if a fake `DefIndex` were passed.
1254 .and_then(|dst_id| {
1255 item.item_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1258 if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1259 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1261 privacy_error(self.cx, diag_info, path_str);
1268 fn report_disambiguator_mismatch(
1271 ori_link: &MarkdownLink,
1272 specified: Disambiguator,
1274 diag_info: &DiagnosticInfo<'_>,
1276 // The resolved item did not match the disambiguator; give a better error than 'not found'
1277 let msg = format!("incompatible link kind for `{}`", path_str);
1278 let callback = |diag: &mut Diagnostic, sp: Option<rustc_span::Span>| {
1280 "this link resolved to {} {}, which is not {} {}",
1283 specified.article(),
1286 if let Some(sp) = sp {
1287 diag.span_label(sp, ¬e);
1291 suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1293 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1296 fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1298 super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1299 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1300 rustc_session::parse::feature_err(
1301 &self.cx.tcx.sess.parse_sess,
1302 sym::intra_doc_pointers,
1304 "linking to associated items of raw pointers is experimental",
1306 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1310 fn resolve_with_disambiguator_cached(
1312 key: ResolutionInfo,
1313 diag: DiagnosticInfo<'_>,
1314 cache_resolution_failure: bool,
1315 ) -> Option<(Res, Option<UrlFragment>)> {
1316 if let Some(ref cached) = self.visited_links.get(&key) {
1319 return Some(cached.res.clone());
1321 None if cache_resolution_failure => return None,
1323 // Although we hit the cache and found a resolution error, this link isn't
1324 // supposed to cache those. Run link resolution again to emit the expected
1325 // resolution error.
1330 let res = self.resolve_with_disambiguator(&key, diag.clone()).and_then(|(res, def_id)| {
1331 let fragment = match (&key.extra_fragment, def_id) {
1332 (Some(_), Some(def_id)) => {
1333 report_anchor_conflict(self.cx, diag, Res::from_def_id(self.cx.tcx, def_id));
1336 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1337 (None, Some(def_id)) => Some(UrlFragment::Item(ItemFragment(
1338 FragmentKind::from_def_id(self.cx.tcx, def_id),
1341 (None, None) => None,
1343 Some((res, fragment))
1346 // Cache only if resolved successfully - don't silence duplicate errors
1347 if let Some(res) = res {
1348 // Store result for the actual namespace
1349 self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1353 if cache_resolution_failure {
1354 // For reference-style links we only want to report one resolution error
1355 // so let's cache them as well.
1356 self.visited_links.insert(key, None);
1363 /// After parsing the disambiguator, resolve the main part of the link.
1364 // FIXME(jynelson): wow this is just so much
1365 fn resolve_with_disambiguator(
1367 key: &ResolutionInfo,
1368 diag: DiagnosticInfo<'_>,
1369 ) -> Option<(Res, Option<DefId>)> {
1370 let disambiguator = key.dis;
1371 let path_str = &key.path_str;
1372 let item_id = key.item_id;
1373 let base_node = key.module_id;
1375 match disambiguator.map(Disambiguator::ns) {
1376 Some(expected_ns) => {
1377 match self.resolve(path_str, expected_ns, item_id, base_node) {
1378 Ok(res) => Some(res),
1380 // We only looked in one namespace. Try to give a better error if possible.
1381 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`.
1382 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach.
1383 let mut err = ResolutionFailure::NotResolved(err);
1384 for other_ns in [TypeNS, ValueNS, MacroNS] {
1385 if other_ns != expected_ns {
1387 self.resolve(path_str, other_ns, item_id, base_node)
1389 err = ResolutionFailure::WrongNamespace {
1390 res: full_res(self.cx.tcx, res),
1397 resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1398 // This could just be a normal link or a broken link
1399 // we could potentially check if something is
1400 // "intra-doc-link-like" and warn in that case.
1407 let mut candidate = |ns| {
1408 self.resolve(path_str, ns, item_id, base_node)
1409 .map_err(ResolutionFailure::NotResolved)
1412 let candidates = PerNS {
1413 macro_ns: candidate(MacroNS),
1414 type_ns: candidate(TypeNS),
1415 value_ns: candidate(ValueNS).and_then(|(res, def_id)| {
1417 // Constructors are picked up in the type namespace.
1418 Res::Def(DefKind::Ctor(..), _) => {
1419 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1421 _ => Ok((res, def_id)),
1426 let len = candidates.iter().filter(|res| res.is_ok()).count();
1434 candidates.into_iter().filter_map(|res| res.err()).collect(),
1436 // this could just be a normal link
1441 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1442 } else if len == 2 && is_derive_trait_collision(&candidates) {
1443 Some(candidates.type_ns.unwrap())
1445 let ignore_macro = is_derive_trait_collision(&candidates);
1446 // If we're reporting an ambiguity, don't mention the namespaces that failed
1447 let mut candidates =
1448 candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1450 candidates.macro_ns = None;
1452 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1460 /// Get the section of a link between the backticks,
1461 /// or the whole link if there aren't any backticks.
1469 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1470 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1471 let before_second_backtick_group = ori_link
1474 .skip(after_first_backtick_group)
1475 .position(|b| b == b'`')
1476 .unwrap_or(ori_link.link.len());
1477 (ori_link.range.start + after_first_backtick_group)
1478 ..(ori_link.range.start + before_second_backtick_group)
1481 /// Returns true if we should ignore `link` due to it being unlikely
1482 /// that it is an intra-doc link. `link` should still have disambiguators
1483 /// if there were any.
1485 /// The difference between this and [`should_ignore_link()`] is that this
1486 /// check should only be used on links that still have disambiguators.
1487 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1488 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1491 /// Returns true if we should ignore `path_str` due to it being unlikely
1492 /// that it is an intra-doc link.
1493 fn should_ignore_link(path_str: &str) -> bool {
1494 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1497 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1498 /// Disambiguators for a link.
1499 enum Disambiguator {
1502 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1504 /// `struct@` or `f()`
1507 Namespace(Namespace),
1510 impl Disambiguator {
1511 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1513 /// This returns `Ok(Some(...))` if a disambiguator was found,
1514 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1515 /// if there was a problem with the disambiguator.
1516 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1517 use Disambiguator::{Kind, Namespace as NS, Primitive};
1519 if let Some(idx) = link.find('@') {
1520 let (prefix, rest) = link.split_at(idx);
1521 let d = match prefix {
1522 "struct" => Kind(DefKind::Struct),
1523 "enum" => Kind(DefKind::Enum),
1524 "trait" => Kind(DefKind::Trait),
1525 "union" => Kind(DefKind::Union),
1526 "module" | "mod" => Kind(DefKind::Mod),
1527 "const" | "constant" => Kind(DefKind::Const),
1528 "static" => Kind(DefKind::Static(Mutability::Not)),
1529 "function" | "fn" | "method" => Kind(DefKind::Fn),
1530 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1531 "type" => NS(Namespace::TypeNS),
1532 "value" => NS(Namespace::ValueNS),
1533 "macro" => NS(Namespace::MacroNS),
1534 "prim" | "primitive" => Primitive,
1535 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1537 Ok(Some((d, &rest[1..], &rest[1..])))
1540 ("!()", DefKind::Macro(MacroKind::Bang)),
1541 ("!{}", DefKind::Macro(MacroKind::Bang)),
1542 ("![]", DefKind::Macro(MacroKind::Bang)),
1543 ("()", DefKind::Fn),
1544 ("!", DefKind::Macro(MacroKind::Bang)),
1546 for (suffix, kind) in suffixes {
1547 if let Some(path_str) = link.strip_suffix(suffix) {
1548 // Avoid turning `!` or `()` into an empty string
1549 if !path_str.is_empty() {
1550 return Ok(Some((Kind(kind), path_str, link)));
1558 fn ns(self) -> Namespace {
1560 Self::Namespace(n) => n,
1562 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1564 Self::Primitive => TypeNS,
1568 fn article(self) -> &'static str {
1570 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1571 Self::Kind(k) => k.article(),
1572 Self::Primitive => "a",
1576 fn descr(self) -> &'static str {
1578 Self::Namespace(n) => n.descr(),
1579 // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1580 // printing "module" vs "crate" so using the wrong ID is not a huge problem
1581 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1582 Self::Primitive => "builtin type",
1587 /// A suggestion to show in a diagnostic.
1590 Prefix(&'static str),
1595 /// `foo` without any disambiguator
1596 RemoveDisambiguator,
1600 fn descr(&self) -> Cow<'static, str> {
1602 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1603 Self::Function => "add parentheses".into(),
1604 Self::Macro => "add an exclamation mark".into(),
1605 Self::RemoveDisambiguator => "remove the disambiguator".into(),
1609 fn as_help(&self, path_str: &str) -> String {
1610 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1612 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1613 Self::Function => format!("{}()", path_str),
1614 Self::Macro => format!("{}!", path_str),
1615 Self::RemoveDisambiguator => path_str.into(),
1623 sp: rustc_span::Span,
1624 ) -> Vec<(rustc_span::Span, String)> {
1625 let inner_sp = match ori_link.find('(') {
1626 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1629 let inner_sp = match ori_link.find('!') {
1630 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1633 let inner_sp = match ori_link.find('@') {
1634 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1638 Self::Prefix(prefix) => {
1639 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1640 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1641 if sp.hi() != inner_sp.hi() {
1642 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1647 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1648 if sp.lo() != inner_sp.lo() {
1649 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1654 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1655 if sp.lo() != inner_sp.lo() {
1656 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1660 Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1665 /// Reports a diagnostic for an intra-doc link.
1667 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1668 /// the entire documentation block is used for the lint. If a range is provided but the span
1669 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1671 /// The `decorate` callback is invoked in all cases to allow further customization of the
1672 /// diagnostic before emission. If the span of the link was able to be determined, the second
1673 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1675 fn report_diagnostic(
1677 lint: &'static Lint,
1679 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1680 decorate: impl FnOnce(&mut Diagnostic, Option<rustc_span::Span>),
1682 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id)
1684 // If non-local, no need to check anything.
1685 info!("ignoring warning from parent crate: {}", msg);
1689 let sp = item.attr_span(tcx);
1691 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1692 let mut diag = lint.build(msg);
1695 super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1696 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1697 && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1699 sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1705 if let Some(sp) = span {
1708 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1711 // last_new_line_offset
1712 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1713 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1715 // Print the line containing the `link_range` and manually mark it with '^'s.
1717 "the link appears in this line:\n\n{line}\n\
1718 {indicator: <before$}{indicator:^<found$}",
1721 before = link_range.start - last_new_line_offset,
1722 found = link_range.len(),
1726 decorate(&mut diag, span);
1732 /// Reports a link that failed to resolve.
1734 /// This also tries to resolve any intermediate path segments that weren't
1735 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1736 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1737 fn resolution_failure(
1738 collector: &mut LinkCollector<'_, '_>,
1739 diag_info: DiagnosticInfo<'_>,
1741 disambiguator: Option<Disambiguator>,
1742 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1744 let tcx = collector.cx.tcx;
1747 BROKEN_INTRA_DOC_LINKS,
1748 &format!("unresolved link to `{}`", path_str),
1751 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1752 let assoc_item_not_allowed = |res: Res| {
1753 let name = res.name(tcx);
1755 "`{}` is {} {}, not a module or type, and cannot have associated items",
1761 // ignore duplicates
1762 let mut variants_seen = SmallVec::<[_; 3]>::new();
1763 for mut failure in kinds {
1764 let variant = std::mem::discriminant(&failure);
1765 if variants_seen.contains(&variant) {
1768 variants_seen.push(variant);
1770 if let ResolutionFailure::NotResolved(UnresolvedPath {
1779 let item_id = *item_id;
1780 let module_id = *module_id;
1781 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1782 // FIXME: maybe use itertools `collect_tuple` instead?
1783 fn split(path: &str) -> Option<(&str, &str)> {
1784 let mut splitter = path.rsplitn(2, "::");
1785 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1788 // Check if _any_ parent of the path gets resolved.
1789 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1790 let mut name = path_str;
1792 let Some((start, end)) = split(name) else {
1793 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1794 if partial_res.is_none() {
1795 *unresolved = name.into();
1800 for ns in [TypeNS, ValueNS, MacroNS] {
1801 if let Ok(res) = collector.resolve(start, ns, item_id, module_id) {
1802 debug!("found partial_res={:?}", res);
1803 *partial_res = Some(full_res(collector.cx.tcx, res));
1804 *unresolved = end.into();
1808 *unresolved = end.into();
1811 let last_found_module = match *partial_res {
1812 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1813 None => Some(module_id),
1816 // See if this was a module: `[path]` or `[std::io::nope]`
1817 if let Some(module) = last_found_module {
1818 let note = if partial_res.is_some() {
1819 // Part of the link resolved; e.g. `std::io::nonexistent`
1820 let module_name = tcx.item_name(module);
1821 format!("no item named `{}` in module `{}`", unresolved, module_name)
1823 // None of the link resolved; e.g. `Notimported`
1824 format!("no item named `{}` in scope", unresolved)
1826 if let Some(span) = sp {
1827 diag.span_label(span, ¬e);
1832 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1833 // Otherwise, the `[]` might be unrelated.
1834 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1835 if !path_str.contains("::") {
1836 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1842 // Otherwise, it must be an associated item or variant
1843 let res = partial_res.expect("None case was handled by `last_found_module`");
1844 let name = res.name(tcx);
1845 let kind = match res {
1846 Res::Def(kind, _) => Some(kind),
1847 Res::Primitive(_) => None,
1849 let path_description = if let Some(kind) = kind {
1851 Mod | ForeignMod => "inner item",
1852 Struct => "field or associated item",
1853 Enum | Union => "variant or associated item",
1871 let note = assoc_item_not_allowed(res);
1872 if let Some(span) = sp {
1873 diag.span_label(span, ¬e);
1879 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1880 | Static(_) => "associated item",
1881 Impl | GlobalAsm => unreachable!("not a path"),
1887 "the {} `{}` has no {} named `{}`",
1890 disambiguator.map_or(path_description, |d| d.descr()),
1893 if let Some(span) = sp {
1894 diag.span_label(span, ¬e);
1901 let note = match failure {
1902 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1903 ResolutionFailure::WrongNamespace { res, expected_ns } => {
1904 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
1907 "this link resolves to {}, which is not in the {} namespace",
1913 if let Some(span) = sp {
1914 diag.span_label(span, ¬e);
1923 fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
1924 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
1925 anchor_failure(cx, diag_info, &msg, 1)
1928 fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, res: Res) {
1929 let (link, kind) = (diag_info.ori_link, res.descr());
1930 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
1931 anchor_failure(cx, diag_info, &msg, 0)
1934 /// Report an anchor failure.
1936 cx: &DocContext<'_>,
1937 diag_info: DiagnosticInfo<'_>,
1941 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
1942 if let Some(mut sp) = sp {
1943 if let Some((fragment_offset, _)) =
1944 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
1946 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
1948 diag.span_label(sp, "invalid anchor");
1953 /// Report an error in the link disambiguator.
1954 fn disambiguator_error(
1955 cx: &DocContext<'_>,
1956 mut diag_info: DiagnosticInfo<'_>,
1957 disambiguator_range: Range<usize>,
1960 diag_info.link_range = disambiguator_range;
1961 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
1963 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
1964 crate::DOC_RUST_LANG_ORG_CHANNEL
1970 fn report_malformed_generics(
1971 cx: &DocContext<'_>,
1972 diag_info: DiagnosticInfo<'_>,
1973 err: MalformedGenerics,
1978 BROKEN_INTRA_DOC_LINKS,
1979 &format!("unresolved link to `{}`", path_str),
1982 let note = match err {
1983 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
1984 MalformedGenerics::MissingType => "missing type for generic parameters",
1985 MalformedGenerics::HasFullyQualifiedSyntax => {
1987 "see https://github.com/rust-lang/rust/issues/74563 for more information",
1989 "fully-qualified syntax is unsupported"
1991 MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
1992 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
1993 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
1995 if let Some(span) = sp {
1996 diag.span_label(span, note);
2004 /// Report an ambiguity error, where there were multiple possible resolutions.
2006 cx: &DocContext<'_>,
2007 diag_info: DiagnosticInfo<'_>,
2009 candidates: Vec<Res>,
2011 let mut msg = format!("`{}` is ", path_str);
2013 match candidates.as_slice() {
2014 [first_def, second_def] => {
2016 "both {} {} and {} {}",
2017 first_def.article(),
2019 second_def.article(),
2024 let mut candidates = candidates.iter().peekable();
2025 while let Some(res) = candidates.next() {
2026 if candidates.peek().is_some() {
2027 msg += &format!("{} {}, ", res.article(), res.descr());
2029 msg += &format!("and {} {}", res.article(), res.descr());
2035 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2036 if let Some(sp) = sp {
2037 diag.span_label(sp, "ambiguous link");
2039 diag.note("ambiguous link");
2042 for res in candidates {
2043 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2048 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2050 fn suggest_disambiguator(
2052 diag: &mut Diagnostic,
2055 sp: Option<rustc_span::Span>,
2057 let suggestion = res.disambiguator_suggestion();
2058 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2060 if let Some(sp) = sp {
2061 let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2062 if spans.len() > 1 {
2063 diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2065 let (sp, suggestion_text) = spans.pop().unwrap();
2066 diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2069 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2073 /// Report a link from a public item to a private one.
2074 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2076 let item_name = match diag_info.item.name {
2081 None => "<unknown>",
2084 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2086 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2087 if let Some(sp) = sp {
2088 diag.span_label(sp, "this item is private");
2091 let note_msg = if cx.render_options.document_private {
2092 "this link resolves only because you passed `--document-private-items`, but will break without"
2094 "this link will resolve properly if you pass `--document-private-items`"
2096 diag.note(note_msg);
2100 /// Resolve a primitive type or value.
2101 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2105 use PrimitiveType::*;
2106 let prim = match path_str {
2122 "bool" | "true" | "false" => Bool,
2123 "str" | "&str" => Str,
2124 // See #80181 for why these don't have symbols associated.
2129 "pointer" | "*const" | "*mut" => RawPointer,
2130 "reference" | "&" | "&mut" => Reference,
2132 "never" | "!" => Never,
2135 debug!("resolved primitives {:?}", prim);
2136 Some(Res::Primitive(prim))
2139 fn strip_generics_from_path(path_str: &str) -> Result<String, MalformedGenerics> {
2140 let mut stripped_segments = vec![];
2141 let mut path = path_str.chars().peekable();
2142 let mut segment = Vec::new();
2144 while let Some(chr) = path.next() {
2147 if path.next_if_eq(&':').is_some() {
2148 let stripped_segment =
2149 strip_generics_from_path_segment(mem::take(&mut segment))?;
2150 if !stripped_segment.is_empty() {
2151 stripped_segments.push(stripped_segment);
2154 return Err(MalformedGenerics::InvalidPathSeparator);
2162 return Err(MalformedGenerics::TooManyAngleBrackets);
2165 return Err(MalformedGenerics::EmptyAngleBrackets);
2170 while let Some(chr) = path.next_if(|c| *c != '>') {
2177 _ => segment.push(chr),
2179 trace!("raw segment: {:?}", segment);
2182 if !segment.is_empty() {
2183 let stripped_segment = strip_generics_from_path_segment(segment)?;
2184 if !stripped_segment.is_empty() {
2185 stripped_segments.push(stripped_segment);
2189 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2191 let stripped_path = stripped_segments.join("::");
2193 if !stripped_path.is_empty() { Ok(stripped_path) } else { Err(MalformedGenerics::MissingType) }
2196 fn strip_generics_from_path_segment(segment: Vec<char>) -> Result<String, MalformedGenerics> {
2197 let mut stripped_segment = String::new();
2198 let mut param_depth = 0;
2200 let mut latest_generics_chunk = String::new();
2205 latest_generics_chunk.clear();
2206 } else if c == '>' {
2208 if latest_generics_chunk.contains(" as ") {
2209 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2210 // Give a helpful error message instead of completely ignoring the angle brackets.
2211 return Err(MalformedGenerics::HasFullyQualifiedSyntax);
2214 if param_depth == 0 {
2215 stripped_segment.push(c);
2217 latest_generics_chunk.push(c);
2222 if param_depth == 0 {
2223 Ok(stripped_segment)
2225 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2226 Err(MalformedGenerics::UnbalancedAngleBrackets)