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};
26 use crate::clean::{self, utils::find_nearest_parent_module};
27 use crate::clean::{Crate, Item, ItemId, ItemLink, PrimitiveType};
28 use crate::core::DocContext;
29 use crate::html::markdown::{markdown_links, MarkdownLink};
30 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
31 use crate::passes::Pass;
32 use crate::visit::DocVisitor;
35 pub(crate) use early::early_resolve_intra_doc_links;
37 pub(crate) const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
38 name: "collect-intra-doc-links",
39 run: collect_intra_doc_links,
40 description: "resolves intra-doc links",
43 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
45 LinkCollector { cx, mod_ids: Vec::new(), visited_links: FxHashMap::default() };
46 collector.visit_crate(&krate);
50 #[derive(Copy, Clone, Debug, Hash)]
53 Primitive(PrimitiveType),
56 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
59 fn descr(self) -> &'static str {
61 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
62 Res::Primitive(_) => "builtin type",
66 fn article(self) -> &'static str {
68 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
69 Res::Primitive(_) => "a",
73 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
75 Res::Def(_, id) => tcx.item_name(id),
76 Res::Primitive(prim) => prim.as_sym(),
80 fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
82 Res::Def(_, id) => id,
83 Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
87 fn from_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Res {
88 Res::Def(tcx.def_kind(def_id), def_id)
91 /// Used for error reporting.
92 fn disambiguator_suggestion(self) -> Suggestion {
93 let kind = match self {
94 Res::Primitive(_) => return Suggestion::Prefix("prim"),
95 Res::Def(kind, _) => kind,
97 if kind == DefKind::Macro(MacroKind::Bang) {
98 return Suggestion::Macro;
99 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
100 return Suggestion::Function;
101 } else if kind == DefKind::Field {
102 return Suggestion::RemoveDisambiguator;
105 let prefix = match kind {
106 DefKind::Struct => "struct",
107 DefKind::Enum => "enum",
108 DefKind::Trait => "trait",
109 DefKind::Union => "union",
110 DefKind::Mod => "mod",
111 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
114 DefKind::Static(_) => "static",
115 DefKind::Macro(MacroKind::Derive) => "derive",
116 // Now handle things that don't have a specific disambiguator
119 .expect("tried to calculate a disambiguator for a def without a namespace?")
121 Namespace::TypeNS => "type",
122 Namespace::ValueNS => "value",
123 Namespace::MacroNS => "macro",
127 Suggestion::Prefix(prefix)
131 impl TryFrom<ResolveRes> for Res {
134 fn try_from(res: ResolveRes) -> Result<Self, ()> {
135 use rustc_hir::def::Res::*;
137 Def(kind, id) => Ok(Res::Def(kind, id)),
138 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
140 NonMacroAttr(..) | Err => Result::Err(()),
141 other => bug!("unrecognized res {:?}", other),
146 /// The link failed to resolve. [`resolution_failure`] should look to see if there's
147 /// a more helpful error that can be given.
149 struct UnresolvedPath<'a> {
150 /// Item on which the link is resolved, used for resolving `Self`.
152 /// The scope the link was resolved in.
154 /// If part of the link resolved, this has the `Res`.
156 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
157 partial_res: Option<Res>,
158 /// The remaining unresolved path segments.
160 /// In `[std::io::Error::x]`, `x` would be unresolved.
161 unresolved: Cow<'a, str>,
165 enum ResolutionFailure<'a> {
166 /// This resolved, but with the wrong namespace.
168 /// What the link resolved to.
170 /// The expected namespace for the resolution, determined from the link's disambiguator.
172 /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
173 /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
174 expected_ns: Namespace,
176 NotResolved(UnresolvedPath<'a>),
179 #[derive(Clone, Copy, Debug)]
180 enum MalformedGenerics {
181 /// This link has unbalanced angle brackets.
183 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
184 UnbalancedAngleBrackets,
185 /// The generics are not attached to a type.
187 /// For example, `<T>` should trigger this.
189 /// This is detected by checking if the path is empty after the generics are stripped.
191 /// The link uses fully-qualified syntax, which is currently unsupported.
193 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
195 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
197 HasFullyQualifiedSyntax,
198 /// The link has an invalid path separator.
200 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
201 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
204 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
205 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
206 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
208 /// This is detected by checking if there is a colon followed by a non-colon in the link.
209 InvalidPathSeparator,
210 /// The link has too many angle brackets.
212 /// For example, `Vec<<T>>` should trigger this.
213 TooManyAngleBrackets,
214 /// The link has empty angle brackets.
216 /// For example, `Vec<>` should trigger this.
220 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
221 pub(crate) enum UrlFragment {
227 /// Render the fragment, including the leading `#`.
228 pub(crate) fn render(&self, s: &mut String, tcx: TyCtxt<'_>) {
231 &UrlFragment::Item(def_id) => {
232 let kind = match tcx.def_kind(def_id) {
233 DefKind::AssocFn => {
234 if tcx.associated_item(def_id).defaultness.has_value() {
240 DefKind::AssocConst => "associatedconstant.",
241 DefKind::AssocTy => "associatedtype.",
242 DefKind::Variant => "variant.",
244 let parent_id = tcx.parent(def_id);
245 if tcx.def_kind(parent_id) == DefKind::Variant {
246 s.push_str("variant.");
247 s.push_str(tcx.item_name(parent_id).as_str());
253 kind => bug!("unexpected associated item kind: {:?}", kind),
256 s.push_str(tcx.item_name(def_id).as_str());
258 UrlFragment::UserWritten(raw) => s.push_str(&raw),
263 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
264 struct ResolutionInfo {
267 dis: Option<Disambiguator>,
269 extra_fragment: Option<String>,
273 struct DiagnosticInfo<'a> {
277 link_range: Range<usize>,
280 struct LinkCollector<'a, 'tcx> {
281 cx: &'a mut DocContext<'tcx>,
282 /// A stack of modules used to decide what scope to resolve in.
284 /// The last module will be used if the parent scope of the current item is
287 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
288 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
289 visited_links: FxHashMap<ResolutionInfo, Option<(Res, Option<UrlFragment>)>>,
292 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
293 /// Given a full link, parse it as an [enum struct variant].
295 /// In particular, this will return an error whenever there aren't three
296 /// full path segments left in the link.
298 /// [enum struct variant]: rustc_hir::VariantData::Struct
299 fn variant_field<'path>(
301 path_str: &'path str,
304 ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
305 let tcx = self.cx.tcx;
306 let no_res = || UnresolvedPath {
310 unresolved: path_str.into(),
313 debug!("looking for enum variant {}", path_str);
314 let mut split = path_str.rsplitn(3, "::");
315 let variant_field_name = split
317 .map(|f| Symbol::intern(f))
318 .expect("fold_item should ensure link is non-empty");
320 // we're not sure this is a variant at all, so use the full string
321 // If there's no second component, the link looks like `[path]`.
322 // So there's no partial res and we should say the whole link failed to resolve.
323 split.next().map(|f| Symbol::intern(f)).ok_or_else(no_res)?;
326 .map(|f| f.to_owned())
327 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
328 // So there's no partial res.
329 .ok_or_else(no_res)?;
330 let ty_res = self.resolve_path(&path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
333 Res::Def(DefKind::Enum, did) => match tcx.type_of(did).kind() {
334 ty::Adt(def, _) if def.is_enum() => {
335 if let Some(field) = def.all_fields().find(|f| f.name == variant_field_name) {
336 Ok((ty_res, field.did))
341 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
342 unresolved: variant_field_name.to_string().into(),
348 _ => Err(UnresolvedPath {
351 partial_res: Some(ty_res),
352 unresolved: variant_name.to_string().into(),
357 /// Given a primitive type, try to resolve an associated item.
358 fn resolve_primitive_associated_item(
360 prim_ty: PrimitiveType,
363 ) -> Option<(Res, DefId)> {
364 let tcx = self.cx.tcx;
366 prim_ty.impls(tcx).find_map(|impl_| {
367 tcx.associated_items(impl_)
368 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
369 .map(|item| (Res::Primitive(prim_ty), item.def_id))
373 fn resolve_self_ty(&self, path_str: &str, ns: Namespace, item_id: ItemId) -> Option<Res> {
374 if ns != TypeNS || path_str != "Self" {
378 let tcx = self.cx.tcx;
381 .map(|def_id| match tcx.def_kind(def_id) {
382 def_kind @ (DefKind::AssocFn
383 | DefKind::AssocConst
386 | DefKind::Field) => {
387 let parent_def_id = tcx.parent(def_id);
388 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant
390 tcx.parent(parent_def_id)
397 .and_then(|self_id| match tcx.def_kind(self_id) {
398 DefKind::Impl => self.def_id_to_res(self_id),
399 def_kind => Some(Res::Def(def_kind, self_id)),
403 /// Convenience wrapper around `resolve_rustdoc_path`.
405 /// This also handles resolving `true` and `false` as booleans.
406 /// NOTE: `resolve_rustdoc_path` knows only about paths, not about types.
407 /// Associated items will never be resolved by this function.
415 if let res @ Some(..) = self.resolve_self_ty(path_str, ns, item_id) {
419 // Resolver doesn't know about true, false, and types that aren't paths (e.g. `()`).
423 .doc_link_resolutions
424 .get(&(Symbol::intern(path_str), ns, module_id))
427 self.cx.enter_resolver(|resolver| {
429 ParentScope::module(resolver.expect_module(module_id), resolver);
430 resolver.resolve_rustdoc_path(path_str, ns, parent_scope)
433 .and_then(|res| res.try_into().ok())
434 .or_else(|| resolve_primitive(path_str, ns));
435 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
439 /// Resolves a string as a path within a particular namespace. Returns an
440 /// optional URL fragment in the case of variants and methods.
443 path_str: &'path str,
447 ) -> Result<(Res, Option<DefId>), UnresolvedPath<'path>> {
448 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
449 return Ok(match res {
451 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Variant,
453 ) => (Res::from_def_id(self.cx.tcx, self.cx.tcx.parent(def_id)), Some(def_id)),
456 } else if ns == MacroNS {
457 return Err(UnresolvedPath {
461 unresolved: path_str.into(),
465 // Try looking for methods and associated items.
466 let mut split = path_str.rsplitn(2, "::");
467 // NB: `split`'s first element is always defined, even if the delimiter was not present.
468 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
469 let item_str = split.next().unwrap();
470 let item_name = Symbol::intern(item_str);
471 let path_root = split
473 .map(|f| f.to_owned())
474 // If there's no `::`, it's not an associated item.
475 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
477 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
482 unresolved: item_str.into(),
486 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
487 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
488 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
490 resolve_primitive(&path_root, TypeNS)
491 .or_else(|| self.resolve_path(&path_root, TypeNS, item_id, module_id))
493 self.resolve_associated_item(ty_res, item_name, ns, module_id).map(Ok)
496 if ns == Namespace::ValueNS {
497 self.variant_field(path_str, item_id, module_id)
503 unresolved: path_root.into(),
507 .map(|(res, def_id)| (res, Some(def_id)))
510 /// Convert a DefId to a Res, where possible.
512 /// This is used for resolving type aliases.
513 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
514 use PrimitiveType::*;
515 Some(match *self.cx.tcx.type_of(ty_id).kind() {
516 ty::Bool => Res::Primitive(Bool),
517 ty::Char => Res::Primitive(Char),
518 ty::Int(ity) => Res::Primitive(ity.into()),
519 ty::Uint(uty) => Res::Primitive(uty.into()),
520 ty::Float(fty) => Res::Primitive(fty.into()),
521 ty::Str => Res::Primitive(Str),
522 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
523 ty::Tuple(_) => Res::Primitive(Tuple),
524 ty::Array(..) => Res::Primitive(Array),
525 ty::Slice(_) => Res::Primitive(Slice),
526 ty::RawPtr(_) => Res::Primitive(RawPointer),
527 ty::Ref(..) => Res::Primitive(Reference),
528 ty::FnDef(..) => panic!("type alias to a function definition"),
529 ty::FnPtr(_) => Res::Primitive(Fn),
530 ty::Never => Res::Primitive(Never),
531 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
532 Res::from_def_id(self.cx.tcx, did)
537 | ty::GeneratorWitness(_)
544 | ty::Error(_) => return None,
548 /// Convert a PrimitiveType to a Ty, where possible.
550 /// This is used for resolving trait impls for primitives
551 fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
552 use PrimitiveType::*;
553 let tcx = self.cx.tcx;
555 // FIXME: Only simple types are supported here, see if we can support
556 // other types such as Tuple, Array, Slice, etc.
557 // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
558 Some(tcx.mk_ty(match prim {
563 I8 => ty::Int(ty::IntTy::I8),
564 I16 => ty::Int(ty::IntTy::I16),
565 I32 => ty::Int(ty::IntTy::I32),
566 I64 => ty::Int(ty::IntTy::I64),
567 I128 => ty::Int(ty::IntTy::I128),
568 Isize => ty::Int(ty::IntTy::Isize),
569 F32 => ty::Float(ty::FloatTy::F32),
570 F64 => ty::Float(ty::FloatTy::F64),
571 U8 => ty::Uint(ty::UintTy::U8),
572 U16 => ty::Uint(ty::UintTy::U16),
573 U32 => ty::Uint(ty::UintTy::U32),
574 U64 => ty::Uint(ty::UintTy::U64),
575 U128 => ty::Uint(ty::UintTy::U128),
576 Usize => ty::Uint(ty::UintTy::Usize),
581 /// Resolve an associated item, returning its containing page's `Res`
582 /// and the fragment targeting the associated item on its page.
583 fn resolve_associated_item(
589 ) -> Option<(Res, DefId)> {
590 let tcx = self.cx.tcx;
593 Res::Primitive(prim) => {
594 self.resolve_primitive_associated_item(prim, ns, item_name).or_else(|| {
595 self.primitive_type_to_ty(prim)
597 resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
599 .map(|item| (root_res, item.def_id))
602 Res::Def(DefKind::TyAlias, did) => {
603 // Resolve the link on the type the alias points to.
604 // FIXME: if the associated item is defined directly on the type alias,
605 // it will show up on its documentation page, we should link there instead.
606 let res = self.def_id_to_res(did)?;
607 self.resolve_associated_item(res, item_name, ns, module_id)
610 def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
613 debug!("looking for associated item named {} for item {:?}", item_name, did);
614 // Checks if item_name is a variant of the `SomeItem` enum
615 if ns == TypeNS && def_kind == DefKind::Enum {
616 match tcx.type_of(did).kind() {
617 ty::Adt(adt_def, _) => {
618 for variant in adt_def.variants() {
619 if variant.name == item_name {
620 return Some((root_res, variant.def_id));
628 // Checks if item_name belongs to `impl SomeItem`
633 tcx.associated_items(imp).find_by_name_and_namespace(
635 Ident::with_dummy_span(item_name),
641 // There should only ever be one associated item that matches from any inherent impl
643 // Check if item_name belongs to `impl SomeTrait for SomeItem`
644 // FIXME(#74563): This gives precedence to `impl SomeItem`:
645 // Although having both would be ambiguous, use impl version for compatibility's sake.
646 // To handle that properly resolve() would have to support
647 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
649 resolve_associated_trait_item(
658 debug!("got associated item {:?}", assoc_item);
660 if let Some(item) = assoc_item {
661 return Some((root_res, item.def_id));
664 if ns != Namespace::ValueNS {
667 debug!("looking for fields named {} for {:?}", item_name, did);
668 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
669 // NOTE: it's different from variant_field because it only resolves struct fields,
670 // not variant fields (2 path segments, not 3).
672 // We need to handle struct (and union) fields in this code because
673 // syntactically their paths are identical to associated item paths:
674 // `module::Type::field` and `module::Type::Assoc`.
676 // On the other hand, variant fields can't be mistaken for associated
677 // items because they look like this: `module::Type::Variant::field`.
679 // Variants themselves don't need to be handled here, even though
680 // they also look like associated items (`module::Type::Variant`),
681 // because they are real Rust syntax (unlike the intra-doc links
682 // field syntax) and are handled by the compiler's resolver.
683 let def = match tcx.type_of(did).kind() {
684 ty::Adt(def, _) if !def.is_enum() => def,
688 def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?;
689 Some((root_res, field.did))
691 Res::Def(DefKind::Trait, did) => tcx
692 .associated_items(did)
693 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
695 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
703 fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
704 assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
707 /// Look to see if a resolved item has an associated item named `item_name`.
709 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
710 /// find `std::error::Error::source` and return
711 /// `<io::Error as error::Error>::source`.
712 fn resolve_associated_trait_item<'a>(
717 cx: &mut DocContext<'a>,
718 ) -> Option<ty::AssocItem> {
719 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
720 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
721 // meantime, just don't look for these blanket impls.
723 // Next consider explicit impls: `impl MyTrait for MyType`
724 // Give precedence to inherent impls.
725 let traits = trait_impls_for(cx, ty, module);
726 debug!("considering traits {:?}", traits);
727 let mut candidates = traits.iter().filter_map(|&(impl_, trait_)| {
729 .associated_items(trait_)
730 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
732 trait_assoc_to_impl_assoc_item(cx.tcx, impl_, trait_assoc.def_id)
733 .unwrap_or(trait_assoc)
736 // FIXME(#74563): warn about ambiguity
737 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
738 candidates.next().copied()
741 /// Find the associated item in the impl `impl_id` that corresponds to the
742 /// trait associated item `trait_assoc_id`.
744 /// This function returns `None` if no associated item was found in the impl.
745 /// This can occur when the trait associated item has a default value that is
746 /// not overridden in the impl.
748 /// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
749 /// [`TyCtxt::associated_item()`] (with some helpful logging added).
750 #[instrument(level = "debug", skip(tcx))]
751 fn trait_assoc_to_impl_assoc_item<'tcx>(
754 trait_assoc_id: DefId,
755 ) -> Option<&'tcx ty::AssocItem> {
756 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
757 debug!(?trait_to_impl_assoc_map);
758 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
759 debug!(?impl_assoc_id);
760 let impl_assoc = tcx.associated_item(impl_assoc_id);
765 /// Given a type, return all trait impls in scope in `module` for that type.
766 /// Returns a set of pairs of `(impl_id, trait_id)`.
768 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
769 /// So it is not stable to serialize cross-crate.
770 #[instrument(level = "debug", skip(cx))]
771 fn trait_impls_for<'a>(
772 cx: &mut DocContext<'a>,
775 ) -> FxHashSet<(DefId, DefId)> {
777 let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
778 let trait_ = trait_candidate.def_id;
779 trace!("considering explicit impl for trait {:?}", trait_);
781 // Look at each trait implementation to see if it's an impl for `did`
782 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
783 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
784 // Check if these are the same type.
785 let impl_type = trait_ref.self_ty();
787 "comparing type {} with kind {:?} against type {:?}",
792 // Fast path: if this is a primitive simple `==` will work
793 // NOTE: the `match` is necessary; see #92662.
794 // this allows us to ignore generics because the user input
795 // may not include the generic placeholders
796 // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
797 let saw_impl = impl_type == ty
798 || match (impl_type.kind(), ty.kind()) {
799 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
800 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
801 impl_def.did() == ty_def.did()
806 if saw_impl { Some((impl_, trait_)) } else { None }
812 /// Check for resolve collisions between a trait and its derive.
814 /// These are common and we should just resolve to the trait in that case.
815 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
819 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
820 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
826 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
827 fn visit_item(&mut self, item: &Item) {
829 item.item_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
830 if parent_node.is_some() {
831 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.item_id);
834 let inner_docs = item.inner_docs(self.cx.tcx);
836 if item.is_mod() && inner_docs {
837 self.mod_ids.push(item.item_id.expect_def_id());
840 // We want to resolve in the lexical scope of the documentation.
841 // In the presence of re-exports, this is not the same as the module of the item.
842 // Rather than merging all documentation into one, resolve it one attribute at a time
843 // so we know which module it came from.
844 for (parent_module, doc) in item.attrs.prepare_to_doc_link_resolution() {
845 if !may_have_doc_links(&doc) {
848 debug!("combined_docs={}", doc);
849 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
850 // This is a degenerate case and it's not supported by rustdoc.
851 let parent_node = parent_module.or(parent_node);
852 let mut tmp_links = self
857 .expect("`markdown_links` are already borrowed");
858 if !tmp_links.contains_key(&doc) {
859 tmp_links.insert(doc.clone(), preprocessed_markdown_links(&doc));
861 for md_link in &tmp_links[&doc] {
862 let link = self.resolve_link(item, &doc, parent_node, md_link);
863 if let Some(link) = link {
864 self.cx.cache.intra_doc_links.entry(item.item_id).or_default().push(link);
867 self.cx.resolver_caches.markdown_links = Some(tmp_links);
872 self.mod_ids.push(item.item_id.expect_def_id());
875 self.visit_item_recur(item);
878 self.visit_item_recur(item)
883 enum PreprocessingError {
884 /// User error: `[std#x#y]` is not valid
886 Disambiguator(Range<usize>, String),
887 MalformedGenerics(MalformedGenerics, String),
890 impl PreprocessingError {
891 fn report(&self, cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
893 PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info),
894 PreprocessingError::Disambiguator(range, msg) => {
895 disambiguator_error(cx, diag_info, range.clone(), msg)
897 PreprocessingError::MalformedGenerics(err, path_str) => {
898 report_malformed_generics(cx, diag_info, *err, path_str)
905 struct PreprocessingInfo {
907 disambiguator: Option<Disambiguator>,
908 extra_fragment: Option<String>,
912 // Not a typedef to avoid leaking several private structures from this module.
913 pub(crate) struct PreprocessedMarkdownLink(
914 Result<PreprocessingInfo, PreprocessingError>,
919 /// - `None` if the link should be ignored.
920 /// - `Some(Err)` if the link should emit an error
921 /// - `Some(Ok)` if the link is valid
923 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
925 ori_link: &MarkdownLink,
926 ) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
927 // [] is mostly likely not supposed to be a link
928 if ori_link.link.is_empty() {
932 // Bail early for real links.
933 if ori_link.link.contains('/') {
937 let stripped = ori_link.link.replace('`', "");
938 let mut parts = stripped.split('#');
940 let link = parts.next().unwrap();
941 if link.trim().is_empty() {
942 // This is an anchor to an element of the current page, nothing to do in here!
945 let extra_fragment = parts.next();
946 if parts.next().is_some() {
947 // A valid link can't have multiple #'s
948 return Some(Err(PreprocessingError::MultipleAnchors));
951 // Parse and strip the disambiguator from the link, if present.
952 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
953 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
954 Ok(None) => (None, link.trim(), link.trim()),
955 Err((err_msg, relative_range)) => {
956 // Only report error if we would not have ignored this link. See issue #83859.
957 if !should_ignore_link_with_disambiguators(link) {
958 let no_backticks_range = range_between_backticks(ori_link);
959 let disambiguator_range = (no_backticks_range.start + relative_range.start)
960 ..(no_backticks_range.start + relative_range.end);
961 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
968 if should_ignore_link(path_str) {
972 // Strip generics from the path.
973 let path_str = if path_str.contains(['<', '>'].as_slice()) {
974 match strip_generics_from_path(path_str) {
977 debug!("link has malformed generics: {}", path_str);
978 return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
985 // Sanity check to make sure we don't have any angle brackets after stripping generics.
986 assert!(!path_str.contains(['<', '>'].as_slice()));
988 // The link is not an intra-doc link if it still contains spaces after stripping generics.
989 if path_str.contains(' ') {
993 Some(Ok(PreprocessingInfo {
996 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
997 link_text: link_text.to_owned(),
1001 fn preprocessed_markdown_links(s: &str) -> Vec<PreprocessedMarkdownLink> {
1002 markdown_links(s, |link| {
1003 preprocess_link(&link).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1007 impl LinkCollector<'_, '_> {
1008 /// This is the entry point for resolving an intra-doc link.
1010 /// FIXME(jynelson): this is way too many arguments
1015 parent_node: Option<DefId>,
1016 link: &PreprocessedMarkdownLink,
1017 ) -> Option<ItemLink> {
1018 let PreprocessedMarkdownLink(pp_link, ori_link) = link;
1019 trace!("considering link '{}'", ori_link.link);
1021 let diag_info = DiagnosticInfo {
1024 ori_link: &ori_link.link,
1025 link_range: ori_link.range.clone(),
1028 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1029 pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1030 let disambiguator = *disambiguator;
1032 // In order to correctly resolve intra-doc links we need to
1033 // pick a base AST node to work from. If the documentation for
1034 // this module came from an inner comment (//!) then we anchor
1035 // our name resolution *inside* the module. If, on the other
1036 // hand it was an outer comment (///) then we anchor the name
1037 // resolution in the parent module on the basis that the names
1038 // used are more likely to be intended to be parent names. For
1039 // this, we set base_node to None for inner comments since
1040 // we've already pushed this node onto the resolution stack but
1041 // for outer comments we explicitly try and resolve against the
1042 // parent_node first.
1043 let inner_docs = item.inner_docs(self.cx.tcx);
1045 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1046 let module_id = base_node.expect("doc link without parent module");
1048 let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1050 item_id: item.item_id,
1053 path_str: path_str.to_owned(),
1054 extra_fragment: extra_fragment.clone(),
1056 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1057 // For reference-style links we want to report only one error so unsuccessful
1058 // resolutions are cached, for other links we want to report an error every
1059 // time so they are not cached.
1060 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1063 // Check for a primitive which might conflict with a module
1064 // Report the ambiguity and require that the user specify which one they meant.
1065 // FIXME: could there ever be a primitive not in the type namespace?
1068 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1069 ) && !matches!(res, Res::Primitive(_))
1071 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1073 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1076 // `[char]` when a `char` module is in scope
1077 let candidates = vec![res, prim];
1078 ambiguity_error(self.cx, diag_info, path_str, candidates);
1085 Res::Primitive(prim) => {
1086 if let Some(UrlFragment::Item(id)) = fragment {
1087 // We're actually resolving an associated item of a primitive, so we need to
1088 // verify the disambiguator (if any) matches the type of the associated item.
1089 // This case should really follow the same flow as the `Res::Def` branch below,
1090 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1091 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1092 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1093 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1094 // for discussion on the matter.
1095 let kind = self.cx.tcx.def_kind(id);
1096 self.verify_disambiguator(
1106 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1107 // However I'm not sure how to check that across crates.
1108 if prim == PrimitiveType::RawPointer
1109 && item.item_id.is_local()
1110 && !self.cx.tcx.features().intra_doc_pointers
1112 self.report_rawptr_assoc_feature_gate(dox, ori_link, item);
1115 match disambiguator {
1116 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1118 self.report_disambiguator_mismatch(
1119 path_str, ori_link, other, res, &diag_info,
1127 link: ori_link.link.clone(),
1128 link_text: link_text.clone(),
1129 did: res.def_id(self.cx.tcx),
1133 Res::Def(kind, id) => {
1134 let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1135 (self.cx.tcx.def_kind(id), id)
1139 self.verify_disambiguator(
1148 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1150 link: ori_link.link.clone(),
1151 link_text: link_text.clone(),
1159 fn verify_disambiguator(
1162 ori_link: &MarkdownLink,
1165 disambiguator: Option<Disambiguator>,
1167 diag_info: &DiagnosticInfo<'_>,
1169 debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1171 // Disallow e.g. linking to enums with `struct@`
1172 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1173 match (kind, disambiguator) {
1174 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1175 // NOTE: this allows 'method' to mean both normal functions and associated functions
1176 // This can't cause ambiguity because both are in the same namespace.
1177 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1178 // These are namespaces; allow anything in the namespace to match
1179 | (_, Some(Disambiguator::Namespace(_)))
1180 // If no disambiguator given, allow anything
1182 // All of these are valid, so do nothing
1184 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1185 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1186 self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1191 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1192 if let Some((src_id, dst_id)) = id
1194 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1195 // would presumably panic if a fake `DefIndex` were passed.
1196 .and_then(|dst_id| {
1197 item.item_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1200 if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1201 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1203 privacy_error(self.cx, diag_info, path_str);
1210 fn report_disambiguator_mismatch(
1213 ori_link: &MarkdownLink,
1214 specified: Disambiguator,
1216 diag_info: &DiagnosticInfo<'_>,
1218 // The resolved item did not match the disambiguator; give a better error than 'not found'
1219 let msg = format!("incompatible link kind for `{}`", path_str);
1220 let callback = |diag: &mut Diagnostic, sp: Option<rustc_span::Span>| {
1222 "this link resolved to {} {}, which is not {} {}",
1225 specified.article(),
1228 if let Some(sp) = sp {
1229 diag.span_label(sp, ¬e);
1233 suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1235 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, diag_info, callback);
1238 fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1240 super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1241 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1242 rustc_session::parse::feature_err(
1243 &self.cx.tcx.sess.parse_sess,
1244 sym::intra_doc_pointers,
1246 "linking to associated items of raw pointers is experimental",
1248 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1252 fn resolve_with_disambiguator_cached(
1254 key: ResolutionInfo,
1255 diag: DiagnosticInfo<'_>,
1256 // If errors are cached then they are only reported on first ocurrence
1257 // which we want in some cases but not in others.
1259 ) -> Option<(Res, Option<UrlFragment>)> {
1260 if let Some(res) = self.visited_links.get(&key) {
1261 if res.is_some() || cache_errors {
1266 let res = self.resolve_with_disambiguator(&key, diag.clone()).and_then(|(res, def_id)| {
1267 let fragment = match (&key.extra_fragment, def_id) {
1268 (Some(_), Some(def_id)) => {
1269 report_anchor_conflict(self.cx, diag, def_id);
1272 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1273 (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1274 (None, None) => None,
1276 Some((res, fragment))
1279 if res.is_some() || cache_errors {
1280 self.visited_links.insert(key, res.clone());
1285 /// After parsing the disambiguator, resolve the main part of the link.
1286 // FIXME(jynelson): wow this is just so much
1287 fn resolve_with_disambiguator(
1289 key: &ResolutionInfo,
1290 diag: DiagnosticInfo<'_>,
1291 ) -> Option<(Res, Option<DefId>)> {
1292 let disambiguator = key.dis;
1293 let path_str = &key.path_str;
1294 let item_id = key.item_id;
1295 let base_node = key.module_id;
1297 match disambiguator.map(Disambiguator::ns) {
1298 Some(expected_ns) => {
1299 match self.resolve(path_str, expected_ns, item_id, base_node) {
1300 Ok(res) => Some(res),
1302 // We only looked in one namespace. Try to give a better error if possible.
1303 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`.
1304 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach.
1305 let mut err = ResolutionFailure::NotResolved(err);
1306 for other_ns in [TypeNS, ValueNS, MacroNS] {
1307 if other_ns != expected_ns {
1309 self.resolve(path_str, other_ns, item_id, base_node)
1311 err = ResolutionFailure::WrongNamespace {
1312 res: full_res(self.cx.tcx, res),
1319 resolution_failure(self, diag, path_str, disambiguator, smallvec![err])
1325 let mut candidate = |ns| {
1326 self.resolve(path_str, ns, item_id, base_node)
1327 .map_err(ResolutionFailure::NotResolved)
1330 let candidates = PerNS {
1331 macro_ns: candidate(MacroNS),
1332 type_ns: candidate(TypeNS),
1333 value_ns: candidate(ValueNS).and_then(|(res, def_id)| {
1335 // Constructors are picked up in the type namespace.
1336 Res::Def(DefKind::Ctor(..), _) => {
1337 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1339 _ => Ok((res, def_id)),
1344 let len = candidates.iter().filter(|res| res.is_ok()).count();
1347 return resolution_failure(
1352 candidates.into_iter().filter_map(|res| res.err()).collect(),
1357 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1358 } else if len == 2 && is_derive_trait_collision(&candidates) {
1359 Some(candidates.type_ns.unwrap())
1361 let ignore_macro = is_derive_trait_collision(&candidates);
1362 // If we're reporting an ambiguity, don't mention the namespaces that failed
1363 let mut candidates =
1364 candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1366 candidates.macro_ns = None;
1368 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1376 /// Get the section of a link between the backticks,
1377 /// or the whole link if there aren't any backticks.
1385 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1386 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1387 let before_second_backtick_group = ori_link
1390 .skip(after_first_backtick_group)
1391 .position(|b| b == b'`')
1392 .unwrap_or(ori_link.link.len());
1393 (ori_link.range.start + after_first_backtick_group)
1394 ..(ori_link.range.start + before_second_backtick_group)
1397 /// Returns true if we should ignore `link` due to it being unlikely
1398 /// that it is an intra-doc link. `link` should still have disambiguators
1399 /// if there were any.
1401 /// The difference between this and [`should_ignore_link()`] is that this
1402 /// check should only be used on links that still have disambiguators.
1403 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1404 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1407 /// Returns true if we should ignore `path_str` due to it being unlikely
1408 /// that it is an intra-doc link.
1409 fn should_ignore_link(path_str: &str) -> bool {
1410 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1413 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1414 /// Disambiguators for a link.
1415 enum Disambiguator {
1418 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1420 /// `struct@` or `f()`
1423 Namespace(Namespace),
1426 impl Disambiguator {
1427 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1429 /// This returns `Ok(Some(...))` if a disambiguator was found,
1430 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1431 /// if there was a problem with the disambiguator.
1432 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1433 use Disambiguator::{Kind, Namespace as NS, Primitive};
1435 if let Some(idx) = link.find('@') {
1436 let (prefix, rest) = link.split_at(idx);
1437 let d = match prefix {
1438 "struct" => Kind(DefKind::Struct),
1439 "enum" => Kind(DefKind::Enum),
1440 "trait" => Kind(DefKind::Trait),
1441 "union" => Kind(DefKind::Union),
1442 "module" | "mod" => Kind(DefKind::Mod),
1443 "const" | "constant" => Kind(DefKind::Const),
1444 "static" => Kind(DefKind::Static(Mutability::Not)),
1445 "function" | "fn" | "method" => Kind(DefKind::Fn),
1446 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1447 "type" => NS(Namespace::TypeNS),
1448 "value" => NS(Namespace::ValueNS),
1449 "macro" => NS(Namespace::MacroNS),
1450 "prim" | "primitive" => Primitive,
1451 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1453 Ok(Some((d, &rest[1..], &rest[1..])))
1456 ("!()", DefKind::Macro(MacroKind::Bang)),
1457 ("!{}", DefKind::Macro(MacroKind::Bang)),
1458 ("![]", DefKind::Macro(MacroKind::Bang)),
1459 ("()", DefKind::Fn),
1460 ("!", DefKind::Macro(MacroKind::Bang)),
1462 for (suffix, kind) in suffixes {
1463 if let Some(path_str) = link.strip_suffix(suffix) {
1464 // Avoid turning `!` or `()` into an empty string
1465 if !path_str.is_empty() {
1466 return Ok(Some((Kind(kind), path_str, link)));
1474 fn ns(self) -> Namespace {
1476 Self::Namespace(n) => n,
1478 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1480 Self::Primitive => TypeNS,
1484 fn article(self) -> &'static str {
1486 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1487 Self::Kind(k) => k.article(),
1488 Self::Primitive => "a",
1492 fn descr(self) -> &'static str {
1494 Self::Namespace(n) => n.descr(),
1495 // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1496 // printing "module" vs "crate" so using the wrong ID is not a huge problem
1497 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1498 Self::Primitive => "builtin type",
1503 /// A suggestion to show in a diagnostic.
1506 Prefix(&'static str),
1511 /// `foo` without any disambiguator
1512 RemoveDisambiguator,
1516 fn descr(&self) -> Cow<'static, str> {
1518 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1519 Self::Function => "add parentheses".into(),
1520 Self::Macro => "add an exclamation mark".into(),
1521 Self::RemoveDisambiguator => "remove the disambiguator".into(),
1525 fn as_help(&self, path_str: &str) -> String {
1526 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1528 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1529 Self::Function => format!("{}()", path_str),
1530 Self::Macro => format!("{}!", path_str),
1531 Self::RemoveDisambiguator => path_str.into(),
1539 sp: rustc_span::Span,
1540 ) -> Vec<(rustc_span::Span, String)> {
1541 let inner_sp = match ori_link.find('(') {
1542 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1545 let inner_sp = match ori_link.find('!') {
1546 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1549 let inner_sp = match ori_link.find('@') {
1550 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1554 Self::Prefix(prefix) => {
1555 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1556 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1557 if sp.hi() != inner_sp.hi() {
1558 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1563 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1564 if sp.lo() != inner_sp.lo() {
1565 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1570 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1571 if sp.lo() != inner_sp.lo() {
1572 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1576 Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1581 /// Reports a diagnostic for an intra-doc link.
1583 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1584 /// the entire documentation block is used for the lint. If a range is provided but the span
1585 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1587 /// The `decorate` callback is invoked in all cases to allow further customization of the
1588 /// diagnostic before emission. If the span of the link was able to be determined, the second
1589 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1591 fn report_diagnostic(
1593 lint: &'static Lint,
1595 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1596 decorate: impl FnOnce(&mut Diagnostic, Option<rustc_span::Span>),
1598 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id)
1600 // If non-local, no need to check anything.
1601 info!("ignoring warning from parent crate: {}", msg);
1605 let sp = item.attr_span(tcx);
1607 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1608 let mut diag = lint.build(msg);
1611 super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1612 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1613 && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1615 sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1621 if let Some(sp) = span {
1624 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1627 // last_new_line_offset
1628 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1629 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1631 // Print the line containing the `link_range` and manually mark it with '^'s.
1633 "the link appears in this line:\n\n{line}\n\
1634 {indicator: <before$}{indicator:^<found$}",
1637 before = link_range.start - last_new_line_offset,
1638 found = link_range.len(),
1642 decorate(&mut diag, span);
1648 /// Reports a link that failed to resolve.
1650 /// This also tries to resolve any intermediate path segments that weren't
1651 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1652 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1653 fn resolution_failure(
1654 collector: &mut LinkCollector<'_, '_>,
1655 diag_info: DiagnosticInfo<'_>,
1657 disambiguator: Option<Disambiguator>,
1658 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1659 ) -> Option<(Res, Option<DefId>)> {
1660 let tcx = collector.cx.tcx;
1661 let mut recovered_res = None;
1664 BROKEN_INTRA_DOC_LINKS,
1665 &format!("unresolved link to `{}`", path_str),
1668 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1669 let assoc_item_not_allowed = |res: Res| {
1670 let name = res.name(tcx);
1672 "`{}` is {} {}, not a module or type, and cannot have associated items",
1678 // ignore duplicates
1679 let mut variants_seen = SmallVec::<[_; 3]>::new();
1680 for mut failure in kinds {
1681 let variant = std::mem::discriminant(&failure);
1682 if variants_seen.contains(&variant) {
1685 variants_seen.push(variant);
1687 if let ResolutionFailure::NotResolved(UnresolvedPath {
1696 let item_id = *item_id;
1697 let module_id = *module_id;
1698 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1699 // FIXME: maybe use itertools `collect_tuple` instead?
1700 fn split(path: &str) -> Option<(&str, &str)> {
1701 let mut splitter = path.rsplitn(2, "::");
1702 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1705 // Check if _any_ parent of the path gets resolved.
1706 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1707 let mut name = path_str;
1709 let Some((start, end)) = split(name) else {
1710 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1711 if partial_res.is_none() {
1712 *unresolved = name.into();
1717 for ns in [TypeNS, ValueNS, MacroNS] {
1718 if let Ok(res) = collector.resolve(start, ns, item_id, module_id) {
1719 debug!("found partial_res={:?}", res);
1720 *partial_res = Some(full_res(collector.cx.tcx, res));
1721 *unresolved = end.into();
1725 *unresolved = end.into();
1728 let last_found_module = match *partial_res {
1729 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1730 None => Some(module_id),
1733 // See if this was a module: `[path]` or `[std::io::nope]`
1734 if let Some(module) = last_found_module {
1735 let note = if partial_res.is_some() {
1736 // Part of the link resolved; e.g. `std::io::nonexistent`
1737 let module_name = tcx.item_name(module);
1738 format!("no item named `{}` in module `{}`", unresolved, module_name)
1740 // None of the link resolved; e.g. `Notimported`
1741 format!("no item named `{}` in scope", unresolved)
1743 if let Some(span) = sp {
1744 diag.span_label(span, ¬e);
1749 if !path_str.contains("::") {
1750 if disambiguator.map_or(true, |d| d.ns() == MacroNS)
1751 && let Some(&res) = collector.cx.resolver_caches.all_macro_rules
1752 .get(&Symbol::intern(path_str))
1755 "`macro_rules` named `{path_str}` exists in this crate, \
1756 but it is not in scope at this link's location"
1758 recovered_res = res.try_into().ok().map(|res| (res, None));
1760 // If the link has `::` in it, assume it was meant to be an
1761 // intra-doc link. Otherwise, the `[]` might be unrelated.
1762 diag.help("to escape `[` and `]` characters, \
1763 add '\\' before them like `\\[` or `\\]`");
1770 // Otherwise, it must be an associated item or variant
1771 let res = partial_res.expect("None case was handled by `last_found_module`");
1772 let name = res.name(tcx);
1773 let kind = match res {
1774 Res::Def(kind, _) => Some(kind),
1775 Res::Primitive(_) => None,
1777 let path_description = if let Some(kind) = kind {
1779 Mod | ForeignMod => "inner item",
1780 Struct => "field or associated item",
1781 Enum | Union => "variant or associated item",
1799 let note = assoc_item_not_allowed(res);
1800 if let Some(span) = sp {
1801 diag.span_label(span, ¬e);
1807 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1808 | Static(_) => "associated item",
1809 Impl | GlobalAsm => unreachable!("not a path"),
1815 "the {} `{}` has no {} named `{}`",
1818 disambiguator.map_or(path_description, |d| d.descr()),
1821 if let Some(span) = sp {
1822 diag.span_label(span, ¬e);
1829 let note = match failure {
1830 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1831 ResolutionFailure::WrongNamespace { res, expected_ns } => {
1832 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
1835 "this link resolves to {}, which is not in the {} namespace",
1841 if let Some(span) = sp {
1842 diag.span_label(span, ¬e);
1853 fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
1854 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
1855 anchor_failure(cx, diag_info, &msg, 1)
1858 fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
1859 let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
1860 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
1861 anchor_failure(cx, diag_info, &msg, 0)
1864 /// Report an anchor failure.
1866 cx: &DocContext<'_>,
1867 diag_info: DiagnosticInfo<'_>,
1871 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp| {
1872 if let Some(mut sp) = sp {
1873 if let Some((fragment_offset, _)) =
1874 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
1876 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
1878 diag.span_label(sp, "invalid anchor");
1883 /// Report an error in the link disambiguator.
1884 fn disambiguator_error(
1885 cx: &DocContext<'_>,
1886 mut diag_info: DiagnosticInfo<'_>,
1887 disambiguator_range: Range<usize>,
1890 diag_info.link_range = disambiguator_range;
1891 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
1893 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
1894 crate::DOC_RUST_LANG_ORG_CHANNEL
1900 fn report_malformed_generics(
1901 cx: &DocContext<'_>,
1902 diag_info: DiagnosticInfo<'_>,
1903 err: MalformedGenerics,
1908 BROKEN_INTRA_DOC_LINKS,
1909 &format!("unresolved link to `{}`", path_str),
1912 let note = match err {
1913 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
1914 MalformedGenerics::MissingType => "missing type for generic parameters",
1915 MalformedGenerics::HasFullyQualifiedSyntax => {
1917 "see https://github.com/rust-lang/rust/issues/74563 for more information",
1919 "fully-qualified syntax is unsupported"
1921 MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
1922 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
1923 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
1925 if let Some(span) = sp {
1926 diag.span_label(span, note);
1934 /// Report an ambiguity error, where there were multiple possible resolutions.
1936 cx: &DocContext<'_>,
1937 diag_info: DiagnosticInfo<'_>,
1939 candidates: Vec<Res>,
1941 let mut msg = format!("`{}` is ", path_str);
1943 match candidates.as_slice() {
1944 [first_def, second_def] => {
1946 "both {} {} and {} {}",
1947 first_def.article(),
1949 second_def.article(),
1954 let mut candidates = candidates.iter().peekable();
1955 while let Some(res) = candidates.next() {
1956 if candidates.peek().is_some() {
1957 msg += &format!("{} {}, ", res.article(), res.descr());
1959 msg += &format!("and {} {}", res.article(), res.descr());
1965 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
1966 if let Some(sp) = sp {
1967 diag.span_label(sp, "ambiguous link");
1969 diag.note("ambiguous link");
1972 for res in candidates {
1973 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
1978 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
1980 fn suggest_disambiguator(
1982 diag: &mut Diagnostic,
1985 sp: Option<rustc_span::Span>,
1987 let suggestion = res.disambiguator_suggestion();
1988 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
1990 if let Some(sp) = sp {
1991 let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
1992 if spans.len() > 1 {
1993 diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
1995 let (sp, suggestion_text) = spans.pop().unwrap();
1996 diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
1999 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2003 /// Report a link from a public item to a private one.
2004 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2006 let item_name = match diag_info.item.name {
2011 None => "<unknown>",
2014 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2016 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2017 if let Some(sp) = sp {
2018 diag.span_label(sp, "this item is private");
2021 let note_msg = if cx.render_options.document_private {
2022 "this link resolves only because you passed `--document-private-items`, but will break without"
2024 "this link will resolve properly if you pass `--document-private-items`"
2026 diag.note(note_msg);
2030 /// Resolve a primitive type or value.
2031 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2035 use PrimitiveType::*;
2036 let prim = match path_str {
2052 "bool" | "true" | "false" => Bool,
2053 "str" | "&str" => Str,
2054 // See #80181 for why these don't have symbols associated.
2059 "pointer" | "*const" | "*mut" => RawPointer,
2060 "reference" | "&" | "&mut" => Reference,
2062 "never" | "!" => Never,
2065 debug!("resolved primitives {:?}", prim);
2066 Some(Res::Primitive(prim))
2069 fn strip_generics_from_path(path_str: &str) -> Result<String, MalformedGenerics> {
2070 let mut stripped_segments = vec![];
2071 let mut path = path_str.chars().peekable();
2072 let mut segment = Vec::new();
2074 while let Some(chr) = path.next() {
2077 if path.next_if_eq(&':').is_some() {
2078 let stripped_segment =
2079 strip_generics_from_path_segment(mem::take(&mut segment))?;
2080 if !stripped_segment.is_empty() {
2081 stripped_segments.push(stripped_segment);
2084 return Err(MalformedGenerics::InvalidPathSeparator);
2092 return Err(MalformedGenerics::TooManyAngleBrackets);
2095 return Err(MalformedGenerics::EmptyAngleBrackets);
2100 while let Some(chr) = path.next_if(|c| *c != '>') {
2107 _ => segment.push(chr),
2109 trace!("raw segment: {:?}", segment);
2112 if !segment.is_empty() {
2113 let stripped_segment = strip_generics_from_path_segment(segment)?;
2114 if !stripped_segment.is_empty() {
2115 stripped_segments.push(stripped_segment);
2119 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2121 let stripped_path = stripped_segments.join("::");
2123 if !stripped_path.is_empty() { Ok(stripped_path) } else { Err(MalformedGenerics::MissingType) }
2126 fn strip_generics_from_path_segment(segment: Vec<char>) -> Result<String, MalformedGenerics> {
2127 let mut stripped_segment = String::new();
2128 let mut param_depth = 0;
2130 let mut latest_generics_chunk = String::new();
2135 latest_generics_chunk.clear();
2136 } else if c == '>' {
2138 if latest_generics_chunk.contains(" as ") {
2139 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2140 // Give a helpful error message instead of completely ignoring the angle brackets.
2141 return Err(MalformedGenerics::HasFullyQualifiedSyntax);
2144 if param_depth == 0 {
2145 stripped_segment.push(c);
2147 latest_generics_chunk.push(c);
2152 if param_depth == 0 {
2153 Ok(stripped_segment)
2155 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2156 Err(MalformedGenerics::UnbalancedAngleBrackets)