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
6 use rustc_data_structures::{fx::FxHashMap, stable_set::FxHashSet};
7 use rustc_errors::{Applicability, DiagnosticBuilder};
8 use rustc_expand::base::SyntaxExtensionKind;
15 use rustc_hir::def_id::{CrateNum, DefId};
16 use rustc_middle::{bug, ty};
17 use rustc_resolve::ParentScope;
18 use rustc_session::lint::{
19 builtin::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS},
22 use rustc_span::hygiene::MacroKind;
23 use rustc_span::symbol::Ident;
24 use rustc_span::symbol::Symbol;
25 use rustc_span::DUMMY_SP;
26 use smallvec::{smallvec, SmallVec};
30 use std::convert::{TryFrom, TryInto};
34 use crate::clean::{self, utils::find_nearest_parent_module, Crate, Item, ItemLink, PrimitiveType};
35 use crate::core::DocContext;
36 use crate::fold::DocFolder;
37 use crate::html::markdown::markdown_links;
38 use crate::passes::Pass;
40 use super::span_of_attrs;
42 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
43 name: "collect-intra-doc-links",
44 run: collect_intra_doc_links,
45 description: "reads a crate's documentation to resolve intra-doc-links",
48 crate fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
49 LinkCollector::new(cx).fold_crate(krate)
52 /// Top-level errors emitted by this pass.
54 Resolve(Box<ResolutionFailure<'a>>),
55 AnchorFailure(AnchorFailure),
58 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
59 fn from(err: ResolutionFailure<'a>) -> Self {
60 ErrorKind::Resolve(box err)
64 #[derive(Copy, Clone, Debug, Hash)]
67 Primitive(PrimitiveType),
70 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
73 fn descr(self) -> &'static str {
75 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
76 Res::Primitive(_) => "builtin type",
80 fn article(self) -> &'static str {
82 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
83 Res::Primitive(_) => "a",
87 fn name(self, tcx: ty::TyCtxt<'_>) -> String {
89 Res::Def(_, id) => tcx.item_name(id).to_string(),
90 Res::Primitive(prim) => prim.as_str().to_string(),
94 fn def_id(self) -> DefId {
95 self.opt_def_id().expect("called def_id() on a primitive")
98 fn opt_def_id(self) -> Option<DefId> {
100 Res::Def(_, id) => Some(id),
101 Res::Primitive(_) => None,
105 fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
107 Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
108 // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
109 Res::Primitive(_) => None,
114 impl TryFrom<ResolveRes> for Res {
117 fn try_from(res: ResolveRes) -> Result<Self, ()> {
118 use rustc_hir::def::Res::*;
120 Def(kind, id) => Ok(Res::Def(kind, id)),
121 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
123 NonMacroAttr(..) | Err => Result::Err(()),
124 other => bug!("unrecognized res {:?}", other),
130 /// A link failed to resolve.
131 enum ResolutionFailure<'a> {
132 /// This resolved, but with the wrong namespace.
134 /// `Namespace` is the namespace specified with a disambiguator
135 /// (as opposed to the actual namespace of the `Res`).
136 WrongNamespace(Res, /* disambiguated */ Namespace),
137 /// The link failed to resolve. `resolution_failure` should look to see if there's
138 /// a more helpful error that can be given.
140 /// The scope the link was resolved in.
142 /// If part of the link resolved, this has the `Res`.
144 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
145 partial_res: Option<Res>,
146 /// The remaining unresolved path segments.
148 /// In `[std::io::Error::x]`, `x` would be unresolved.
149 unresolved: Cow<'a, str>,
151 /// This happens when rustdoc can't determine the parent scope for an item.
153 /// It is always a bug in rustdoc.
155 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
156 MalformedGenerics(MalformedGenerics),
157 /// Used to communicate that this should be ignored, but shouldn't be reported to the user
159 /// This happens when there is no disambiguator and one of the namespaces
160 /// failed to resolve.
165 enum MalformedGenerics {
166 /// This link has unbalanced angle brackets.
168 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
169 UnbalancedAngleBrackets,
170 /// The generics are not attached to a type.
172 /// For example, `<T>` should trigger this.
174 /// This is detected by checking if the path is empty after the generics are stripped.
176 /// The link uses fully-qualified syntax, which is currently unsupported.
178 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
180 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
182 HasFullyQualifiedSyntax,
183 /// The link has an invalid path separator.
185 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
186 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
189 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
190 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
191 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
193 /// This is detected by checking if there is a colon followed by a non-colon in the link.
194 InvalidPathSeparator,
195 /// The link has too many angle brackets.
197 /// For example, `Vec<<T>>` should trigger this.
198 TooManyAngleBrackets,
199 /// The link has empty angle brackets.
201 /// For example, `Vec<>` should trigger this.
205 impl ResolutionFailure<'a> {
206 /// This resolved fully (not just partially) but is erroneous for some other reason
208 /// Returns the full resolution of the link, if present.
209 fn full_res(&self) -> Option<Res> {
211 Self::WrongNamespace(res, _) => Some(*res),
218 /// User error: `[std#x#y]` is not valid
220 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
222 /// This is an unfortunate state of affairs. Not every item that can be
223 /// linked to has its own page; sometimes it is a subheading within a page,
224 /// like for associated items. In those cases, rustdoc uses an anchor to
225 /// link to the subheading. Since you can't have two anchors for the same
226 /// link, Rustdoc disallows having a user-specified anchor.
228 /// Most of the time this is fine, because you can just link to the page of
229 /// the item if you want to provide your own anchor. For primitives, though,
230 /// rustdoc uses the anchor as a side channel to know which page to link to;
231 /// it doesn't show up in the generated link. Ideally, rustdoc would remove
232 /// this limitation, allowing you to link to subheaders on primitives.
233 RustdocAnchorConflict(Res),
236 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
237 struct ResolutionInfo {
239 dis: Option<Disambiguator>,
241 extra_fragment: Option<String>,
244 struct DiagnosticInfo<'a> {
248 link_range: Option<Range<usize>>,
251 #[derive(Clone, Debug, Hash)]
253 pub res: (Res, Option<String>),
254 pub side_channel: Option<(DefKind, DefId)>,
257 struct LinkCollector<'a, 'tcx> {
258 cx: &'a DocContext<'tcx>,
259 /// A stack of modules used to decide what scope to resolve in.
261 /// The last module will be used if the parent scope of the current item is
264 /// This is used to store the kind of associated items,
265 /// because `clean` and the disambiguator code expect them to be different.
266 /// See the code for associated items on inherent impls for details.
267 kind_side_channel: Cell<Option<(DefKind, DefId)>>,
268 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link
269 visited_links: FxHashMap<ResolutionInfo, CachedLink>,
272 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
273 fn new(cx: &'a DocContext<'tcx>) -> Self {
277 kind_side_channel: Cell::new(None),
278 visited_links: FxHashMap::default(),
282 /// Given a full link, parse it as an [enum struct variant].
284 /// In particular, this will return an error whenever there aren't three
285 /// full path segments left in the link.
287 /// [enum struct variant]: hir::VariantData::Struct
290 path_str: &'path str,
292 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
294 let no_res = || ResolutionFailure::NotResolved {
297 unresolved: path_str.into(),
300 debug!("looking for enum variant {}", path_str);
301 let mut split = path_str.rsplitn(3, "::");
302 let (variant_field_str, variant_field_name) = split
304 .map(|f| (f, Symbol::intern(f)))
305 .expect("fold_item should ensure link is non-empty");
306 let (variant_str, variant_name) =
307 // we're not sure this is a variant at all, so use the full string
308 // If there's no second component, the link looks like `[path]`.
309 // So there's no partial res and we should say the whole link failed to resolve.
310 split.next().map(|f| (f, Symbol::intern(f))).ok_or_else(no_res)?;
313 .map(|f| f.to_owned())
314 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
315 // So there's no partial res.
316 .ok_or_else(no_res)?;
318 .enter_resolver(|resolver| {
319 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
321 .and_then(|(_, res)| res.try_into())
322 .map_err(|()| no_res())?;
325 Res::Def(DefKind::Enum, did) => {
330 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
331 .any(|item| item.ident.name == variant_name)
333 // This is just to let `fold_item` know that this shouldn't be considered;
334 // it's a bug for the error to make it to the user
335 return Err(ResolutionFailure::Dummy.into());
337 match cx.tcx.type_of(did).kind() {
338 ty::Adt(def, _) if def.is_enum() => {
339 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
343 "variant.{}.field.{}",
344 variant_str, variant_field_name
348 Err(ResolutionFailure::NotResolved {
350 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
351 unresolved: variant_field_str.into(),
359 _ => Err(ResolutionFailure::NotResolved {
361 partial_res: Some(ty_res),
362 unresolved: variant_str.into(),
368 /// Given a primitive type, try to resolve an associated item.
370 /// HACK(jynelson): `item_str` is passed in instead of derived from `item_name` so the
371 /// lifetimes on `&'path` will work.
372 fn resolve_primitive_associated_item(
374 prim_ty: PrimitiveType,
378 item_str: &'path str,
379 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
387 .associated_items(impl_)
388 .find_by_name_and_namespace(
390 Ident::with_dummy_span(item_name),
394 .map(|item| match item.kind {
395 ty::AssocKind::Fn => "method",
396 ty::AssocKind::Const => "associatedconstant",
397 ty::AssocKind::Type => "associatedtype",
401 Res::Primitive(prim_ty),
402 Some(format!("{}#{}.{}", prim_ty.as_str(), out, item_str)),
408 "returning primitive error for {}::{} in {} namespace",
413 ResolutionFailure::NotResolved {
415 partial_res: Some(Res::Primitive(prim_ty)),
416 unresolved: item_str.into(),
422 /// Resolves a string as a macro.
424 /// FIXME(jynelson): Can this be unified with `resolve()`?
429 ) -> Result<Res, ResolutionFailure<'a>> {
431 let path = ast::Path::from_ident(Ident::from_str(path_str));
432 cx.enter_resolver(|resolver| {
433 // FIXME(jynelson): does this really need 3 separate lookups?
434 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
437 &ParentScope::module(resolver.graph_root(), resolver),
441 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
442 return Ok(res.try_into().unwrap());
445 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
446 return Ok(res.try_into().unwrap());
448 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
449 if let Ok((_, res)) =
450 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
452 // don't resolve builtins like `#[derive]`
453 if let Ok(res) = res.try_into() {
457 Err(ResolutionFailure::NotResolved {
460 unresolved: path_str.into(),
465 /// Convenience wrapper around `resolve_str_path_error`.
467 /// This also handles resolving `true` and `false` as booleans.
468 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
469 /// Associated items will never be resolved by this function.
470 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
471 let result = self.cx.enter_resolver(|resolver| {
473 .resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
474 .and_then(|(_, res)| res.try_into())
476 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
478 // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
480 Err(()) => resolve_primitive(path_str, ns),
481 Ok(res) => Some(res),
485 /// Resolves a string as a path within a particular namespace. Returns an
486 /// optional URL fragment in the case of variants and methods.
489 path_str: &'path str,
492 extra_fragment: &Option<String>,
493 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
496 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
498 // FIXME(#76467): make this fallthrough to lookup the associated
499 // item a separate function.
500 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => {
501 assert_eq!(ns, ValueNS);
503 Res::Def(DefKind::AssocTy, _) => {
504 assert_eq!(ns, TypeNS);
506 Res::Def(DefKind::Variant, _) => {
507 return handle_variant(cx, res, extra_fragment);
509 // Not a trait item; just return what we found.
510 Res::Primitive(ty) => {
511 if extra_fragment.is_some() {
512 return Err(ErrorKind::AnchorFailure(
513 AnchorFailure::RustdocAnchorConflict(res),
516 return Ok((res, Some(ty.as_str().to_owned())));
518 Res::Def(DefKind::Mod, _) => {
519 return Ok((res, extra_fragment.clone()));
522 return Ok((res, extra_fragment.clone()));
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);
540 ResolutionFailure::NotResolved {
543 unresolved: item_str.into(),
547 // FIXME: are these both necessary?
548 let ty_res = if let Some(ty_res) = resolve_primitive(&path_root, TypeNS)
549 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
553 // FIXME: this is duplicated on the end of this function.
554 return if ns == Namespace::ValueNS {
555 self.variant_field(path_str, module_id)
557 Err(ResolutionFailure::NotResolved {
560 unresolved: path_root.into(),
566 let res = match ty_res {
567 Res::Primitive(prim) => Some(
568 self.resolve_primitive_associated_item(prim, ns, module_id, item_name, item_str),
575 | DefKind::ForeignTy,
578 debug!("looking for associated item named {} for item {:?}", item_name, did);
579 // Checks if item_name belongs to `impl SomeItem`
585 cx.tcx.associated_items(imp).find_by_name_and_namespace(
587 Ident::with_dummy_span(item_name),
592 .map(|item| (item.kind, item.def_id))
593 // There should only ever be one associated item that matches from any inherent impl
595 // Check if item_name belongs to `impl SomeTrait for SomeItem`
596 // FIXME(#74563): This gives precedence to `impl SomeItem`:
597 // Although having both would be ambiguous, use impl version for compatibility's sake.
598 // To handle that properly resolve() would have to support
599 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
602 resolve_associated_trait_item(did, module_id, item_name, ns, &self.cx);
603 debug!("got associated item kind {:?}", kind);
607 if let Some((kind, id)) = assoc_item {
608 let out = match kind {
609 ty::AssocKind::Fn => "method",
610 ty::AssocKind::Const => "associatedconstant",
611 ty::AssocKind::Type => "associatedtype",
613 Some(if extra_fragment.is_some() {
614 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
616 // HACK(jynelson): `clean` expects the type, not the associated item
617 // but the disambiguator logic expects the associated item.
618 // Store the kind in a side channel so that only the disambiguator logic looks at it.
619 self.kind_side_channel.set(Some((kind.as_def_kind(), id)));
620 Ok((ty_res, Some(format!("{}.{}", out, item_str))))
622 } else if ns == Namespace::ValueNS {
623 debug!("looking for variants or fields named {} for {:?}", item_name, did);
624 // FIXME(jynelson): why is this different from
626 match cx.tcx.type_of(did).kind() {
628 let field = if def.is_enum() {
629 def.all_fields().find(|item| item.ident.name == item_name)
631 def.non_enum_variant()
634 .find(|item| item.ident.name == item_name)
637 if extra_fragment.is_some() {
646 Err(ErrorKind::AnchorFailure(
647 AnchorFailure::RustdocAnchorConflict(res),
654 if def.is_enum() { "variant" } else { "structfield" },
667 Res::Def(DefKind::Trait, did) => cx
669 .associated_items(did)
670 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, did)
672 let kind = match item.kind {
673 ty::AssocKind::Const => "associatedconstant",
674 ty::AssocKind::Type => "associatedtype",
675 ty::AssocKind::Fn => {
676 if item.defaultness.has_value() {
684 if extra_fragment.is_some() {
685 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
687 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
688 Ok((res, Some(format!("{}.{}", kind, item_str))))
693 res.unwrap_or_else(|| {
694 if ns == Namespace::ValueNS {
695 self.variant_field(path_str, module_id)
697 Err(ResolutionFailure::NotResolved {
699 partial_res: Some(ty_res),
700 unresolved: item_str.into(),
707 /// Used for reporting better errors.
709 /// Returns whether the link resolved 'fully' in another namespace.
710 /// 'fully' here means that all parts of the link resolved, not just some path segments.
711 /// This returns the `Res` even if it was erroneous for some reason
712 /// (such as having invalid URL fragments or being in the wrong namespace).
718 extra_fragment: &Option<String>,
720 // resolve() can't be used for macro namespace
721 let result = match ns {
722 Namespace::MacroNS => self.resolve_macro(path_str, module_id).map_err(ErrorKind::from),
723 Namespace::TypeNS | Namespace::ValueNS => {
724 self.resolve(path_str, ns, module_id, extra_fragment).map(|(res, _)| res)
728 let res = match result {
729 Ok(res) => Some(res),
730 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
731 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
732 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
734 self.kind_side_channel.take().map(|(kind, id)| Res::Def(kind, id)).or(res)
738 /// Look to see if a resolved item has an associated item named `item_name`.
740 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
741 /// find `std::error::Error::source` and return
742 /// `<io::Error as error::Error>::source`.
743 fn resolve_associated_trait_item(
749 ) -> Option<(ty::AssocKind, DefId)> {
750 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
751 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
752 // meantime, just don't look for these blanket impls.
754 // Next consider explicit impls: `impl MyTrait for MyType`
755 // Give precedence to inherent impls.
756 let traits = traits_implemented_by(cx, did, module);
757 debug!("considering traits {:?}", traits);
758 let mut candidates = traits.iter().filter_map(|&trait_| {
760 .associated_items(trait_)
761 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
762 .map(|assoc| (assoc.kind, assoc.def_id))
764 // FIXME(#74563): warn about ambiguity
765 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
769 /// Given a type, return all traits in scope in `module` implemented by that type.
771 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
772 /// So it is not stable to serialize cross-crate.
773 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
774 let mut cache = cx.module_trait_cache.borrow_mut();
775 let in_scope_traits = cache.entry(module).or_insert_with(|| {
776 cx.enter_resolver(|resolver| {
777 resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
781 let ty = cx.tcx.type_of(type_);
782 let iter = in_scope_traits.iter().flat_map(|&trait_| {
783 trace!("considering explicit impl for trait {:?}", trait_);
785 // Look at each trait implementation to see if it's an impl for `did`
786 cx.tcx.find_map_relevant_impl(trait_, ty, |impl_| {
787 let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
788 // Check if these are the same type.
789 let impl_type = trait_ref.self_ty();
791 "comparing type {} with kind {:?} against type {:?}",
796 // Fast path: if this is a primitive simple `==` will work
797 let saw_impl = impl_type == ty
798 || match impl_type.kind() {
799 // Check if these are the same def_id
801 debug!("adt def_id: {:?}", def.did);
804 ty::Foreign(def_id) => *def_id == type_,
808 if saw_impl { Some(trait_) } else { None }
814 /// Check for resolve collisions between a trait and its derive.
816 /// These are common and we should just resolve to the trait in that case.
817 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
821 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
822 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
828 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
829 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
830 use rustc_middle::ty::DefIdTree;
832 let parent_node = if item.is_fake() {
835 find_nearest_parent_module(self.cx.tcx, item.def_id)
838 if parent_node.is_some() {
839 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
842 // find item's parent to resolve `Self` in item's docs below
843 debug!("looking for the `Self` type");
844 let self_id = if item.is_fake() {
847 self.cx.tcx.def_kind(item.def_id),
854 self.cx.tcx.parent(item.def_id)
855 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
856 // Fixing this breaks `fn render_deref_methods`.
857 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
858 // regardless of what rustdoc wants to call it.
859 } else if let Some(parent) = self.cx.tcx.parent(item.def_id) {
860 let parent_kind = self.cx.tcx.def_kind(parent);
861 Some(if parent_kind == DefKind::Impl { parent } else { item.def_id })
866 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
867 let self_name = self_id.and_then(|self_id| {
869 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
870 // using `ty.to_string()` (or any variant) has issues with raw idents
871 let ty = self.cx.tcx.type_of(self_id);
872 let name = match ty.kind() {
873 TyKind::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
874 other if other.is_primitive() => Some(ty.to_string()),
877 debug!("using type_of(): {:?}", name);
880 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
881 debug!("using item_name(): {:?}", name);
886 if item.is_mod() && item.attrs.inner_docs {
887 self.mod_ids.push(item.def_id);
890 // We want to resolve in the lexical scope of the documentation.
891 // In the presence of re-exports, this is not the same as the module of the item.
892 // Rather than merging all documentation into one, resolve it one attribute at a time
893 // so we know which module it came from.
894 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
895 debug!("combined_docs={}", doc);
897 let (krate, parent_node) = if let Some(id) = parent_module {
900 (item.def_id.krate, parent_node)
902 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
903 // This is a degenerate case and it's not supported by rustdoc.
904 for (ori_link, link_range) in markdown_links(&doc) {
905 let link = self.resolve_link(
914 if let Some(link) = link {
915 item.attrs.links.push(link);
920 Some(if item.is_mod() {
921 if !item.attrs.inner_docs {
922 self.mod_ids.push(item.def_id);
925 let ret = self.fold_item_recur(item);
929 self.fold_item_recur(item)
934 impl LinkCollector<'_, '_> {
935 /// This is the entry point for resolving an intra-doc link.
937 /// FIXME(jynelson): this is way too many arguments
942 self_name: &Option<String>,
943 parent_node: Option<DefId>,
946 link_range: Option<Range<usize>>,
947 ) -> Option<ItemLink> {
948 trace!("considering link '{}'", ori_link);
950 // Bail early for real links.
951 if ori_link.contains('/') {
955 // [] is mostly likely not supposed to be a link
956 if ori_link.is_empty() {
961 let link = ori_link.replace("`", "");
962 let parts = link.split('#').collect::<Vec<_>>();
963 let (link, extra_fragment) = if parts.len() > 2 {
964 // A valid link can't have multiple #'s
965 anchor_failure(cx, &item, &link, dox, link_range, AnchorFailure::MultipleAnchors);
967 } else if parts.len() == 2 {
968 if parts[0].trim().is_empty() {
969 // This is an anchor to an element of the current page, nothing to do in here!
972 (parts[0], Some(parts[1].to_owned()))
977 // Parse and strip the disambiguator from the link, if present.
978 let (mut path_str, disambiguator) = if let Ok((d, path)) = Disambiguator::from_str(&link) {
979 (path.trim(), Some(d))
984 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch))) {
988 // We stripped `()` and `!` when parsing the disambiguator.
989 // Add them back to be displayed, but not prefix disambiguators.
991 disambiguator.map(|d| d.display_for(path_str)).unwrap_or_else(|| path_str.to_owned());
993 // In order to correctly resolve intra-doc-links we need to
994 // pick a base AST node to work from. If the documentation for
995 // this module came from an inner comment (//!) then we anchor
996 // our name resolution *inside* the module. If, on the other
997 // hand it was an outer comment (///) then we anchor the name
998 // resolution in the parent module on the basis that the names
999 // used are more likely to be intended to be parent names. For
1000 // this, we set base_node to None for inner comments since
1001 // we've already pushed this node onto the resolution stack but
1002 // for outer comments we explicitly try and resolve against the
1003 // parent_node first.
1004 let base_node = if item.is_mod() && item.attrs.inner_docs {
1005 self.mod_ids.last().copied()
1010 let mut module_id = if let Some(id) = base_node {
1014 debug!("attempting to resolve item without parent module: {}", path_str);
1022 smallvec![ResolutionFailure::NoParentItem],
1028 // replace `Self` with suitable item's parent name
1029 if path_str.starts_with("Self::") {
1030 if let Some(ref name) = self_name {
1031 resolved_self = format!("{}::{}", name, &path_str[6..]);
1032 path_str = &resolved_self;
1034 } else if path_str.starts_with("crate::") {
1035 use rustc_span::def_id::CRATE_DEF_INDEX;
1037 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1038 // But rustdoc wants it to mean the crate this item was originally present in.
1039 // To work around this, remove it and resolve relative to the crate root instead.
1040 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1041 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1042 // FIXME(#78696): This doesn't always work.
1043 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1044 path_str = &resolved_self;
1045 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1048 // Strip generics from the path.
1049 let stripped_path_string;
1050 if path_str.contains(['<', '>'].as_slice()) {
1051 stripped_path_string = match strip_generics_from_path(path_str) {
1054 debug!("link has malformed generics: {}", path_str);
1062 smallvec![err_kind],
1067 path_str = &stripped_path_string;
1069 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1070 assert!(!path_str.contains(['<', '>'].as_slice()));
1072 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1073 if path_str.contains(' ') {
1077 let key = ResolutionInfo {
1080 path_str: path_str.to_owned(),
1084 DiagnosticInfo { item, dox, ori_link: &ori_link, link_range: link_range.clone() };
1085 let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(key, diag)?;
1087 // Check for a primitive which might conflict with a module
1088 // Report the ambiguity and require that the user specify which one they meant.
1089 // FIXME: could there ever be a primitive not in the type namespace?
1092 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1093 ) && !matches!(res, Res::Primitive(_))
1095 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1097 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1098 if fragment.is_some() {
1105 AnchorFailure::RustdocAnchorConflict(prim),
1110 fragment = Some(prim.name(self.cx.tcx));
1112 // `[char]` when a `char` module is in scope
1113 let candidates = vec![res, prim];
1114 ambiguity_error(cx, &item, path_str, dox, link_range, candidates);
1120 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1121 // The resolved item did not match the disambiguator; give a better error than 'not found'
1122 let msg = format!("incompatible link kind for `{}`", path_str);
1123 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1125 "this link resolved to {} {}, which is not {} {}",
1128 specified.article(),
1132 suggest_disambiguator(resolved, diag, path_str, dox, sp, &link_range);
1134 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, &item, dox, &link_range, callback);
1137 Res::Primitive(_) => match disambiguator {
1138 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
1139 Some(ItemLink { link: ori_link, link_text, did: None, fragment })
1142 report_mismatch(other, Disambiguator::Primitive);
1146 Res::Def(kind, id) => {
1147 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
1149 // Disallow e.g. linking to enums with `struct@`
1150 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1151 match (self.kind_side_channel.take().map(|(kind, _)| kind).unwrap_or(kind), disambiguator) {
1152 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1153 // NOTE: this allows 'method' to mean both normal functions and associated functions
1154 // This can't cause ambiguity because both are in the same namespace.
1155 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1156 // These are namespaces; allow anything in the namespace to match
1157 | (_, Some(Disambiguator::Namespace(_)))
1158 // If no disambiguator given, allow anything
1160 // All of these are valid, so do nothing
1162 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1163 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1164 report_mismatch(specified, Disambiguator::Kind(kind));
1169 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1170 if let Some((src_id, dst_id)) = id
1172 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
1174 use rustc_hir::def_id::LOCAL_CRATE;
1176 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1177 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1179 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
1180 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
1182 privacy_error(cx, &item, &path_str, dox, link_range);
1185 let id = clean::register_res(cx, rustc_hir::def::Res::Def(kind, id));
1186 Some(ItemLink { link: ori_link, link_text, did: Some(id), fragment })
1191 fn resolve_with_disambiguator_cached(
1193 key: ResolutionInfo,
1194 diag: DiagnosticInfo<'_>,
1195 ) -> Option<(Res, Option<String>)> {
1196 // Try to look up both the result and the corresponding side channel value
1197 if let Some(ref cached) = self.visited_links.get(&key) {
1198 self.kind_side_channel.set(cached.side_channel);
1199 return Some(cached.res.clone());
1202 let res = self.resolve_with_disambiguator(&key, diag);
1204 // Cache only if resolved successfully - don't silence duplicate errors
1205 if let Some(res) = &res {
1206 // Store result for the actual namespace
1207 self.visited_links.insert(
1211 side_channel: self.kind_side_channel.clone().into_inner(),
1219 /// After parsing the disambiguator, resolve the main part of the link.
1220 // FIXME(jynelson): wow this is just so much
1221 fn resolve_with_disambiguator(
1223 key: &ResolutionInfo,
1224 diag: DiagnosticInfo<'_>,
1225 ) -> Option<(Res, Option<String>)> {
1226 let disambiguator = key.dis;
1227 let path_str = &key.path_str;
1228 let base_node = key.module_id;
1229 let extra_fragment = &key.extra_fragment;
1231 match disambiguator.map(Disambiguator::ns) {
1232 Some(ns @ (ValueNS | TypeNS)) => {
1233 match self.resolve(path_str, ns, base_node, extra_fragment) {
1234 Ok(res) => Some(res),
1235 Err(ErrorKind::Resolve(box mut kind)) => {
1236 // We only looked in one namespace. Try to give a better error if possible.
1237 if kind.full_res().is_none() {
1238 let other_ns = if ns == ValueNS { TypeNS } else { ValueNS };
1239 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1240 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1241 for &new_ns in &[other_ns, MacroNS] {
1243 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1245 kind = ResolutionFailure::WrongNamespace(res, ns);
1259 // This could just be a normal link or a broken link
1260 // we could potentially check if something is
1261 // "intra-doc-link-like" and warn in that case.
1264 Err(ErrorKind::AnchorFailure(msg)) => {
1279 let mut candidates = PerNS {
1281 .resolve_macro(path_str, base_node)
1282 .map(|res| (res, extra_fragment.clone())),
1283 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1285 debug!("got res in TypeNS: {:?}", res);
1288 Err(ErrorKind::AnchorFailure(msg)) => {
1299 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1301 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1303 Err(ErrorKind::AnchorFailure(msg)) => {
1314 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1316 .and_then(|(res, fragment)| {
1317 // Constructors are picked up in the type namespace.
1319 Res::Def(DefKind::Ctor(..), _) => {
1320 Err(ResolutionFailure::WrongNamespace(res, TypeNS))
1323 match (fragment, extra_fragment.clone()) {
1324 (Some(fragment), Some(_)) => {
1325 // Shouldn't happen but who knows?
1326 Ok((res, Some(fragment)))
1328 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1335 let len = candidates.iter().filter(|res| res.is_ok()).count();
1345 candidates.into_iter().filter_map(|res| res.err()).collect(),
1347 // this could just be a normal link
1352 Some(candidates.into_iter().filter_map(|res| res.ok()).next().unwrap())
1353 } else if len == 2 && is_derive_trait_collision(&candidates) {
1354 Some(candidates.type_ns.unwrap())
1356 if is_derive_trait_collision(&candidates) {
1357 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1359 // If we're reporting an ambiguity, don't mention the namespaces that failed
1360 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1367 candidates.present_items().collect(),
1373 match self.resolve_macro(path_str, base_node) {
1374 Ok(res) => Some((res, extra_fragment.clone())),
1376 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1377 for &ns in &[TypeNS, ValueNS] {
1379 self.check_full_res(ns, path_str, base_node, extra_fragment)
1381 kind = ResolutionFailure::WrongNamespace(res, MacroNS);
1402 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1403 /// Disambiguators for a link.
1404 enum Disambiguator {
1407 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1409 /// `struct@` or `f()`
1412 Namespace(Namespace),
1415 impl Disambiguator {
1416 /// The text that should be displayed when the path is rendered as HTML.
1418 /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1419 fn display_for(&self, path: &str) -> String {
1421 // FIXME: this will have different output if the user had `m!()` originally.
1422 Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1423 Self::Kind(DefKind::Fn) => format!("{}()", path),
1424 _ => path.to_owned(),
1428 /// Given a link, parse and return `(disambiguator, path_str)`
1429 fn from_str(link: &str) -> Result<(Self, &str), ()> {
1430 use Disambiguator::{Kind, Namespace as NS, Primitive};
1432 let find_suffix = || {
1434 ("!()", DefKind::Macro(MacroKind::Bang)),
1435 ("()", DefKind::Fn),
1436 ("!", DefKind::Macro(MacroKind::Bang)),
1438 for &(suffix, kind) in &suffixes {
1439 if let Some(link) = link.strip_suffix(suffix) {
1440 // Avoid turning `!` or `()` into an empty string
1441 if !link.is_empty() {
1442 return Ok((Kind(kind), link));
1449 if let Some(idx) = link.find('@') {
1450 let (prefix, rest) = link.split_at(idx);
1451 let d = match prefix {
1452 "struct" => Kind(DefKind::Struct),
1453 "enum" => Kind(DefKind::Enum),
1454 "trait" => Kind(DefKind::Trait),
1455 "union" => Kind(DefKind::Union),
1456 "module" | "mod" => Kind(DefKind::Mod),
1457 "const" | "constant" => Kind(DefKind::Const),
1458 "static" => Kind(DefKind::Static),
1459 "function" | "fn" | "method" => Kind(DefKind::Fn),
1460 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1461 "type" => NS(Namespace::TypeNS),
1462 "value" => NS(Namespace::ValueNS),
1463 "macro" => NS(Namespace::MacroNS),
1464 "prim" | "primitive" => Primitive,
1465 _ => return find_suffix(),
1473 fn from_res(res: Res) -> Self {
1475 Res::Def(kind, _) => Disambiguator::Kind(kind),
1476 Res::Primitive(_) => Disambiguator::Primitive,
1480 /// Used for error reporting.
1481 fn suggestion(self) -> Suggestion {
1482 let kind = match self {
1483 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1484 Disambiguator::Kind(kind) => kind,
1485 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1487 if kind == DefKind::Macro(MacroKind::Bang) {
1488 return Suggestion::Macro;
1489 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1490 return Suggestion::Function;
1493 let prefix = match kind {
1494 DefKind::Struct => "struct",
1495 DefKind::Enum => "enum",
1496 DefKind::Trait => "trait",
1497 DefKind::Union => "union",
1498 DefKind::Mod => "mod",
1499 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1502 DefKind::Static => "static",
1503 DefKind::Macro(MacroKind::Derive) => "derive",
1504 // Now handle things that don't have a specific disambiguator
1507 .expect("tried to calculate a disambiguator for a def without a namespace?")
1509 Namespace::TypeNS => "type",
1510 Namespace::ValueNS => "value",
1511 Namespace::MacroNS => "macro",
1515 Suggestion::Prefix(prefix)
1518 fn ns(self) -> Namespace {
1520 Self::Namespace(n) => n,
1522 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1524 Self::Primitive => TypeNS,
1528 fn article(self) -> &'static str {
1530 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1531 Self::Kind(k) => k.article(),
1532 Self::Primitive => "a",
1536 fn descr(self) -> &'static str {
1538 Self::Namespace(n) => n.descr(),
1539 // HACK(jynelson): by looking at the source I saw the DefId we pass
1540 // for `expected.descr()` doesn't matter, since it's not a crate
1541 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1542 Self::Primitive => "builtin type",
1547 /// A suggestion to show in a diagnostic.
1550 Prefix(&'static str),
1558 fn descr(&self) -> Cow<'static, str> {
1560 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1561 Self::Function => "add parentheses".into(),
1562 Self::Macro => "add an exclamation mark".into(),
1566 fn as_help(&self, path_str: &str) -> String {
1567 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1569 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1570 Self::Function => format!("{}()", path_str),
1571 Self::Macro => format!("{}!", path_str),
1576 /// Reports a diagnostic for an intra-doc link.
1578 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1579 /// the entire documentation block is used for the lint. If a range is provided but the span
1580 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1582 /// The `decorate` callback is invoked in all cases to allow further customization of the
1583 /// diagnostic before emission. If the span of the link was able to be determined, the second
1584 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1586 fn report_diagnostic(
1587 cx: &DocContext<'_>,
1588 lint: &'static Lint,
1592 link_range: &Option<Range<usize>>,
1593 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1595 let hir_id = match cx.as_local_hir_id(item.def_id) {
1596 Some(hir_id) => hir_id,
1598 // If non-local, no need to check anything.
1599 info!("ignoring warning from parent crate: {}", msg);
1604 let attrs = &item.attrs;
1605 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1607 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1608 let mut diag = lint.build(msg);
1610 let span = link_range
1612 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
1614 if let Some(link_range) = link_range {
1615 if let Some(sp) = span {
1618 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1621 // last_new_line_offset
1622 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1623 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1625 // Print the line containing the `link_range` and manually mark it with '^'s.
1627 "the link appears in this line:\n\n{line}\n\
1628 {indicator: <before$}{indicator:^<found$}",
1631 before = link_range.start - last_new_line_offset,
1632 found = link_range.len(),
1637 decorate(&mut diag, span);
1643 /// Reports a link that failed to resolve.
1645 /// This also tries to resolve any intermediate path segments that weren't
1646 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1647 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1648 fn resolution_failure(
1649 collector: &LinkCollector<'_, '_>,
1652 disambiguator: Option<Disambiguator>,
1654 link_range: Option<Range<usize>>,
1655 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1657 let tcx = collector.cx.tcx;
1660 BROKEN_INTRA_DOC_LINKS,
1661 &format!("unresolved link to `{}`", path_str),
1666 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1667 let assoc_item_not_allowed = |res: Res| {
1668 let name = res.name(tcx);
1670 "`{}` is {} {}, not a module or type, and cannot have associated items",
1676 // ignore duplicates
1677 let mut variants_seen = SmallVec::<[_; 3]>::new();
1678 for mut failure in kinds {
1679 let variant = std::mem::discriminant(&failure);
1680 if variants_seen.contains(&variant) {
1683 variants_seen.push(variant);
1685 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1690 let module_id = *module_id;
1691 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1692 // FIXME: maybe use itertools `collect_tuple` instead?
1693 fn split(path: &str) -> Option<(&str, &str)> {
1694 let mut splitter = path.rsplitn(2, "::");
1695 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1698 // Check if _any_ parent of the path gets resolved.
1699 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1700 let mut name = path_str;
1702 let (start, end) = if let Some(x) = split(name) {
1705 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1706 if partial_res.is_none() {
1707 *unresolved = name.into();
1712 for &ns in &[TypeNS, ValueNS, MacroNS] {
1714 collector.check_full_res(ns, &start, module_id, &None)
1716 debug!("found partial_res={:?}", res);
1717 *partial_res = Some(res);
1718 *unresolved = end.into();
1722 *unresolved = end.into();
1725 let last_found_module = match *partial_res {
1726 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1727 None => Some(module_id),
1730 // See if this was a module: `[path]` or `[std::io::nope]`
1731 if let Some(module) = last_found_module {
1732 let note = if partial_res.is_some() {
1733 // Part of the link resolved; e.g. `std::io::nonexistent`
1734 let module_name = tcx.item_name(module);
1735 format!("no item named `{}` in module `{}`", unresolved, module_name)
1737 // None of the link resolved; e.g. `Notimported`
1738 format!("no item named `{}` in scope", unresolved)
1740 if let Some(span) = sp {
1741 diag.span_label(span, ¬e);
1746 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1747 // Otherwise, the `[]` might be unrelated.
1748 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1749 if !path_str.contains("::") {
1750 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1756 // Otherwise, it must be an associated item or variant
1757 let res = partial_res.expect("None case was handled by `last_found_module`");
1758 let name = res.name(tcx);
1759 let kind = match res {
1760 Res::Def(kind, _) => Some(kind),
1761 Res::Primitive(_) => None,
1763 let path_description = if let Some(kind) = kind {
1765 Mod | ForeignMod => "inner item",
1766 Struct => "field or associated item",
1767 Enum | Union => "variant or associated item",
1784 let note = assoc_item_not_allowed(res);
1785 if let Some(span) = sp {
1786 diag.span_label(span, ¬e);
1792 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1793 | Static => "associated item",
1794 Impl | GlobalAsm => unreachable!("not a path"),
1800 "the {} `{}` has no {} named `{}`",
1803 disambiguator.map_or(path_description, |d| d.descr()),
1806 if let Some(span) = sp {
1807 diag.span_label(span, ¬e);
1814 let note = match failure {
1815 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1816 ResolutionFailure::Dummy => continue,
1817 ResolutionFailure::WrongNamespace(res, expected_ns) => {
1818 if let Res::Def(kind, _) = res {
1819 let disambiguator = Disambiguator::Kind(kind);
1820 suggest_disambiguator(
1831 "this link resolves to {}, which is not in the {} namespace",
1836 ResolutionFailure::NoParentItem => {
1837 diag.level = rustc_errors::Level::Bug;
1838 "all intra doc links should have a parent item".to_owned()
1840 ResolutionFailure::MalformedGenerics(variant) => match variant {
1841 MalformedGenerics::UnbalancedAngleBrackets => {
1842 String::from("unbalanced angle brackets")
1844 MalformedGenerics::MissingType => {
1845 String::from("missing type for generic parameters")
1847 MalformedGenerics::HasFullyQualifiedSyntax => {
1848 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1849 String::from("fully-qualified syntax is unsupported")
1851 MalformedGenerics::InvalidPathSeparator => {
1852 String::from("has invalid path separator")
1854 MalformedGenerics::TooManyAngleBrackets => {
1855 String::from("too many angle brackets")
1857 MalformedGenerics::EmptyAngleBrackets => {
1858 String::from("empty angle brackets")
1862 if let Some(span) = sp {
1863 diag.span_label(span, ¬e);
1872 /// Report an anchor failure.
1874 cx: &DocContext<'_>,
1878 link_range: Option<Range<usize>>,
1879 failure: AnchorFailure,
1881 let msg = match failure {
1882 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1883 AnchorFailure::RustdocAnchorConflict(res) => format!(
1884 "`{}` contains an anchor, but links to {kind}s are already anchored",
1890 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1891 if let Some(sp) = sp {
1892 diag.span_label(sp, "contains invalid anchor");
1897 /// Report an ambiguity error, where there were multiple possible resolutions.
1899 cx: &DocContext<'_>,
1903 link_range: Option<Range<usize>>,
1904 candidates: Vec<Res>,
1906 let mut msg = format!("`{}` is ", path_str);
1908 match candidates.as_slice() {
1909 [first_def, second_def] => {
1911 "both {} {} and {} {}",
1912 first_def.article(),
1914 second_def.article(),
1919 let mut candidates = candidates.iter().peekable();
1920 while let Some(res) = candidates.next() {
1921 if candidates.peek().is_some() {
1922 msg += &format!("{} {}, ", res.article(), res.descr());
1924 msg += &format!("and {} {}", res.article(), res.descr());
1930 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1931 if let Some(sp) = sp {
1932 diag.span_label(sp, "ambiguous link");
1934 diag.note("ambiguous link");
1937 for res in candidates {
1938 let disambiguator = Disambiguator::from_res(res);
1939 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1944 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
1946 fn suggest_disambiguator(
1947 disambiguator: Disambiguator,
1948 diag: &mut DiagnosticBuilder<'_>,
1951 sp: Option<rustc_span::Span>,
1952 link_range: &Option<Range<usize>>,
1954 let suggestion = disambiguator.suggestion();
1955 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
1957 if let Some(sp) = sp {
1958 let link_range = link_range.as_ref().expect("must have a link range if we have a span");
1959 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
1960 format!("`{}`", suggestion.as_help(path_str))
1962 suggestion.as_help(path_str)
1965 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
1967 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
1971 /// Report a link from a public item to a private one.
1973 cx: &DocContext<'_>,
1977 link_range: Option<Range<usize>>,
1980 let item_name = match item.name {
1982 sym = name.as_str();
1985 None => "<unknown>",
1988 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1990 report_diagnostic(cx, PRIVATE_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1991 if let Some(sp) = sp {
1992 diag.span_label(sp, "this item is private");
1995 let note_msg = if cx.render_options.document_private {
1996 "this link resolves only because you passed `--document-private-items`, but will break without"
1998 "this link will resolve properly if you pass `--document-private-items`"
2000 diag.note(note_msg);
2004 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2006 cx: &DocContext<'_>,
2008 extra_fragment: &Option<String>,
2009 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
2010 use rustc_middle::ty::DefIdTree;
2012 if extra_fragment.is_some() {
2013 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2016 .parent(res.def_id())
2018 let parent_def = Res::Def(DefKind::Enum, parent);
2019 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2020 (parent_def, Some(format!("variant.{}", variant.ident.name)))
2022 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2025 /// Resolve a primitive type or value.
2026 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2030 use PrimitiveType::*;
2031 let prim = match path_str {
2047 "bool" | "true" | "false" => Bool,
2049 // See #80181 for why these don't have symbols associated.
2054 "pointer" | "*" | "*const" | "*mut" => RawPointer,
2055 "reference" | "&" | "&mut" => Reference,
2057 "never" | "!" => Never,
2060 debug!("resolved primitives {:?}", prim);
2061 Some(Res::Primitive(prim))
2064 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2065 let mut stripped_segments = vec![];
2066 let mut path = path_str.chars().peekable();
2067 let mut segment = Vec::new();
2069 while let Some(chr) = path.next() {
2072 if path.next_if_eq(&':').is_some() {
2073 let stripped_segment =
2074 strip_generics_from_path_segment(mem::take(&mut segment))?;
2075 if !stripped_segment.is_empty() {
2076 stripped_segments.push(stripped_segment);
2079 return Err(ResolutionFailure::MalformedGenerics(
2080 MalformedGenerics::InvalidPathSeparator,
2089 return Err(ResolutionFailure::MalformedGenerics(
2090 MalformedGenerics::TooManyAngleBrackets,
2094 return Err(ResolutionFailure::MalformedGenerics(
2095 MalformedGenerics::EmptyAngleBrackets,
2101 while let Some(chr) = path.next_if(|c| *c != '>') {
2108 _ => segment.push(chr),
2110 trace!("raw segment: {:?}", segment);
2113 if !segment.is_empty() {
2114 let stripped_segment = strip_generics_from_path_segment(segment)?;
2115 if !stripped_segment.is_empty() {
2116 stripped_segments.push(stripped_segment);
2120 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2122 let stripped_path = stripped_segments.join("::");
2124 if !stripped_path.is_empty() {
2127 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2131 fn strip_generics_from_path_segment(
2133 ) -> Result<String, ResolutionFailure<'static>> {
2134 let mut stripped_segment = String::new();
2135 let mut param_depth = 0;
2137 let mut latest_generics_chunk = String::new();
2142 latest_generics_chunk.clear();
2143 } else if c == '>' {
2145 if latest_generics_chunk.contains(" as ") {
2146 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2147 // Give a helpful error message instead of completely ignoring the angle brackets.
2148 return Err(ResolutionFailure::MalformedGenerics(
2149 MalformedGenerics::HasFullyQualifiedSyntax,
2153 if param_depth == 0 {
2154 stripped_segment.push(c);
2156 latest_generics_chunk.push(c);
2161 if param_depth == 0 {
2162 Ok(stripped_segment)
2164 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2165 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))