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};
28 use pulldown_cmark::LinkType;
32 use std::convert::{TryFrom, TryInto};
36 use crate::clean::{self, utils::find_nearest_parent_module, Crate, Item, ItemLink, PrimitiveType};
37 use crate::core::DocContext;
38 use crate::fold::DocFolder;
39 use crate::html::markdown::{markdown_links, MarkdownLink};
40 use crate::passes::Pass;
42 use super::span_of_attrs;
44 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
45 name: "collect-intra-doc-links",
46 run: collect_intra_doc_links,
47 description: "reads a crate's documentation to resolve intra-doc-links",
50 crate fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
51 LinkCollector::new(cx).fold_crate(krate)
54 /// Top-level errors emitted by this pass.
56 Resolve(Box<ResolutionFailure<'a>>),
57 AnchorFailure(AnchorFailure),
60 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
61 fn from(err: ResolutionFailure<'a>) -> Self {
62 ErrorKind::Resolve(box err)
66 #[derive(Copy, Clone, Debug, Hash)]
69 Primitive(PrimitiveType),
72 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
75 fn descr(self) -> &'static str {
77 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
78 Res::Primitive(_) => "builtin type",
82 fn article(self) -> &'static str {
84 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
85 Res::Primitive(_) => "a",
89 fn name(self, tcx: ty::TyCtxt<'_>) -> String {
91 Res::Def(_, id) => tcx.item_name(id).to_string(),
92 Res::Primitive(prim) => prim.as_str().to_string(),
96 fn def_id(self) -> DefId {
97 self.opt_def_id().expect("called def_id() on a primitive")
100 fn opt_def_id(self) -> Option<DefId> {
102 Res::Def(_, id) => Some(id),
103 Res::Primitive(_) => None,
107 fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
109 Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
110 // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
111 Res::Primitive(_) => None,
116 impl TryFrom<ResolveRes> for Res {
119 fn try_from(res: ResolveRes) -> Result<Self, ()> {
120 use rustc_hir::def::Res::*;
122 Def(kind, id) => Ok(Res::Def(kind, id)),
123 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
125 NonMacroAttr(..) | Err => Result::Err(()),
126 other => bug!("unrecognized res {:?}", other),
132 /// A link failed to resolve.
133 enum ResolutionFailure<'a> {
134 /// This resolved, but with the wrong namespace.
136 /// `Namespace` is the namespace specified with a disambiguator
137 /// (as opposed to the actual namespace of the `Res`).
138 WrongNamespace(Res, /* disambiguated */ Namespace),
139 /// The link failed to resolve. `resolution_failure` should look to see if there's
140 /// a more helpful error that can be given.
142 /// The scope the link was resolved in.
144 /// If part of the link resolved, this has the `Res`.
146 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
147 partial_res: Option<Res>,
148 /// The remaining unresolved path segments.
150 /// In `[std::io::Error::x]`, `x` would be unresolved.
151 unresolved: Cow<'a, str>,
153 /// This happens when rustdoc can't determine the parent scope for an item.
155 /// It is always a bug in rustdoc.
157 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
158 MalformedGenerics(MalformedGenerics),
159 /// Used to communicate that this should be ignored, but shouldn't be reported to the user
161 /// This happens when there is no disambiguator and one of the namespaces
162 /// failed to resolve.
167 enum MalformedGenerics {
168 /// This link has unbalanced angle brackets.
170 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
171 UnbalancedAngleBrackets,
172 /// The generics are not attached to a type.
174 /// For example, `<T>` should trigger this.
176 /// This is detected by checking if the path is empty after the generics are stripped.
178 /// The link uses fully-qualified syntax, which is currently unsupported.
180 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
182 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
184 HasFullyQualifiedSyntax,
185 /// The link has an invalid path separator.
187 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
188 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
191 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
192 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
193 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
195 /// This is detected by checking if there is a colon followed by a non-colon in the link.
196 InvalidPathSeparator,
197 /// The link has too many angle brackets.
199 /// For example, `Vec<<T>>` should trigger this.
200 TooManyAngleBrackets,
201 /// The link has empty angle brackets.
203 /// For example, `Vec<>` should trigger this.
207 impl ResolutionFailure<'a> {
208 /// This resolved fully (not just partially) but is erroneous for some other reason
210 /// Returns the full resolution of the link, if present.
211 fn full_res(&self) -> Option<Res> {
213 Self::WrongNamespace(res, _) => Some(*res),
220 /// User error: `[std#x#y]` is not valid
222 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
224 /// This is an unfortunate state of affairs. Not every item that can be
225 /// linked to has its own page; sometimes it is a subheading within a page,
226 /// like for associated items. In those cases, rustdoc uses an anchor to
227 /// link to the subheading. Since you can't have two anchors for the same
228 /// link, Rustdoc disallows having a user-specified anchor.
230 /// Most of the time this is fine, because you can just link to the page of
231 /// the item if you want to provide your own anchor. For primitives, though,
232 /// rustdoc uses the anchor as a side channel to know which page to link to;
233 /// it doesn't show up in the generated link. Ideally, rustdoc would remove
234 /// this limitation, allowing you to link to subheaders on primitives.
235 RustdocAnchorConflict(Res),
238 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
239 struct ResolutionInfo {
241 dis: Option<Disambiguator>,
243 extra_fragment: Option<String>,
246 struct DiagnosticInfo<'a> {
250 link_range: Range<usize>,
253 #[derive(Clone, Debug, Hash)]
255 pub res: (Res, Option<String>),
256 pub side_channel: Option<(DefKind, DefId)>,
259 struct LinkCollector<'a, 'tcx> {
260 cx: &'a DocContext<'tcx>,
261 /// A stack of modules used to decide what scope to resolve in.
263 /// The last module will be used if the parent scope of the current item is
266 /// This is used to store the kind of associated items,
267 /// because `clean` and the disambiguator code expect them to be different.
268 /// See the code for associated items on inherent impls for details.
269 kind_side_channel: Cell<Option<(DefKind, DefId)>>,
270 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
271 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
272 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
275 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
276 fn new(cx: &'a DocContext<'tcx>) -> Self {
280 kind_side_channel: Cell::new(None),
281 visited_links: FxHashMap::default(),
285 /// Given a full link, parse it as an [enum struct variant].
287 /// In particular, this will return an error whenever there aren't three
288 /// full path segments left in the link.
290 /// [enum struct variant]: hir::VariantData::Struct
293 path_str: &'path str,
295 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
297 let no_res = || ResolutionFailure::NotResolved {
300 unresolved: path_str.into(),
303 debug!("looking for enum variant {}", path_str);
304 let mut split = path_str.rsplitn(3, "::");
305 let (variant_field_str, variant_field_name) = split
307 .map(|f| (f, Symbol::intern(f)))
308 .expect("fold_item should ensure link is non-empty");
309 let (variant_str, variant_name) =
310 // we're not sure this is a variant at all, so use the full string
311 // If there's no second component, the link looks like `[path]`.
312 // So there's no partial res and we should say the whole link failed to resolve.
313 split.next().map(|f| (f, Symbol::intern(f))).ok_or_else(no_res)?;
316 .map(|f| f.to_owned())
317 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
318 // So there's no partial res.
319 .ok_or_else(no_res)?;
321 .enter_resolver(|resolver| {
322 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
324 .and_then(|(_, res)| res.try_into())
325 .map_err(|()| no_res())?;
328 Res::Def(DefKind::Enum, did) => {
333 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
334 .any(|item| item.ident.name == variant_name)
336 // This is just to let `fold_item` know that this shouldn't be considered;
337 // it's a bug for the error to make it to the user
338 return Err(ResolutionFailure::Dummy.into());
340 match cx.tcx.type_of(did).kind() {
341 ty::Adt(def, _) if def.is_enum() => {
342 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
346 "variant.{}.field.{}",
347 variant_str, variant_field_name
351 Err(ResolutionFailure::NotResolved {
353 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
354 unresolved: variant_field_str.into(),
362 _ => Err(ResolutionFailure::NotResolved {
364 partial_res: Some(ty_res),
365 unresolved: variant_str.into(),
371 /// Given a primitive type, try to resolve an associated item.
373 /// HACK(jynelson): `item_str` is passed in instead of derived from `item_name` so the
374 /// lifetimes on `&'path` will work.
375 fn resolve_primitive_associated_item(
377 prim_ty: PrimitiveType,
381 item_str: &'path str,
382 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
390 .associated_items(impl_)
391 .find_by_name_and_namespace(
393 Ident::with_dummy_span(item_name),
397 .map(|item| match item.kind {
398 ty::AssocKind::Fn => "method",
399 ty::AssocKind::Const => "associatedconstant",
400 ty::AssocKind::Type => "associatedtype",
404 Res::Primitive(prim_ty),
405 Some(format!("{}#{}.{}", prim_ty.as_str(), out, item_str)),
411 "returning primitive error for {}::{} in {} namespace",
416 ResolutionFailure::NotResolved {
418 partial_res: Some(Res::Primitive(prim_ty)),
419 unresolved: item_str.into(),
425 /// Resolves a string as a macro.
427 /// FIXME(jynelson): Can this be unified with `resolve()`?
432 ) -> Result<Res, ResolutionFailure<'a>> {
434 let path = ast::Path::from_ident(Ident::from_str(path_str));
435 cx.enter_resolver(|resolver| {
436 // FIXME(jynelson): does this really need 3 separate lookups?
437 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
440 &ParentScope::module(resolver.graph_root(), resolver),
444 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
445 return Ok(res.try_into().unwrap());
448 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
449 return Ok(res.try_into().unwrap());
451 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
452 if let Ok((_, res)) =
453 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
455 // don't resolve builtins like `#[derive]`
456 if let Ok(res) = res.try_into() {
460 Err(ResolutionFailure::NotResolved {
463 unresolved: path_str.into(),
468 /// Convenience wrapper around `resolve_str_path_error`.
470 /// This also handles resolving `true` and `false` as booleans.
471 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
472 /// Associated items will never be resolved by this function.
473 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
474 let result = self.cx.enter_resolver(|resolver| {
476 .resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
477 .and_then(|(_, res)| res.try_into())
479 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
481 // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
483 Err(()) => resolve_primitive(path_str, ns),
484 Ok(res) => Some(res),
488 /// Resolves a string as a path within a particular namespace. Returns an
489 /// optional URL fragment in the case of variants and methods.
492 path_str: &'path str,
495 extra_fragment: &Option<String>,
496 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
499 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
501 // FIXME(#76467): make this fallthrough to lookup the associated
502 // item a separate function.
503 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => {
504 assert_eq!(ns, ValueNS);
506 Res::Def(DefKind::AssocTy, _) => {
507 assert_eq!(ns, TypeNS);
509 Res::Def(DefKind::Variant, _) => {
510 return handle_variant(cx, res, extra_fragment);
512 // Not a trait item; just return what we found.
513 Res::Primitive(ty) => {
514 if extra_fragment.is_some() {
515 return Err(ErrorKind::AnchorFailure(
516 AnchorFailure::RustdocAnchorConflict(res),
519 return Ok((res, Some(ty.as_str().to_owned())));
521 Res::Def(DefKind::Mod, _) => {
522 return Ok((res, extra_fragment.clone()));
525 return Ok((res, extra_fragment.clone()));
530 // Try looking for methods and associated items.
531 let mut split = path_str.rsplitn(2, "::");
532 // NB: `split`'s first element is always defined, even if the delimiter was not present.
533 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
534 let item_str = split.next().unwrap();
535 let item_name = Symbol::intern(item_str);
536 let path_root = split
538 .map(|f| f.to_owned())
539 // If there's no `::`, it's not an associated item.
540 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
542 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
543 ResolutionFailure::NotResolved {
546 unresolved: item_str.into(),
550 // FIXME: are these both necessary?
551 let ty_res = if let Some(ty_res) = resolve_primitive(&path_root, TypeNS)
552 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
556 // FIXME: this is duplicated on the end of this function.
557 return if ns == Namespace::ValueNS {
558 self.variant_field(path_str, module_id)
560 Err(ResolutionFailure::NotResolved {
563 unresolved: path_root.into(),
569 let res = match ty_res {
570 Res::Primitive(prim) => Some(
571 self.resolve_primitive_associated_item(prim, ns, module_id, item_name, item_str),
578 | DefKind::ForeignTy,
581 debug!("looking for associated item named {} for item {:?}", item_name, did);
582 // Checks if item_name belongs to `impl SomeItem`
588 cx.tcx.associated_items(imp).find_by_name_and_namespace(
590 Ident::with_dummy_span(item_name),
595 .map(|item| (item.kind, item.def_id))
596 // There should only ever be one associated item that matches from any inherent impl
598 // Check if item_name belongs to `impl SomeTrait for SomeItem`
599 // FIXME(#74563): This gives precedence to `impl SomeItem`:
600 // Although having both would be ambiguous, use impl version for compatibility's sake.
601 // To handle that properly resolve() would have to support
602 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
605 resolve_associated_trait_item(did, module_id, item_name, ns, &self.cx);
606 debug!("got associated item kind {:?}", kind);
610 if let Some((kind, id)) = assoc_item {
611 let out = match kind {
612 ty::AssocKind::Fn => "method",
613 ty::AssocKind::Const => "associatedconstant",
614 ty::AssocKind::Type => "associatedtype",
616 Some(if extra_fragment.is_some() {
617 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
619 // HACK(jynelson): `clean` expects the type, not the associated item
620 // but the disambiguator logic expects the associated item.
621 // Store the kind in a side channel so that only the disambiguator logic looks at it.
622 self.kind_side_channel.set(Some((kind.as_def_kind(), id)));
623 Ok((ty_res, Some(format!("{}.{}", out, item_str))))
625 } else if ns == Namespace::ValueNS {
626 debug!("looking for variants or fields named {} for {:?}", item_name, did);
627 // FIXME(jynelson): why is this different from
629 match cx.tcx.type_of(did).kind() {
631 let field = if def.is_enum() {
632 def.all_fields().find(|item| item.ident.name == item_name)
634 def.non_enum_variant()
637 .find(|item| item.ident.name == item_name)
640 if extra_fragment.is_some() {
649 Err(ErrorKind::AnchorFailure(
650 AnchorFailure::RustdocAnchorConflict(res),
657 if def.is_enum() { "variant" } else { "structfield" },
670 Res::Def(DefKind::Trait, did) => cx
672 .associated_items(did)
673 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, did)
675 let kind = match item.kind {
676 ty::AssocKind::Const => "associatedconstant",
677 ty::AssocKind::Type => "associatedtype",
678 ty::AssocKind::Fn => {
679 if item.defaultness.has_value() {
687 if extra_fragment.is_some() {
688 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
690 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
691 Ok((res, Some(format!("{}.{}", kind, item_str))))
696 res.unwrap_or_else(|| {
697 if ns == Namespace::ValueNS {
698 self.variant_field(path_str, module_id)
700 Err(ResolutionFailure::NotResolved {
702 partial_res: Some(ty_res),
703 unresolved: item_str.into(),
710 /// Used for reporting better errors.
712 /// Returns whether the link resolved 'fully' in another namespace.
713 /// 'fully' here means that all parts of the link resolved, not just some path segments.
714 /// This returns the `Res` even if it was erroneous for some reason
715 /// (such as having invalid URL fragments or being in the wrong namespace).
721 extra_fragment: &Option<String>,
723 // resolve() can't be used for macro namespace
724 let result = match ns {
725 Namespace::MacroNS => self.resolve_macro(path_str, module_id).map_err(ErrorKind::from),
726 Namespace::TypeNS | Namespace::ValueNS => {
727 self.resolve(path_str, ns, module_id, extra_fragment).map(|(res, _)| res)
731 let res = match result {
732 Ok(res) => Some(res),
733 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
734 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
735 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
737 self.kind_side_channel.take().map(|(kind, id)| Res::Def(kind, id)).or(res)
741 /// Look to see if a resolved item has an associated item named `item_name`.
743 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
744 /// find `std::error::Error::source` and return
745 /// `<io::Error as error::Error>::source`.
746 fn resolve_associated_trait_item(
752 ) -> Option<(ty::AssocKind, DefId)> {
753 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
754 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
755 // meantime, just don't look for these blanket impls.
757 // Next consider explicit impls: `impl MyTrait for MyType`
758 // Give precedence to inherent impls.
759 let traits = traits_implemented_by(cx, did, module);
760 debug!("considering traits {:?}", traits);
761 let mut candidates = traits.iter().filter_map(|&trait_| {
763 .associated_items(trait_)
764 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
765 .map(|assoc| (assoc.kind, assoc.def_id))
767 // FIXME(#74563): warn about ambiguity
768 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
772 /// Given a type, return all traits in scope in `module` implemented by that type.
774 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
775 /// So it is not stable to serialize cross-crate.
776 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
777 let mut cache = cx.module_trait_cache.borrow_mut();
778 let in_scope_traits = cache.entry(module).or_insert_with(|| {
779 cx.enter_resolver(|resolver| {
780 resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
784 let ty = cx.tcx.type_of(type_);
785 let iter = in_scope_traits.iter().flat_map(|&trait_| {
786 trace!("considering explicit impl for trait {:?}", trait_);
788 // Look at each trait implementation to see if it's an impl for `did`
789 cx.tcx.find_map_relevant_impl(trait_, ty, |impl_| {
790 let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
791 // Check if these are the same type.
792 let impl_type = trait_ref.self_ty();
794 "comparing type {} with kind {:?} against type {:?}",
799 // Fast path: if this is a primitive simple `==` will work
800 let saw_impl = impl_type == ty
801 || match impl_type.kind() {
802 // Check if these are the same def_id
804 debug!("adt def_id: {:?}", def.did);
807 ty::Foreign(def_id) => *def_id == type_,
811 if saw_impl { Some(trait_) } else { None }
817 /// Check for resolve collisions between a trait and its derive.
819 /// These are common and we should just resolve to the trait in that case.
820 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
824 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
825 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
831 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
832 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
833 use rustc_middle::ty::DefIdTree;
835 let parent_node = if item.is_fake() {
838 find_nearest_parent_module(self.cx.tcx, item.def_id)
841 if parent_node.is_some() {
842 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
845 // find item's parent to resolve `Self` in item's docs below
846 debug!("looking for the `Self` type");
847 let self_id = if item.is_fake() {
850 self.cx.tcx.def_kind(item.def_id),
857 self.cx.tcx.parent(item.def_id)
858 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
859 // Fixing this breaks `fn render_deref_methods`.
860 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
861 // regardless of what rustdoc wants to call it.
862 } else if let Some(parent) = self.cx.tcx.parent(item.def_id) {
863 let parent_kind = self.cx.tcx.def_kind(parent);
864 Some(if parent_kind == DefKind::Impl { parent } else { item.def_id })
869 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
870 let self_name = self_id.and_then(|self_id| {
872 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
873 // using `ty.to_string()` (or any variant) has issues with raw idents
874 let ty = self.cx.tcx.type_of(self_id);
875 let name = match ty.kind() {
876 TyKind::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
877 other if other.is_primitive() => Some(ty.to_string()),
880 debug!("using type_of(): {:?}", name);
883 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
884 debug!("using item_name(): {:?}", name);
889 if item.is_mod() && item.attrs.inner_docs {
890 self.mod_ids.push(item.def_id);
893 // We want to resolve in the lexical scope of the documentation.
894 // In the presence of re-exports, this is not the same as the module of the item.
895 // Rather than merging all documentation into one, resolve it one attribute at a time
896 // so we know which module it came from.
897 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
898 debug!("combined_docs={}", doc);
900 let (krate, parent_node) = if let Some(id) = parent_module {
903 (item.def_id.krate, parent_node)
905 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
906 // This is a degenerate case and it's not supported by rustdoc.
907 for md_link in markdown_links(&doc) {
908 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
909 if let Some(link) = link {
910 item.attrs.links.push(link);
915 Some(if item.is_mod() {
916 if !item.attrs.inner_docs {
917 self.mod_ids.push(item.def_id);
920 let ret = self.fold_item_recur(item);
924 self.fold_item_recur(item)
929 impl LinkCollector<'_, '_> {
930 /// This is the entry point for resolving an intra-doc link.
932 /// FIXME(jynelson): this is way too many arguments
937 self_name: &Option<String>,
938 parent_node: Option<DefId>,
940 ori_link: MarkdownLink,
941 ) -> Option<ItemLink> {
942 trace!("considering link '{}'", ori_link.link);
944 // Bail early for real links.
945 if ori_link.link.contains('/') {
949 // [] is mostly likely not supposed to be a link
950 if ori_link.link.is_empty() {
955 let link = ori_link.link.replace("`", "");
956 let parts = link.split('#').collect::<Vec<_>>();
957 let (link, extra_fragment) = if parts.len() > 2 {
958 // A valid link can't have multiple #'s
959 anchor_failure(cx, &item, &link, dox, ori_link.range, AnchorFailure::MultipleAnchors);
961 } else if parts.len() == 2 {
962 if parts[0].trim().is_empty() {
963 // This is an anchor to an element of the current page, nothing to do in here!
966 (parts[0], Some(parts[1].to_owned()))
971 // Parse and strip the disambiguator from the link, if present.
972 let (mut path_str, disambiguator) = if let Ok((d, path)) = Disambiguator::from_str(&link) {
973 (path.trim(), Some(d))
978 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch))) {
982 // We stripped `()` and `!` when parsing the disambiguator.
983 // Add them back to be displayed, but not prefix disambiguators.
985 disambiguator.map(|d| d.display_for(path_str)).unwrap_or_else(|| path_str.to_owned());
987 // In order to correctly resolve intra-doc-links we need to
988 // pick a base AST node to work from. If the documentation for
989 // this module came from an inner comment (//!) then we anchor
990 // our name resolution *inside* the module. If, on the other
991 // hand it was an outer comment (///) then we anchor the name
992 // resolution in the parent module on the basis that the names
993 // used are more likely to be intended to be parent names. For
994 // this, we set base_node to None for inner comments since
995 // we've already pushed this node onto the resolution stack but
996 // for outer comments we explicitly try and resolve against the
997 // parent_node first.
998 let base_node = if item.is_mod() && item.attrs.inner_docs {
999 self.mod_ids.last().copied()
1004 let mut module_id = if let Some(id) = base_node {
1008 debug!("attempting to resolve item without parent module: {}", path_str);
1016 smallvec![ResolutionFailure::NoParentItem],
1022 // replace `Self` with suitable item's parent name
1023 if path_str.starts_with("Self::") {
1024 if let Some(ref name) = self_name {
1025 resolved_self = format!("{}::{}", name, &path_str[6..]);
1026 path_str = &resolved_self;
1028 } else if path_str.starts_with("crate::") {
1029 use rustc_span::def_id::CRATE_DEF_INDEX;
1031 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1032 // But rustdoc wants it to mean the crate this item was originally present in.
1033 // To work around this, remove it and resolve relative to the crate root instead.
1034 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1035 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1036 // FIXME(#78696): This doesn't always work.
1037 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1038 path_str = &resolved_self;
1039 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1042 // Strip generics from the path.
1043 let stripped_path_string;
1044 if path_str.contains(['<', '>'].as_slice()) {
1045 stripped_path_string = match strip_generics_from_path(path_str) {
1048 debug!("link has malformed generics: {}", path_str);
1056 smallvec![err_kind],
1061 path_str = &stripped_path_string;
1063 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1064 assert!(!path_str.contains(['<', '>'].as_slice()));
1066 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1067 if path_str.contains(' ') {
1071 let diag_info = DiagnosticInfo {
1074 ori_link: &ori_link.link,
1075 link_range: ori_link.range.clone(),
1077 let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(
1081 path_str: path_str.to_owned(),
1085 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1088 // Check for a primitive which might conflict with a module
1089 // Report the ambiguity and require that the user specify which one they meant.
1090 // FIXME: could there ever be a primitive not in the type namespace?
1093 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1094 ) && !matches!(res, Res::Primitive(_))
1096 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1098 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1099 if fragment.is_some() {
1106 AnchorFailure::RustdocAnchorConflict(prim),
1111 fragment = Some(prim.name(self.cx.tcx));
1113 // `[char]` when a `char` module is in scope
1114 let candidates = vec![res, prim];
1115 ambiguity_error(cx, &item, path_str, dox, ori_link.range, candidates);
1121 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1122 // The resolved item did not match the disambiguator; give a better error than 'not found'
1123 let msg = format!("incompatible link kind for `{}`", path_str);
1124 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1126 "this link resolved to {} {}, which is not {} {}",
1129 specified.article(),
1133 suggest_disambiguator(resolved, diag, path_str, dox, sp, &ori_link.range);
1137 BROKEN_INTRA_DOC_LINKS,
1146 Res::Primitive(_) => match disambiguator {
1147 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
1148 Some(ItemLink { link: ori_link.link, link_text, did: None, fragment })
1151 report_mismatch(other, Disambiguator::Primitive);
1155 Res::Def(kind, id) => {
1156 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
1158 // Disallow e.g. linking to enums with `struct@`
1159 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1160 match (self.kind_side_channel.take().map(|(kind, _)| kind).unwrap_or(kind), disambiguator) {
1161 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1162 // NOTE: this allows 'method' to mean both normal functions and associated functions
1163 // This can't cause ambiguity because both are in the same namespace.
1164 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1165 // These are namespaces; allow anything in the namespace to match
1166 | (_, Some(Disambiguator::Namespace(_)))
1167 // If no disambiguator given, allow anything
1169 // All of these are valid, so do nothing
1171 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1172 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1173 report_mismatch(specified, Disambiguator::Kind(kind));
1178 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1179 if let Some((src_id, dst_id)) = id
1181 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
1183 use rustc_hir::def_id::LOCAL_CRATE;
1185 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1186 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1188 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
1189 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
1191 privacy_error(cx, &item, &path_str, dox, &ori_link);
1194 let id = clean::register_res(cx, rustc_hir::def::Res::Def(kind, id));
1195 Some(ItemLink { link: ori_link.link, link_text, did: Some(id), fragment })
1200 fn resolve_with_disambiguator_cached(
1202 key: ResolutionInfo,
1203 diag: DiagnosticInfo<'_>,
1204 cache_resolution_failure: bool,
1205 ) -> Option<(Res, Option<String>)> {
1206 // Try to look up both the result and the corresponding side channel value
1207 if let Some(ref cached) = self.visited_links.get(&key) {
1210 self.kind_side_channel.set(cached.side_channel.clone());
1211 return Some(cached.res.clone());
1213 None if cache_resolution_failure => return None,
1215 // Although we hit the cache and found a resolution error, this link isn't
1216 // supposed to cache those. Run link resolution again to emit the expected
1217 // resolution error.
1222 let res = self.resolve_with_disambiguator(&key, diag);
1224 // Cache only if resolved successfully - don't silence duplicate errors
1225 if let Some(res) = res {
1226 // Store result for the actual namespace
1227 self.visited_links.insert(
1231 side_channel: self.kind_side_channel.clone().into_inner(),
1237 if cache_resolution_failure {
1238 // For reference-style links we only want to report one resolution error
1239 // so let's cache them as well.
1240 self.visited_links.insert(key, None);
1247 /// After parsing the disambiguator, resolve the main part of the link.
1248 // FIXME(jynelson): wow this is just so much
1249 fn resolve_with_disambiguator(
1251 key: &ResolutionInfo,
1252 diag: DiagnosticInfo<'_>,
1253 ) -> Option<(Res, Option<String>)> {
1254 let disambiguator = key.dis;
1255 let path_str = &key.path_str;
1256 let base_node = key.module_id;
1257 let extra_fragment = &key.extra_fragment;
1259 match disambiguator.map(Disambiguator::ns) {
1260 Some(ns @ (ValueNS | TypeNS)) => {
1261 match self.resolve(path_str, ns, base_node, extra_fragment) {
1262 Ok(res) => Some(res),
1263 Err(ErrorKind::Resolve(box mut kind)) => {
1264 // We only looked in one namespace. Try to give a better error if possible.
1265 if kind.full_res().is_none() {
1266 let other_ns = if ns == ValueNS { TypeNS } else { ValueNS };
1267 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1268 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1269 for &new_ns in &[other_ns, MacroNS] {
1271 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1273 kind = ResolutionFailure::WrongNamespace(res, ns);
1287 // This could just be a normal link or a broken link
1288 // we could potentially check if something is
1289 // "intra-doc-link-like" and warn in that case.
1292 Err(ErrorKind::AnchorFailure(msg)) => {
1307 let mut candidates = PerNS {
1309 .resolve_macro(path_str, base_node)
1310 .map(|res| (res, extra_fragment.clone())),
1311 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1313 debug!("got res in TypeNS: {:?}", res);
1316 Err(ErrorKind::AnchorFailure(msg)) => {
1327 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1329 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1331 Err(ErrorKind::AnchorFailure(msg)) => {
1342 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1344 .and_then(|(res, fragment)| {
1345 // Constructors are picked up in the type namespace.
1347 Res::Def(DefKind::Ctor(..), _) => {
1348 Err(ResolutionFailure::WrongNamespace(res, TypeNS))
1351 match (fragment, extra_fragment.clone()) {
1352 (Some(fragment), Some(_)) => {
1353 // Shouldn't happen but who knows?
1354 Ok((res, Some(fragment)))
1356 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1363 let len = candidates.iter().filter(|res| res.is_ok()).count();
1373 candidates.into_iter().filter_map(|res| res.err()).collect(),
1375 // this could just be a normal link
1380 Some(candidates.into_iter().filter_map(|res| res.ok()).next().unwrap())
1381 } else if len == 2 && is_derive_trait_collision(&candidates) {
1382 Some(candidates.type_ns.unwrap())
1384 if is_derive_trait_collision(&candidates) {
1385 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1387 // If we're reporting an ambiguity, don't mention the namespaces that failed
1388 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1395 candidates.present_items().collect(),
1401 match self.resolve_macro(path_str, base_node) {
1402 Ok(res) => Some((res, extra_fragment.clone())),
1404 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1405 for &ns in &[TypeNS, ValueNS] {
1407 self.check_full_res(ns, path_str, base_node, extra_fragment)
1409 kind = ResolutionFailure::WrongNamespace(res, MacroNS);
1430 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1431 /// Disambiguators for a link.
1432 enum Disambiguator {
1435 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1437 /// `struct@` or `f()`
1440 Namespace(Namespace),
1443 impl Disambiguator {
1444 /// The text that should be displayed when the path is rendered as HTML.
1446 /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1447 fn display_for(&self, path: &str) -> String {
1449 // FIXME: this will have different output if the user had `m!()` originally.
1450 Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1451 Self::Kind(DefKind::Fn) => format!("{}()", path),
1452 _ => path.to_owned(),
1456 /// Given a link, parse and return `(disambiguator, path_str)`
1457 fn from_str(link: &str) -> Result<(Self, &str), ()> {
1458 use Disambiguator::{Kind, Namespace as NS, Primitive};
1460 let find_suffix = || {
1462 ("!()", DefKind::Macro(MacroKind::Bang)),
1463 ("()", DefKind::Fn),
1464 ("!", DefKind::Macro(MacroKind::Bang)),
1466 for &(suffix, kind) in &suffixes {
1467 if let Some(link) = link.strip_suffix(suffix) {
1468 // Avoid turning `!` or `()` into an empty string
1469 if !link.is_empty() {
1470 return Ok((Kind(kind), link));
1477 if let Some(idx) = link.find('@') {
1478 let (prefix, rest) = link.split_at(idx);
1479 let d = match prefix {
1480 "struct" => Kind(DefKind::Struct),
1481 "enum" => Kind(DefKind::Enum),
1482 "trait" => Kind(DefKind::Trait),
1483 "union" => Kind(DefKind::Union),
1484 "module" | "mod" => Kind(DefKind::Mod),
1485 "const" | "constant" => Kind(DefKind::Const),
1486 "static" => Kind(DefKind::Static),
1487 "function" | "fn" | "method" => Kind(DefKind::Fn),
1488 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1489 "type" => NS(Namespace::TypeNS),
1490 "value" => NS(Namespace::ValueNS),
1491 "macro" => NS(Namespace::MacroNS),
1492 "prim" | "primitive" => Primitive,
1493 _ => return find_suffix(),
1501 fn from_res(res: Res) -> Self {
1503 Res::Def(kind, _) => Disambiguator::Kind(kind),
1504 Res::Primitive(_) => Disambiguator::Primitive,
1508 /// Used for error reporting.
1509 fn suggestion(self) -> Suggestion {
1510 let kind = match self {
1511 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1512 Disambiguator::Kind(kind) => kind,
1513 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1515 if kind == DefKind::Macro(MacroKind::Bang) {
1516 return Suggestion::Macro;
1517 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1518 return Suggestion::Function;
1521 let prefix = match kind {
1522 DefKind::Struct => "struct",
1523 DefKind::Enum => "enum",
1524 DefKind::Trait => "trait",
1525 DefKind::Union => "union",
1526 DefKind::Mod => "mod",
1527 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1530 DefKind::Static => "static",
1531 DefKind::Macro(MacroKind::Derive) => "derive",
1532 // Now handle things that don't have a specific disambiguator
1535 .expect("tried to calculate a disambiguator for a def without a namespace?")
1537 Namespace::TypeNS => "type",
1538 Namespace::ValueNS => "value",
1539 Namespace::MacroNS => "macro",
1543 Suggestion::Prefix(prefix)
1546 fn ns(self) -> Namespace {
1548 Self::Namespace(n) => n,
1550 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1552 Self::Primitive => TypeNS,
1556 fn article(self) -> &'static str {
1558 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1559 Self::Kind(k) => k.article(),
1560 Self::Primitive => "a",
1564 fn descr(self) -> &'static str {
1566 Self::Namespace(n) => n.descr(),
1567 // HACK(jynelson): by looking at the source I saw the DefId we pass
1568 // for `expected.descr()` doesn't matter, since it's not a crate
1569 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1570 Self::Primitive => "builtin type",
1575 /// A suggestion to show in a diagnostic.
1578 Prefix(&'static str),
1586 fn descr(&self) -> Cow<'static, str> {
1588 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1589 Self::Function => "add parentheses".into(),
1590 Self::Macro => "add an exclamation mark".into(),
1594 fn as_help(&self, path_str: &str) -> String {
1595 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1597 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1598 Self::Function => format!("{}()", path_str),
1599 Self::Macro => format!("{}!", path_str),
1604 /// Reports a diagnostic for an intra-doc link.
1606 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1607 /// the entire documentation block is used for the lint. If a range is provided but the span
1608 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1610 /// The `decorate` callback is invoked in all cases to allow further customization of the
1611 /// diagnostic before emission. If the span of the link was able to be determined, the second
1612 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1614 fn report_diagnostic(
1615 cx: &DocContext<'_>,
1616 lint: &'static Lint,
1620 link_range: &Range<usize>,
1621 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1623 let hir_id = match cx.as_local_hir_id(item.def_id) {
1624 Some(hir_id) => hir_id,
1626 // If non-local, no need to check anything.
1627 info!("ignoring warning from parent crate: {}", msg);
1632 let attrs = &item.attrs;
1633 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1635 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1636 let mut diag = lint.build(msg);
1638 let span = super::source_span_for_markdown_range(cx, dox, link_range, attrs);
1640 if let Some(sp) = span {
1643 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1646 // last_new_line_offset
1647 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1648 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1650 // Print the line containing the `link_range` and manually mark it with '^'s.
1652 "the link appears in this line:\n\n{line}\n\
1653 {indicator: <before$}{indicator:^<found$}",
1656 before = link_range.start - last_new_line_offset,
1657 found = link_range.len(),
1661 decorate(&mut diag, span);
1667 /// Reports a link that failed to resolve.
1669 /// This also tries to resolve any intermediate path segments that weren't
1670 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1671 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1672 fn resolution_failure(
1673 collector: &LinkCollector<'_, '_>,
1676 disambiguator: Option<Disambiguator>,
1678 link_range: Range<usize>,
1679 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1681 let tcx = collector.cx.tcx;
1684 BROKEN_INTRA_DOC_LINKS,
1685 &format!("unresolved link to `{}`", path_str),
1690 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1691 let assoc_item_not_allowed = |res: Res| {
1692 let name = res.name(tcx);
1694 "`{}` is {} {}, not a module or type, and cannot have associated items",
1700 // ignore duplicates
1701 let mut variants_seen = SmallVec::<[_; 3]>::new();
1702 for mut failure in kinds {
1703 let variant = std::mem::discriminant(&failure);
1704 if variants_seen.contains(&variant) {
1707 variants_seen.push(variant);
1709 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1714 let module_id = *module_id;
1715 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1716 // FIXME: maybe use itertools `collect_tuple` instead?
1717 fn split(path: &str) -> Option<(&str, &str)> {
1718 let mut splitter = path.rsplitn(2, "::");
1719 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1722 // Check if _any_ parent of the path gets resolved.
1723 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1724 let mut name = path_str;
1726 let (start, end) = if let Some(x) = split(name) {
1729 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1730 if partial_res.is_none() {
1731 *unresolved = name.into();
1736 for &ns in &[TypeNS, ValueNS, MacroNS] {
1738 collector.check_full_res(ns, &start, module_id, &None)
1740 debug!("found partial_res={:?}", res);
1741 *partial_res = Some(res);
1742 *unresolved = end.into();
1746 *unresolved = end.into();
1749 let last_found_module = match *partial_res {
1750 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1751 None => Some(module_id),
1754 // See if this was a module: `[path]` or `[std::io::nope]`
1755 if let Some(module) = last_found_module {
1756 let note = if partial_res.is_some() {
1757 // Part of the link resolved; e.g. `std::io::nonexistent`
1758 let module_name = tcx.item_name(module);
1759 format!("no item named `{}` in module `{}`", unresolved, module_name)
1761 // None of the link resolved; e.g. `Notimported`
1762 format!("no item named `{}` in scope", unresolved)
1764 if let Some(span) = sp {
1765 diag.span_label(span, ¬e);
1770 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1771 // Otherwise, the `[]` might be unrelated.
1772 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1773 if !path_str.contains("::") {
1774 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1780 // Otherwise, it must be an associated item or variant
1781 let res = partial_res.expect("None case was handled by `last_found_module`");
1782 let name = res.name(tcx);
1783 let kind = match res {
1784 Res::Def(kind, _) => Some(kind),
1785 Res::Primitive(_) => None,
1787 let path_description = if let Some(kind) = kind {
1789 Mod | ForeignMod => "inner item",
1790 Struct => "field or associated item",
1791 Enum | Union => "variant or associated item",
1808 let note = assoc_item_not_allowed(res);
1809 if let Some(span) = sp {
1810 diag.span_label(span, ¬e);
1816 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1817 | Static => "associated item",
1818 Impl | GlobalAsm => unreachable!("not a path"),
1824 "the {} `{}` has no {} named `{}`",
1827 disambiguator.map_or(path_description, |d| d.descr()),
1830 if let Some(span) = sp {
1831 diag.span_label(span, ¬e);
1838 let note = match failure {
1839 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1840 ResolutionFailure::Dummy => continue,
1841 ResolutionFailure::WrongNamespace(res, expected_ns) => {
1842 if let Res::Def(kind, _) = res {
1843 let disambiguator = Disambiguator::Kind(kind);
1844 suggest_disambiguator(
1855 "this link resolves to {}, which is not in the {} namespace",
1860 ResolutionFailure::NoParentItem => {
1861 diag.level = rustc_errors::Level::Bug;
1862 "all intra doc links should have a parent item".to_owned()
1864 ResolutionFailure::MalformedGenerics(variant) => match variant {
1865 MalformedGenerics::UnbalancedAngleBrackets => {
1866 String::from("unbalanced angle brackets")
1868 MalformedGenerics::MissingType => {
1869 String::from("missing type for generic parameters")
1871 MalformedGenerics::HasFullyQualifiedSyntax => {
1872 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1873 String::from("fully-qualified syntax is unsupported")
1875 MalformedGenerics::InvalidPathSeparator => {
1876 String::from("has invalid path separator")
1878 MalformedGenerics::TooManyAngleBrackets => {
1879 String::from("too many angle brackets")
1881 MalformedGenerics::EmptyAngleBrackets => {
1882 String::from("empty angle brackets")
1886 if let Some(span) = sp {
1887 diag.span_label(span, ¬e);
1896 /// Report an anchor failure.
1898 cx: &DocContext<'_>,
1902 link_range: Range<usize>,
1903 failure: AnchorFailure,
1905 let msg = match failure {
1906 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1907 AnchorFailure::RustdocAnchorConflict(res) => format!(
1908 "`{}` contains an anchor, but links to {kind}s are already anchored",
1914 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1915 if let Some(sp) = sp {
1916 diag.span_label(sp, "contains invalid anchor");
1921 /// Report an ambiguity error, where there were multiple possible resolutions.
1923 cx: &DocContext<'_>,
1927 link_range: Range<usize>,
1928 candidates: Vec<Res>,
1930 let mut msg = format!("`{}` is ", path_str);
1932 match candidates.as_slice() {
1933 [first_def, second_def] => {
1935 "both {} {} and {} {}",
1936 first_def.article(),
1938 second_def.article(),
1943 let mut candidates = candidates.iter().peekable();
1944 while let Some(res) = candidates.next() {
1945 if candidates.peek().is_some() {
1946 msg += &format!("{} {}, ", res.article(), res.descr());
1948 msg += &format!("and {} {}", res.article(), res.descr());
1954 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1955 if let Some(sp) = sp {
1956 diag.span_label(sp, "ambiguous link");
1958 diag.note("ambiguous link");
1961 for res in candidates {
1962 let disambiguator = Disambiguator::from_res(res);
1963 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1968 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
1970 fn suggest_disambiguator(
1971 disambiguator: Disambiguator,
1972 diag: &mut DiagnosticBuilder<'_>,
1975 sp: Option<rustc_span::Span>,
1976 link_range: &Range<usize>,
1978 let suggestion = disambiguator.suggestion();
1979 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
1981 if let Some(sp) = sp {
1982 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
1983 format!("`{}`", suggestion.as_help(path_str))
1985 suggestion.as_help(path_str)
1988 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
1990 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
1994 /// Report a link from a public item to a private one.
1995 fn privacy_error(cx: &DocContext<'_>, item: &Item, path_str: &str, dox: &str, link: &MarkdownLink) {
1997 let item_name = match item.name {
1999 sym = name.as_str();
2002 None => "<unknown>",
2005 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2007 report_diagnostic(cx, PRIVATE_INTRA_DOC_LINKS, &msg, item, dox, &link.range, |diag, sp| {
2008 if let Some(sp) = sp {
2009 diag.span_label(sp, "this item is private");
2012 let note_msg = if cx.render_options.document_private {
2013 "this link resolves only because you passed `--document-private-items`, but will break without"
2015 "this link will resolve properly if you pass `--document-private-items`"
2017 diag.note(note_msg);
2021 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2023 cx: &DocContext<'_>,
2025 extra_fragment: &Option<String>,
2026 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
2027 use rustc_middle::ty::DefIdTree;
2029 if extra_fragment.is_some() {
2030 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2033 .parent(res.def_id())
2035 let parent_def = Res::Def(DefKind::Enum, parent);
2036 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2037 (parent_def, Some(format!("variant.{}", variant.ident.name)))
2039 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2042 /// Resolve a primitive type or value.
2043 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2047 use PrimitiveType::*;
2048 let prim = match path_str {
2064 "bool" | "true" | "false" => Bool,
2066 // See #80181 for why these don't have symbols associated.
2071 "pointer" | "*" | "*const" | "*mut" => RawPointer,
2072 "reference" | "&" | "&mut" => Reference,
2074 "never" | "!" => Never,
2077 debug!("resolved primitives {:?}", prim);
2078 Some(Res::Primitive(prim))
2081 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2082 let mut stripped_segments = vec![];
2083 let mut path = path_str.chars().peekable();
2084 let mut segment = Vec::new();
2086 while let Some(chr) = path.next() {
2089 if path.next_if_eq(&':').is_some() {
2090 let stripped_segment =
2091 strip_generics_from_path_segment(mem::take(&mut segment))?;
2092 if !stripped_segment.is_empty() {
2093 stripped_segments.push(stripped_segment);
2096 return Err(ResolutionFailure::MalformedGenerics(
2097 MalformedGenerics::InvalidPathSeparator,
2106 return Err(ResolutionFailure::MalformedGenerics(
2107 MalformedGenerics::TooManyAngleBrackets,
2111 return Err(ResolutionFailure::MalformedGenerics(
2112 MalformedGenerics::EmptyAngleBrackets,
2118 while let Some(chr) = path.next_if(|c| *c != '>') {
2125 _ => segment.push(chr),
2127 trace!("raw segment: {:?}", segment);
2130 if !segment.is_empty() {
2131 let stripped_segment = strip_generics_from_path_segment(segment)?;
2132 if !stripped_segment.is_empty() {
2133 stripped_segments.push(stripped_segment);
2137 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2139 let stripped_path = stripped_segments.join("::");
2141 if !stripped_path.is_empty() {
2144 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2148 fn strip_generics_from_path_segment(
2150 ) -> Result<String, ResolutionFailure<'static>> {
2151 let mut stripped_segment = String::new();
2152 let mut param_depth = 0;
2154 let mut latest_generics_chunk = String::new();
2159 latest_generics_chunk.clear();
2160 } else if c == '>' {
2162 if latest_generics_chunk.contains(" as ") {
2163 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2164 // Give a helpful error message instead of completely ignoring the angle brackets.
2165 return Err(ResolutionFailure::MalformedGenerics(
2166 MalformedGenerics::HasFullyQualifiedSyntax,
2170 if param_depth == 0 {
2171 stripped_segment.push(c);
2173 latest_generics_chunk.push(c);
2178 if param_depth == 0 {
2179 Ok(stripped_segment)
2181 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2182 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))