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};
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::sym;
24 use rustc_span::symbol::Ident;
25 use rustc_span::symbol::Symbol;
26 use rustc_span::DUMMY_SP;
27 use smallvec::{smallvec, SmallVec};
34 use crate::clean::{self, Crate, GetDefId, 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)
65 /// A link failed to resolve.
66 enum ResolutionFailure<'a> {
67 /// This resolved, but with the wrong namespace.
69 /// `Namespace` is the namespace specified with a disambiguator
70 /// (as opposed to the actual namespace of the `Res`).
71 WrongNamespace(Res, /* disambiguated */ Namespace),
72 /// The link failed to resolve. `resolution_failure` should look to see if there's
73 /// a more helpful error that can be given.
75 /// The scope the link was resolved in.
77 /// If part of the link resolved, this has the `Res`.
79 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
80 partial_res: Option<Res>,
81 /// The remaining unresolved path segments.
83 /// In `[std::io::Error::x]`, `x` would be unresolved.
84 unresolved: Cow<'a, str>,
86 /// This happens when rustdoc can't determine the parent scope for an item.
88 /// It is always a bug in rustdoc.
90 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
91 MalformedGenerics(MalformedGenerics),
92 /// Used to communicate that this should be ignored, but shouldn't be reported to the user
94 /// This happens when there is no disambiguator and one of the namespaces
95 /// failed to resolve.
100 enum MalformedGenerics {
101 /// This link has unbalanced angle brackets.
103 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
104 UnbalancedAngleBrackets,
105 /// The generics are not attached to a type.
107 /// For example, `<T>` should trigger this.
109 /// This is detected by checking if the path is empty after the generics are stripped.
111 /// The link uses fully-qualified syntax, which is currently unsupported.
113 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
115 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
117 HasFullyQualifiedSyntax,
118 /// The link has an invalid path separator.
120 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
121 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
124 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
125 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
126 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
128 /// This is detected by checking if there is a colon followed by a non-colon in the link.
129 InvalidPathSeparator,
130 /// The link has too many angle brackets.
132 /// For example, `Vec<<T>>` should trigger this.
133 TooManyAngleBrackets,
134 /// The link has empty angle brackets.
136 /// For example, `Vec<>` should trigger this.
140 impl ResolutionFailure<'a> {
141 /// This resolved fully (not just partially) but is erroneous for some other reason
143 /// Returns the full resolution of the link, if present.
144 fn full_res(&self) -> Option<Res> {
146 Self::WrongNamespace(res, _) => Some(*res),
153 /// User error: `[std#x#y]` is not valid
155 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
157 /// This is an unfortunate state of affairs. Not every item that can be
158 /// linked to has its own page; sometimes it is a subheading within a page,
159 /// like for associated items. In those cases, rustdoc uses an anchor to
160 /// link to the subheading. Since you can't have two anchors for the same
161 /// link, Rustdoc disallows having a user-specified anchor.
163 /// Most of the time this is fine, because you can just link to the page of
164 /// the item if you want to provide your own anchor. For primitives, though,
165 /// rustdoc uses the anchor as a side channel to know which page to link to;
166 /// it doesn't show up in the generated link. Ideally, rustdoc would remove
167 /// this limitation, allowing you to link to subheaders on primitives.
168 RustdocAnchorConflict(Res),
171 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
172 struct ResolutionInfo {
174 dis: Option<Disambiguator>,
176 extra_fragment: Option<String>,
179 struct DiagnosticInfo<'a> {
183 link_range: Option<Range<usize>>,
186 #[derive(Clone, Debug, Hash)]
188 pub res: (Res, Option<String>),
189 pub side_channel: Option<(DefKind, DefId)>,
192 struct LinkCollector<'a, 'tcx> {
193 cx: &'a DocContext<'tcx>,
194 /// A stack of modules used to decide what scope to resolve in.
196 /// The last module will be used if the parent scope of the current item is
199 /// This is used to store the kind of associated items,
200 /// because `clean` and the disambiguator code expect them to be different.
201 /// See the code for associated items on inherent impls for details.
202 kind_side_channel: Cell<Option<(DefKind, DefId)>>,
203 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link
204 visited_links: FxHashMap<ResolutionInfo, CachedLink>,
207 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
208 fn new(cx: &'a DocContext<'tcx>) -> Self {
212 kind_side_channel: Cell::new(None),
213 visited_links: FxHashMap::default(),
217 /// Given a full link, parse it as an [enum struct variant].
219 /// In particular, this will return an error whenever there aren't three
220 /// full path segments left in the link.
222 /// [enum struct variant]: hir::VariantData::Struct
225 path_str: &'path str,
227 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
229 let no_res = || ResolutionFailure::NotResolved {
232 unresolved: path_str.into(),
235 debug!("looking for enum variant {}", path_str);
236 let mut split = path_str.rsplitn(3, "::");
237 let (variant_field_str, variant_field_name) = split
239 .map(|f| (f, Symbol::intern(f)))
240 .expect("fold_item should ensure link is non-empty");
241 let (variant_str, variant_name) =
242 // we're not sure this is a variant at all, so use the full string
243 // If there's no second component, the link looks like `[path]`.
244 // So there's no partial res and we should say the whole link failed to resolve.
245 split.next().map(|f| (f, Symbol::intern(f))).ok_or_else(no_res)?;
248 .map(|f| f.to_owned())
249 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
250 // So there's no partial res.
251 .ok_or_else(no_res)?;
253 .enter_resolver(|resolver| {
254 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
257 .unwrap_or(Res::Err);
258 if let Res::Err = ty_res {
259 return Err(no_res().into());
261 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
263 Res::Def(DefKind::Enum, did) => {
268 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
269 .any(|item| item.ident.name == variant_name)
271 // This is just to let `fold_item` know that this shouldn't be considered;
272 // it's a bug for the error to make it to the user
273 return Err(ResolutionFailure::Dummy.into());
275 match cx.tcx.type_of(did).kind() {
276 ty::Adt(def, _) if def.is_enum() => {
277 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
281 "variant.{}.field.{}",
282 variant_str, variant_field_name
286 Err(ResolutionFailure::NotResolved {
288 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
289 unresolved: variant_field_str.into(),
297 _ => Err(ResolutionFailure::NotResolved {
299 partial_res: Some(ty_res),
300 unresolved: variant_str.into(),
306 /// Given a primitive type, try to resolve an associated item.
308 /// HACK(jynelson): `item_str` is passed in instead of derived from `item_name` so the
309 /// lifetimes on `&'path` will work.
310 fn resolve_primitive_associated_item(
312 prim_ty: hir::PrimTy,
316 item_str: &'path str,
317 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
320 PrimitiveType::from_hir(prim_ty)
325 .associated_items(impl_)
326 .find_by_name_and_namespace(
328 Ident::with_dummy_span(item_name),
332 .map(|item| match item.kind {
333 ty::AssocKind::Fn => "method",
334 ty::AssocKind::Const => "associatedconstant",
335 ty::AssocKind::Type => "associatedtype",
339 Res::PrimTy(prim_ty),
340 Some(format!("{}#{}.{}", prim_ty.name(), out, item_str)),
346 "returning primitive error for {}::{} in {} namespace",
351 ResolutionFailure::NotResolved {
353 partial_res: Some(Res::PrimTy(prim_ty)),
354 unresolved: item_str.into(),
360 /// Resolves a string as a macro.
362 /// FIXME(jynelson): Can this be unified with `resolve()`?
367 ) -> Result<Res, ResolutionFailure<'a>> {
369 let path = ast::Path::from_ident(Ident::from_str(path_str));
370 cx.enter_resolver(|resolver| {
371 // FIXME(jynelson): does this really need 3 separate lookups?
372 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
375 &ParentScope::module(resolver.graph_root(), resolver),
379 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
380 return Ok(res.map_id(|_| panic!("unexpected id")));
383 if let Some(res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
384 return Ok(res.map_id(|_| panic!("unexpected id")));
386 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
387 if let Ok((_, res)) =
388 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
390 // don't resolve builtins like `#[derive]`
391 if let Res::Def(..) = res {
392 let res = res.map_id(|_| panic!("unexpected node_id"));
396 Err(ResolutionFailure::NotResolved {
399 unresolved: path_str.into(),
404 /// Convenience wrapper around `resolve_str_path_error`.
406 /// This also handles resolving `true` and `false` as booleans.
407 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
408 /// Associated items will never be resolved by this function.
409 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
410 let result = self.cx.enter_resolver(|resolver| {
411 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
413 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
414 match result.map(|(_, res)| res) {
415 // resolver doesn't know about true and false so we'll have to resolve them
417 Ok(Res::Err) | Err(()) => is_bool_value(path_str, ns).map(|(_, res)| res),
418 Ok(res) => Some(res.map_id(|_| panic!("unexpected node_id"))),
422 /// Resolves a string as a path within a particular namespace. Returns an
423 /// optional URL fragment in the case of variants and methods.
426 path_str: &'path str,
429 extra_fragment: &Option<String>,
430 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
433 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
435 // FIXME(#76467): make this fallthrough to lookup the associated
436 // item a separate function.
437 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => {
438 assert_eq!(ns, ValueNS);
440 Res::Def(DefKind::AssocTy, _) => {
441 assert_eq!(ns, TypeNS);
443 Res::Def(DefKind::Variant, _) => {
444 return handle_variant(cx, res, extra_fragment);
446 // Not a trait item; just return what we found.
448 if extra_fragment.is_some() {
449 return Err(ErrorKind::AnchorFailure(
450 AnchorFailure::RustdocAnchorConflict(res),
453 return Ok((res, Some(ty.name_str().to_owned())));
455 Res::Def(DefKind::Mod, _) => {
456 return Ok((res, extra_fragment.clone()));
459 return Ok((res, extra_fragment.clone()));
464 // Try looking for methods and associated items.
465 let mut split = path_str.rsplitn(2, "::");
466 // NB: `split`'s first element is always defined, even if the delimiter was not present.
467 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
468 let item_str = split.next().unwrap();
469 let item_name = Symbol::intern(item_str);
470 let path_root = split
472 .map(|f| f.to_owned())
473 // If there's no `::`, it's not an associated item.
474 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
476 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
477 ResolutionFailure::NotResolved {
480 unresolved: item_str.into(),
484 // FIXME: are these both necessary?
485 let ty_res = if let Some(ty_res) = resolve_primitive(&path_root, TypeNS)
487 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
491 // FIXME: this is duplicated on the end of this function.
492 return if ns == Namespace::ValueNS {
493 self.variant_field(path_str, module_id)
495 Err(ResolutionFailure::NotResolved {
498 unresolved: path_root.into(),
504 let res = match ty_res {
505 Res::PrimTy(prim) => Some(
506 self.resolve_primitive_associated_item(prim, ns, module_id, item_name, item_str),
513 | DefKind::ForeignTy,
516 debug!("looking for associated item named {} for item {:?}", item_name, did);
517 // Checks if item_name belongs to `impl SomeItem`
523 cx.tcx.associated_items(imp).find_by_name_and_namespace(
525 Ident::with_dummy_span(item_name),
530 .map(|item| (item.kind, item.def_id))
531 // There should only ever be one associated item that matches from any inherent impl
533 // Check if item_name belongs to `impl SomeTrait for SomeItem`
534 // FIXME(#74563): This gives precedence to `impl SomeItem`:
535 // Although having both would be ambiguous, use impl version for compatibility's sake.
536 // To handle that properly resolve() would have to support
537 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
540 resolve_associated_trait_item(did, module_id, item_name, ns, &self.cx);
541 debug!("got associated item kind {:?}", kind);
545 if let Some((kind, id)) = assoc_item {
546 let out = match kind {
547 ty::AssocKind::Fn => "method",
548 ty::AssocKind::Const => "associatedconstant",
549 ty::AssocKind::Type => "associatedtype",
551 Some(if extra_fragment.is_some() {
552 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
554 // HACK(jynelson): `clean` expects the type, not the associated item
555 // but the disambiguator logic expects the associated item.
556 // Store the kind in a side channel so that only the disambiguator logic looks at it.
557 self.kind_side_channel.set(Some((kind.as_def_kind(), id)));
558 Ok((ty_res, Some(format!("{}.{}", out, item_str))))
560 } else if ns == Namespace::ValueNS {
561 debug!("looking for variants or fields named {} for {:?}", item_name, did);
562 // FIXME(jynelson): why is this different from
564 match cx.tcx.type_of(did).kind() {
566 let field = if def.is_enum() {
567 def.all_fields().find(|item| item.ident.name == item_name)
569 def.non_enum_variant()
572 .find(|item| item.ident.name == item_name)
575 if extra_fragment.is_some() {
584 Err(ErrorKind::AnchorFailure(
585 AnchorFailure::RustdocAnchorConflict(res),
592 if def.is_enum() { "variant" } else { "structfield" },
605 Res::Def(DefKind::Trait, did) => cx
607 .associated_items(did)
608 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, did)
610 let kind = match item.kind {
611 ty::AssocKind::Const => "associatedconstant",
612 ty::AssocKind::Type => "associatedtype",
613 ty::AssocKind::Fn => {
614 if item.defaultness.has_value() {
622 if extra_fragment.is_some() {
623 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
625 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
626 Ok((res, Some(format!("{}.{}", kind, item_str))))
631 res.unwrap_or_else(|| {
632 if ns == Namespace::ValueNS {
633 self.variant_field(path_str, module_id)
635 Err(ResolutionFailure::NotResolved {
637 partial_res: Some(ty_res),
638 unresolved: item_str.into(),
645 /// Used for reporting better errors.
647 /// Returns whether the link resolved 'fully' in another namespace.
648 /// 'fully' here means that all parts of the link resolved, not just some path segments.
649 /// This returns the `Res` even if it was erroneous for some reason
650 /// (such as having invalid URL fragments or being in the wrong namespace).
656 extra_fragment: &Option<String>,
658 // resolve() can't be used for macro namespace
659 let result = match ns {
660 Namespace::MacroNS => self.resolve_macro(path_str, module_id).map_err(ErrorKind::from),
661 Namespace::TypeNS | Namespace::ValueNS => {
662 self.resolve(path_str, ns, module_id, extra_fragment).map(|(res, _)| res)
666 let res = match result {
667 Ok(res) => Some(res),
668 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
669 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
670 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
672 self.kind_side_channel.take().map(|(kind, id)| Res::Def(kind, id)).or(res)
676 /// Look to see if a resolved item has an associated item named `item_name`.
678 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
679 /// find `std::error::Error::source` and return
680 /// `<io::Error as error::Error>::source`.
681 fn resolve_associated_trait_item(
687 ) -> Option<(ty::AssocKind, DefId)> {
688 let ty = cx.tcx.type_of(did);
689 // First consider blanket impls: `impl From<T> for T`
690 let implicit_impls = crate::clean::get_auto_trait_and_blanket_impls(cx, ty, did);
691 let mut candidates: Vec<_> = implicit_impls
692 .flat_map(|impl_outer| {
693 match impl_outer.kind {
694 clean::ImplItem(impl_) => {
695 debug!("considering auto or blanket impl for trait {:?}", impl_.trait_);
696 // Give precedence to methods that were overridden
697 if !impl_.provided_trait_methods.contains(&*item_name.as_str()) {
698 let mut items = impl_.items.into_iter().filter_map(|assoc| {
699 if assoc.name.as_deref() != Some(&*item_name.as_str()) {
705 .expect("inner items for a trait should be associated items");
706 if kind.namespace() != ns {
710 trace!("considering associated item {:?}", assoc.kind);
711 // We have a slight issue: normal methods come from `clean` types,
712 // but provided methods come directly from `tcx`.
713 // Fortunately, we don't need the whole method, we just need to know
714 // what kind of associated item it is.
715 Some((kind, assoc.def_id))
717 let assoc = items.next();
718 debug_assert_eq!(items.count(), 0);
721 // These are provided methods or default types:
725 // fn has_default() -> A { 0 }
728 let trait_ = impl_.trait_.unwrap().def_id().unwrap();
730 .associated_items(trait_)
731 .find_by_name_and_namespace(
733 Ident::with_dummy_span(item_name),
737 .map(|assoc| (assoc.kind, assoc.def_id))
740 _ => panic!("get_impls returned something that wasn't an impl"),
745 // Next consider explicit impls: `impl MyTrait for MyType`
746 // Give precedence to inherent impls.
747 if candidates.is_empty() {
748 let traits = traits_implemented_by(cx, did, module);
749 debug!("considering traits {:?}", traits);
750 candidates.extend(traits.iter().filter_map(|&trait_| {
752 .associated_items(trait_)
753 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
754 .map(|assoc| (assoc.kind, assoc.def_id))
757 // FIXME(#74563): warn about ambiguity
758 debug!("the candidates were {:?}", candidates);
762 /// Given a type, return all traits in scope in `module` implemented by that type.
764 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
765 /// So it is not stable to serialize cross-crate.
766 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
767 let mut cache = cx.module_trait_cache.borrow_mut();
768 let in_scope_traits = cache.entry(module).or_insert_with(|| {
769 cx.enter_resolver(|resolver| {
770 resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
774 let ty = cx.tcx.type_of(type_);
775 let iter = in_scope_traits.iter().flat_map(|&trait_| {
776 trace!("considering explicit impl for trait {:?}", trait_);
778 // Look at each trait implementation to see if it's an impl for `did`
779 cx.tcx.find_map_relevant_impl(trait_, ty, |impl_| {
780 let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
781 // Check if these are the same type.
782 let impl_type = trait_ref.self_ty();
784 "comparing type {} with kind {:?} against type {:?}",
789 // Fast path: if this is a primitive simple `==` will work
790 let saw_impl = impl_type == ty
791 || match impl_type.kind() {
792 // Check if these are the same def_id
794 debug!("adt def_id: {:?}", def.did);
797 ty::Foreign(def_id) => *def_id == type_,
801 if saw_impl { Some(trait_) } else { None }
807 /// Check for resolve collisions between a trait and its derive.
809 /// These are common and we should just resolve to the trait in that case.
810 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
811 matches!(*ns, PerNS {
812 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
813 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
818 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
819 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
820 use rustc_middle::ty::DefIdTree;
822 let parent_node = if item.is_fake() {
823 // FIXME: is this correct?
825 // If we're documenting the crate root itself, it has no parent. Use the root instead.
826 } else if item.def_id.is_top_level_module() {
829 let mut current = item.def_id;
830 // The immediate parent might not always be a module.
831 // Find the first parent which is.
833 if let Some(parent) = self.cx.tcx.parent(current) {
834 if self.cx.tcx.def_kind(parent) == DefKind::Mod {
840 "{:?} has no parent (kind={:?}, original was {:?})",
842 self.cx.tcx.def_kind(current),
850 if parent_node.is_some() {
851 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
854 // find item's parent to resolve `Self` in item's docs below
855 debug!("looking for the `Self` type");
856 let self_id = if item.is_fake() {
859 self.cx.tcx.def_kind(item.def_id),
866 self.cx.tcx.parent(item.def_id)
867 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
868 // Fixing this breaks `fn render_deref_methods`.
869 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
870 // regardless of what rustdoc wants to call it.
871 } else if let Some(parent) = self.cx.tcx.parent(item.def_id) {
872 let parent_kind = self.cx.tcx.def_kind(parent);
873 Some(if parent_kind == DefKind::Impl { parent } else { item.def_id })
878 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
879 let self_name = self_id.and_then(|self_id| {
881 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
882 // using `ty.to_string()` (or any variant) has issues with raw idents
883 let ty = self.cx.tcx.type_of(self_id);
884 let name = match ty.kind() {
885 TyKind::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
886 other if other.is_primitive() => Some(ty.to_string()),
889 debug!("using type_of(): {:?}", name);
892 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
893 debug!("using item_name(): {:?}", name);
898 if item.is_mod() && item.attrs.inner_docs {
899 self.mod_ids.push(item.def_id);
902 // We want to resolve in the lexical scope of the documentation.
903 // In the presence of re-exports, this is not the same as the module of the item.
904 // Rather than merging all documentation into one, resolve it one attribute at a time
905 // so we know which module it came from.
906 let mut attrs = item.attrs.doc_strings.iter().peekable();
907 while let Some(attr) = attrs.next() {
908 // `collapse_docs` does not have the behavior we want:
909 // we want `///` and `#[doc]` to count as the same attribute,
910 // but currently it will treat them as separate.
911 // As a workaround, combine all attributes with the same parent module into the same attribute.
912 let mut combined_docs = attr.doc.clone();
915 Some(next) if next.parent_module == attr.parent_module => {
916 combined_docs.push('\n');
917 combined_docs.push_str(&attrs.next().unwrap().doc);
922 debug!("combined_docs={}", combined_docs);
924 let (krate, parent_node) = if let Some(id) = attr.parent_module {
925 trace!("docs {:?} came from {:?}", attr.doc, id);
928 trace!("no parent found for {:?}", attr.doc);
929 (item.def_id.krate, parent_node)
931 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
932 // This is a degenerate case and it's not supported by rustdoc.
933 for (ori_link, link_range) in markdown_links(&combined_docs) {
934 let link = self.resolve_link(
943 if let Some(link) = link {
944 item.attrs.links.push(link);
949 Some(if item.is_mod() {
950 if !item.attrs.inner_docs {
951 self.mod_ids.push(item.def_id);
954 let ret = self.fold_item_recur(item);
958 self.fold_item_recur(item)
963 impl LinkCollector<'_, '_> {
964 /// This is the entry point for resolving an intra-doc link.
966 /// FIXME(jynelson): this is way too many arguments
971 self_name: &Option<String>,
972 parent_node: Option<DefId>,
975 link_range: Option<Range<usize>>,
976 ) -> Option<ItemLink> {
977 trace!("considering link '{}'", ori_link);
979 // Bail early for real links.
980 if ori_link.contains('/') {
984 // [] is mostly likely not supposed to be a link
985 if ori_link.is_empty() {
990 let link = ori_link.replace("`", "");
991 let parts = link.split('#').collect::<Vec<_>>();
992 let (link, extra_fragment) = if parts.len() > 2 {
993 // A valid link can't have multiple #'s
994 anchor_failure(cx, &item, &link, dox, link_range, AnchorFailure::MultipleAnchors);
996 } else if parts.len() == 2 {
997 if parts[0].trim().is_empty() {
998 // This is an anchor to an element of the current page, nothing to do in here!
1001 (parts[0], Some(parts[1].to_owned()))
1006 // Parse and strip the disambiguator from the link, if present.
1007 let (mut path_str, disambiguator) = if let Ok((d, path)) = Disambiguator::from_str(&link) {
1008 (path.trim(), Some(d))
1013 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !".contains(ch))) {
1017 // We stripped `()` and `!` when parsing the disambiguator.
1018 // Add them back to be displayed, but not prefix disambiguators.
1020 disambiguator.map(|d| d.display_for(path_str)).unwrap_or_else(|| path_str.to_owned());
1022 // In order to correctly resolve intra-doc-links we need to
1023 // pick a base AST node to work from. If the documentation for
1024 // this module came from an inner comment (//!) then we anchor
1025 // our name resolution *inside* the module. If, on the other
1026 // hand it was an outer comment (///) then we anchor the name
1027 // resolution in the parent module on the basis that the names
1028 // used are more likely to be intended to be parent names. For
1029 // this, we set base_node to None for inner comments since
1030 // we've already pushed this node onto the resolution stack but
1031 // for outer comments we explicitly try and resolve against the
1032 // parent_node first.
1033 let base_node = if item.is_mod() && item.attrs.inner_docs {
1034 self.mod_ids.last().copied()
1039 let mut module_id = if let Some(id) = base_node {
1043 debug!("attempting to resolve item without parent module: {}", path_str);
1051 smallvec![ResolutionFailure::NoParentItem],
1057 // replace `Self` with suitable item's parent name
1058 if path_str.starts_with("Self::") {
1059 if let Some(ref name) = self_name {
1060 resolved_self = format!("{}::{}", name, &path_str[6..]);
1061 path_str = &resolved_self;
1063 } else if path_str.starts_with("crate::") {
1064 use rustc_span::def_id::CRATE_DEF_INDEX;
1066 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1067 // But rustdoc wants it to mean the crate this item was originally present in.
1068 // To work around this, remove it and resolve relative to the crate root instead.
1069 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1070 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1071 // FIXME(#78696): This doesn't always work.
1072 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1073 path_str = &resolved_self;
1074 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1077 // Strip generics from the path.
1078 let stripped_path_string;
1079 if path_str.contains(['<', '>'].as_slice()) {
1080 stripped_path_string = match strip_generics_from_path(path_str) {
1083 debug!("link has malformed generics: {}", path_str);
1091 smallvec![err_kind],
1096 path_str = &stripped_path_string;
1098 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1099 assert!(!path_str.contains(['<', '>'].as_slice()));
1101 // The link is not an intra-doc link if it still contains commas or spaces after
1102 // stripping generics.
1103 if path_str.contains([',', ' '].as_slice()) {
1107 let key = ResolutionInfo {
1110 path_str: path_str.to_owned(),
1114 DiagnosticInfo { item, dox, ori_link: &ori_link, link_range: link_range.clone() };
1115 let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(key, diag)?;
1117 // Check for a primitive which might conflict with a module
1118 // Report the ambiguity and require that the user specify which one they meant.
1119 // FIXME: could there ever be a primitive not in the type namespace?
1122 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1123 ) && !matches!(res, Res::PrimTy(_))
1125 if let Some((path, prim)) = resolve_primitive(path_str, TypeNS) {
1127 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1128 if fragment.is_some() {
1135 AnchorFailure::RustdocAnchorConflict(prim),
1140 fragment = Some(path.as_str().to_string());
1142 // `[char]` when a `char` module is in scope
1143 let candidates = vec![res, prim];
1144 ambiguity_error(cx, &item, path_str, dox, link_range, candidates);
1150 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1151 // The resolved item did not match the disambiguator; give a better error than 'not found'
1152 let msg = format!("incompatible link kind for `{}`", path_str);
1153 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1155 "this link resolved to {} {}, which is not {} {}",
1158 specified.article(),
1162 suggest_disambiguator(resolved, diag, path_str, dox, sp, &link_range);
1164 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, &item, dox, &link_range, callback);
1166 if let Res::PrimTy(..) = res {
1167 match disambiguator {
1168 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
1169 Some(ItemLink { link: ori_link, link_text, did: None, fragment })
1172 report_mismatch(other, Disambiguator::Primitive);
1177 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
1179 // Disallow e.g. linking to enums with `struct@`
1180 if let Res::Def(kind, _) = res {
1181 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1182 match (self.kind_side_channel.take().map(|(kind, _)| kind).unwrap_or(kind), disambiguator) {
1183 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1184 // NOTE: this allows 'method' to mean both normal functions and associated functions
1185 // This can't cause ambiguity because both are in the same namespace.
1186 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1187 // These are namespaces; allow anything in the namespace to match
1188 | (_, Some(Disambiguator::Namespace(_)))
1189 // If no disambiguator given, allow anything
1191 // All of these are valid, so do nothing
1193 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1194 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1195 report_mismatch(specified, Disambiguator::Kind(kind));
1201 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1202 if let Some((src_id, dst_id)) = res
1204 .and_then(|def_id| def_id.as_local())
1205 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
1207 use rustc_hir::def_id::LOCAL_CRATE;
1209 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1210 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1212 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
1213 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
1215 privacy_error(cx, &item, &path_str, dox, link_range);
1218 let id = clean::register_res(cx, res);
1219 Some(ItemLink { link: ori_link, link_text, did: Some(id), fragment })
1223 fn resolve_with_disambiguator_cached(
1225 key: ResolutionInfo,
1226 diag: DiagnosticInfo<'_>,
1227 ) -> Option<(Res, Option<String>)> {
1228 // Try to look up both the result and the corresponding side channel value
1229 if let Some(ref cached) = self.visited_links.get(&key) {
1230 self.kind_side_channel.set(cached.side_channel.clone());
1231 return Some(cached.res.clone());
1234 let res = self.resolve_with_disambiguator(&key, diag);
1236 // Cache only if resolved successfully - don't silence duplicate errors
1237 if let Some(res) = &res {
1238 // Store result for the actual namespace
1239 self.visited_links.insert(
1243 side_channel: self.kind_side_channel.clone().into_inner(),
1251 /// After parsing the disambiguator, resolve the main part of the link.
1252 // FIXME(jynelson): wow this is just so much
1253 fn resolve_with_disambiguator(
1255 key: &ResolutionInfo,
1256 diag: DiagnosticInfo<'_>,
1257 ) -> Option<(Res, Option<String>)> {
1258 let disambiguator = key.dis;
1259 let path_str = &key.path_str;
1260 let base_node = key.module_id;
1261 let extra_fragment = &key.extra_fragment;
1263 match disambiguator.map(Disambiguator::ns) {
1264 Some(ns @ (ValueNS | TypeNS)) => {
1265 match self.resolve(path_str, ns, base_node, extra_fragment) {
1266 Ok(res) => Some(res),
1267 Err(ErrorKind::Resolve(box mut kind)) => {
1268 // We only looked in one namespace. Try to give a better error if possible.
1269 if kind.full_res().is_none() {
1270 let other_ns = if ns == ValueNS { TypeNS } else { ValueNS };
1271 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1272 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1273 for &new_ns in &[other_ns, MacroNS] {
1275 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1277 kind = ResolutionFailure::WrongNamespace(res, ns);
1291 // This could just be a normal link or a broken link
1292 // we could potentially check if something is
1293 // "intra-doc-link-like" and warn in that case.
1296 Err(ErrorKind::AnchorFailure(msg)) => {
1311 let mut candidates = PerNS {
1313 .resolve_macro(path_str, base_node)
1314 .map(|res| (res, extra_fragment.clone())),
1315 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1317 debug!("got res in TypeNS: {:?}", res);
1320 Err(ErrorKind::AnchorFailure(msg)) => {
1331 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1333 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1335 Err(ErrorKind::AnchorFailure(msg)) => {
1346 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1348 .and_then(|(res, fragment)| {
1349 // Constructors are picked up in the type namespace.
1351 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => {
1352 Err(ResolutionFailure::WrongNamespace(res, TypeNS))
1354 _ => match (fragment, extra_fragment.clone()) {
1355 (Some(fragment), Some(_)) => {
1356 // Shouldn't happen but who knows?
1357 Ok((res, Some(fragment)))
1359 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1365 let len = candidates.iter().filter(|res| res.is_ok()).count();
1375 candidates.into_iter().filter_map(|res| res.err()).collect(),
1377 // this could just be a normal link
1382 Some(candidates.into_iter().filter_map(|res| res.ok()).next().unwrap())
1383 } else if len == 2 && is_derive_trait_collision(&candidates) {
1384 Some(candidates.type_ns.unwrap())
1386 if is_derive_trait_collision(&candidates) {
1387 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1389 // If we're reporting an ambiguity, don't mention the namespaces that failed
1390 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1397 candidates.present_items().collect(),
1403 match self.resolve_macro(path_str, base_node) {
1404 Ok(res) => Some((res, extra_fragment.clone())),
1406 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1407 for &ns in &[TypeNS, ValueNS] {
1409 self.check_full_res(ns, path_str, base_node, extra_fragment)
1411 kind = ResolutionFailure::WrongNamespace(res, MacroNS);
1432 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1433 /// Disambiguators for a link.
1434 enum Disambiguator {
1437 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1439 /// `struct@` or `f()`
1442 Namespace(Namespace),
1445 impl Disambiguator {
1446 /// The text that should be displayed when the path is rendered as HTML.
1448 /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1449 fn display_for(&self, path: &str) -> String {
1451 // FIXME: this will have different output if the user had `m!()` originally.
1452 Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1453 Self::Kind(DefKind::Fn) => format!("{}()", path),
1454 _ => path.to_owned(),
1458 /// Given a link, parse and return `(disambiguator, path_str)`
1459 fn from_str(link: &str) -> Result<(Self, &str), ()> {
1460 use Disambiguator::{Kind, Namespace as NS, Primitive};
1462 let find_suffix = || {
1464 ("!()", DefKind::Macro(MacroKind::Bang)),
1465 ("()", DefKind::Fn),
1466 ("!", DefKind::Macro(MacroKind::Bang)),
1468 for &(suffix, kind) in &suffixes {
1469 if link.ends_with(suffix) {
1470 return Ok((Kind(kind), link.trim_end_matches(suffix)));
1476 if let Some(idx) = link.find('@') {
1477 let (prefix, rest) = link.split_at(idx);
1478 let d = match prefix {
1479 "struct" => Kind(DefKind::Struct),
1480 "enum" => Kind(DefKind::Enum),
1481 "trait" => Kind(DefKind::Trait),
1482 "union" => Kind(DefKind::Union),
1483 "module" | "mod" => Kind(DefKind::Mod),
1484 "const" | "constant" => Kind(DefKind::Const),
1485 "static" => Kind(DefKind::Static),
1486 "function" | "fn" | "method" => Kind(DefKind::Fn),
1487 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1488 "type" => NS(Namespace::TypeNS),
1489 "value" => NS(Namespace::ValueNS),
1490 "macro" => NS(Namespace::MacroNS),
1491 "prim" | "primitive" => Primitive,
1492 _ => return find_suffix(),
1500 /// WARNING: panics on `Res::Err`
1501 fn from_res(res: Res) -> Self {
1503 Res::Def(kind, _) => Disambiguator::Kind(kind),
1504 Res::PrimTy(_) => Disambiguator::Primitive,
1505 _ => Disambiguator::Namespace(res.ns().expect("can't call `from_res` on Res::err")),
1509 /// Used for error reporting.
1510 fn suggestion(self) -> Suggestion {
1511 let kind = match self {
1512 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1513 Disambiguator::Kind(kind) => kind,
1514 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1516 if kind == DefKind::Macro(MacroKind::Bang) {
1517 return Suggestion::Macro;
1518 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1519 return Suggestion::Function;
1522 let prefix = match kind {
1523 DefKind::Struct => "struct",
1524 DefKind::Enum => "enum",
1525 DefKind::Trait => "trait",
1526 DefKind::Union => "union",
1527 DefKind::Mod => "mod",
1528 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1531 DefKind::Static => "static",
1532 DefKind::Macro(MacroKind::Derive) => "derive",
1533 // Now handle things that don't have a specific disambiguator
1536 .expect("tried to calculate a disambiguator for a def without a namespace?")
1538 Namespace::TypeNS => "type",
1539 Namespace::ValueNS => "value",
1540 Namespace::MacroNS => "macro",
1544 Suggestion::Prefix(prefix)
1547 fn ns(self) -> Namespace {
1549 Self::Namespace(n) => n,
1551 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1553 Self::Primitive => TypeNS,
1557 fn article(self) -> &'static str {
1559 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1560 Self::Kind(k) => k.article(),
1561 Self::Primitive => "a",
1565 fn descr(self) -> &'static str {
1567 Self::Namespace(n) => n.descr(),
1568 // HACK(jynelson): by looking at the source I saw the DefId we pass
1569 // for `expected.descr()` doesn't matter, since it's not a crate
1570 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1571 Self::Primitive => "builtin type",
1576 /// A suggestion to show in a diagnostic.
1579 Prefix(&'static str),
1587 fn descr(&self) -> Cow<'static, str> {
1589 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1590 Self::Function => "add parentheses".into(),
1591 Self::Macro => "add an exclamation mark".into(),
1595 fn as_help(&self, path_str: &str) -> String {
1596 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1598 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1599 Self::Function => format!("{}()", path_str),
1600 Self::Macro => format!("{}!", path_str),
1605 /// Reports a diagnostic for an intra-doc link.
1607 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1608 /// the entire documentation block is used for the lint. If a range is provided but the span
1609 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1611 /// The `decorate` callback is invoked in all cases to allow further customization of the
1612 /// diagnostic before emission. If the span of the link was able to be determined, the second
1613 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1615 fn report_diagnostic(
1616 cx: &DocContext<'_>,
1617 lint: &'static Lint,
1621 link_range: &Option<Range<usize>>,
1622 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1624 let hir_id = match cx.as_local_hir_id(item.def_id) {
1625 Some(hir_id) => hir_id,
1627 // If non-local, no need to check anything.
1628 info!("ignoring warning from parent crate: {}", msg);
1633 let attrs = &item.attrs;
1634 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1636 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1637 let mut diag = lint.build(msg);
1639 let span = link_range
1641 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
1643 if let Some(link_range) = link_range {
1644 if let Some(sp) = span {
1647 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1650 // last_new_line_offset
1651 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1652 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1654 // Print the line containing the `link_range` and manually mark it with '^'s.
1656 "the link appears in this line:\n\n{line}\n\
1657 {indicator: <before$}{indicator:^<found$}",
1660 before = link_range.start - last_new_line_offset,
1661 found = link_range.len(),
1666 decorate(&mut diag, span);
1672 /// Reports a link that failed to resolve.
1674 /// This also tries to resolve any intermediate path segments that weren't
1675 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1676 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1677 fn resolution_failure(
1678 collector: &LinkCollector<'_, '_>,
1681 disambiguator: Option<Disambiguator>,
1683 link_range: Option<Range<usize>>,
1684 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1688 BROKEN_INTRA_DOC_LINKS,
1689 &format!("unresolved link to `{}`", path_str),
1694 let item = |res: Res| {
1698 collector.cx.tcx.item_name(res.def_id()).to_string()
1701 let assoc_item_not_allowed = |res: Res| {
1702 let def_id = res.def_id();
1703 let name = collector.cx.tcx.item_name(def_id);
1705 "`{}` is {} {}, not a module or type, and cannot have associated items",
1711 // ignore duplicates
1712 let mut variants_seen = SmallVec::<[_; 3]>::new();
1713 for mut failure in kinds {
1714 let variant = std::mem::discriminant(&failure);
1715 if variants_seen.contains(&variant) {
1718 variants_seen.push(variant);
1720 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1725 let module_id = *module_id;
1726 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1727 // FIXME: maybe use itertools `collect_tuple` instead?
1728 fn split(path: &str) -> Option<(&str, &str)> {
1729 let mut splitter = path.rsplitn(2, "::");
1730 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1733 // Check if _any_ parent of the path gets resolved.
1734 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1735 let mut name = path_str;
1737 let (start, end) = if let Some(x) = split(name) {
1740 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1741 if partial_res.is_none() {
1742 *unresolved = name.into();
1747 for &ns in &[TypeNS, ValueNS, MacroNS] {
1749 collector.check_full_res(ns, &start, module_id, &None)
1751 debug!("found partial_res={:?}", res);
1752 *partial_res = Some(res);
1753 *unresolved = end.into();
1757 *unresolved = end.into();
1760 let last_found_module = match *partial_res {
1761 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1762 None => Some(module_id),
1765 // See if this was a module: `[path]` or `[std::io::nope]`
1766 if let Some(module) = last_found_module {
1767 let note = if partial_res.is_some() {
1768 // Part of the link resolved; e.g. `std::io::nonexistent`
1769 let module_name = collector.cx.tcx.item_name(module);
1770 format!("no item named `{}` in module `{}`", unresolved, module_name)
1772 // None of the link resolved; e.g. `Notimported`
1773 format!("no item named `{}` in scope", unresolved)
1775 if let Some(span) = sp {
1776 diag.span_label(span, ¬e);
1781 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1782 // Otherwise, the `[]` might be unrelated.
1783 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1784 if !path_str.contains("::") {
1785 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1791 // Otherwise, it must be an associated item or variant
1792 let res = partial_res.expect("None case was handled by `last_found_module`");
1793 let diagnostic_name;
1794 let (kind, name) = match res {
1795 Res::Def(kind, def_id) => {
1796 diagnostic_name = collector.cx.tcx.item_name(def_id).as_str();
1797 (Some(kind), &*diagnostic_name)
1799 Res::PrimTy(ty) => (None, ty.name_str()),
1800 _ => unreachable!("only ADTs and primitives are in scope at module level"),
1802 let path_description = if let Some(kind) = kind {
1804 Mod | ForeignMod => "inner item",
1805 Struct => "field or associated item",
1806 Enum | Union => "variant or associated item",
1823 let note = assoc_item_not_allowed(res);
1824 if let Some(span) = sp {
1825 diag.span_label(span, ¬e);
1831 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1832 | Static => "associated item",
1833 Impl | GlobalAsm => unreachable!("not a path"),
1839 "the {} `{}` has no {} named `{}`",
1842 disambiguator.map_or(path_description, |d| d.descr()),
1845 if let Some(span) = sp {
1846 diag.span_label(span, ¬e);
1853 let note = match failure {
1854 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1855 ResolutionFailure::Dummy => continue,
1856 ResolutionFailure::WrongNamespace(res, expected_ns) => {
1857 if let Res::Def(kind, _) = res {
1858 let disambiguator = Disambiguator::Kind(kind);
1859 suggest_disambiguator(
1870 "this link resolves to {}, which is not in the {} namespace",
1875 ResolutionFailure::NoParentItem => {
1876 diag.level = rustc_errors::Level::Bug;
1877 "all intra doc links should have a parent item".to_owned()
1879 ResolutionFailure::MalformedGenerics(variant) => match variant {
1880 MalformedGenerics::UnbalancedAngleBrackets => {
1881 String::from("unbalanced angle brackets")
1883 MalformedGenerics::MissingType => {
1884 String::from("missing type for generic parameters")
1886 MalformedGenerics::HasFullyQualifiedSyntax => {
1887 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1888 String::from("fully-qualified syntax is unsupported")
1890 MalformedGenerics::InvalidPathSeparator => {
1891 String::from("has invalid path separator")
1893 MalformedGenerics::TooManyAngleBrackets => {
1894 String::from("too many angle brackets")
1896 MalformedGenerics::EmptyAngleBrackets => {
1897 String::from("empty angle brackets")
1901 if let Some(span) = sp {
1902 diag.span_label(span, ¬e);
1911 /// Report an anchor failure.
1913 cx: &DocContext<'_>,
1917 link_range: Option<Range<usize>>,
1918 failure: AnchorFailure,
1920 let msg = match failure {
1921 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1922 AnchorFailure::RustdocAnchorConflict(res) => format!(
1923 "`{}` contains an anchor, but links to {kind}s are already anchored",
1929 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1930 if let Some(sp) = sp {
1931 diag.span_label(sp, "contains invalid anchor");
1936 /// Report an ambiguity error, where there were multiple possible resolutions.
1938 cx: &DocContext<'_>,
1942 link_range: Option<Range<usize>>,
1943 candidates: Vec<Res>,
1945 let mut msg = format!("`{}` is ", path_str);
1947 match candidates.as_slice() {
1948 [first_def, second_def] => {
1950 "both {} {} and {} {}",
1951 first_def.article(),
1953 second_def.article(),
1958 let mut candidates = candidates.iter().peekable();
1959 while let Some(res) = candidates.next() {
1960 if candidates.peek().is_some() {
1961 msg += &format!("{} {}, ", res.article(), res.descr());
1963 msg += &format!("and {} {}", res.article(), res.descr());
1969 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1970 if let Some(sp) = sp {
1971 diag.span_label(sp, "ambiguous link");
1973 diag.note("ambiguous link");
1976 for res in candidates {
1977 let disambiguator = Disambiguator::from_res(res);
1978 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1983 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
1985 fn suggest_disambiguator(
1986 disambiguator: Disambiguator,
1987 diag: &mut DiagnosticBuilder<'_>,
1990 sp: Option<rustc_span::Span>,
1991 link_range: &Option<Range<usize>>,
1993 let suggestion = disambiguator.suggestion();
1994 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
1996 if let Some(sp) = sp {
1997 let link_range = link_range.as_ref().expect("must have a link range if we have a span");
1998 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
1999 format!("`{}`", suggestion.as_help(path_str))
2001 suggestion.as_help(path_str)
2004 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
2006 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2010 /// Report a link from a public item to a private one.
2012 cx: &DocContext<'_>,
2016 link_range: Option<Range<usize>>,
2018 let item_name = item.name.as_deref().unwrap_or("<unknown>");
2020 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2022 report_diagnostic(cx, PRIVATE_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
2023 if let Some(sp) = sp {
2024 diag.span_label(sp, "this item is private");
2027 let note_msg = if cx.render_options.document_private {
2028 "this link resolves only because you passed `--document-private-items`, but will break without"
2030 "this link will resolve properly if you pass `--document-private-items`"
2032 diag.note(note_msg);
2036 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2038 cx: &DocContext<'_>,
2040 extra_fragment: &Option<String>,
2041 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
2042 use rustc_middle::ty::DefIdTree;
2044 if extra_fragment.is_some() {
2045 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2048 .parent(res.def_id())
2050 let parent_def = Res::Def(DefKind::Enum, parent);
2051 let variant = cx.tcx.expect_variant_res(res);
2052 (parent_def, Some(format!("variant.{}", variant.ident.name)))
2054 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2057 // FIXME: At this point, this is basically a copy of the PrimitiveTypeTable
2058 const PRIMITIVES: &[(Symbol, Res)] = &[
2059 (sym::u8, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
2060 (sym::u16, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
2061 (sym::u32, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
2062 (sym::u64, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
2063 (sym::u128, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
2064 (sym::usize, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
2065 (sym::i8, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
2066 (sym::i16, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
2067 (sym::i32, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
2068 (sym::i64, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
2069 (sym::i128, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
2070 (sym::isize, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
2071 (sym::f32, Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
2072 (sym::f64, Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
2073 (sym::str, Res::PrimTy(hir::PrimTy::Str)),
2074 (sym::bool, Res::PrimTy(hir::PrimTy::Bool)),
2075 (sym::char, Res::PrimTy(hir::PrimTy::Char)),
2078 /// Resolve a primitive type or value.
2079 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<(Symbol, Res)> {
2080 is_bool_value(path_str, ns).or_else(|| {
2082 // FIXME: this should be replaced by a lookup in PrimitiveTypeTable
2083 let maybe_primitive = Symbol::intern(path_str);
2084 PRIMITIVES.iter().find(|x| x.0 == maybe_primitive).copied()
2091 /// Resolve a primitive value.
2092 fn is_bool_value(path_str: &str, ns: Namespace) -> Option<(Symbol, Res)> {
2093 if ns == TypeNS && (path_str == "true" || path_str == "false") {
2094 Some((sym::bool, Res::PrimTy(hir::PrimTy::Bool)))
2100 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2101 let mut stripped_segments = vec![];
2102 let mut path = path_str.chars().peekable();
2103 let mut segment = Vec::new();
2105 while let Some(chr) = path.next() {
2108 if path.next_if_eq(&':').is_some() {
2109 let stripped_segment =
2110 strip_generics_from_path_segment(mem::take(&mut segment))?;
2111 if !stripped_segment.is_empty() {
2112 stripped_segments.push(stripped_segment);
2115 return Err(ResolutionFailure::MalformedGenerics(
2116 MalformedGenerics::InvalidPathSeparator,
2125 return Err(ResolutionFailure::MalformedGenerics(
2126 MalformedGenerics::TooManyAngleBrackets,
2130 return Err(ResolutionFailure::MalformedGenerics(
2131 MalformedGenerics::EmptyAngleBrackets,
2137 while let Some(chr) = path.next_if(|c| *c != '>') {
2144 _ => segment.push(chr),
2146 trace!("raw segment: {:?}", segment);
2149 if !segment.is_empty() {
2150 let stripped_segment = strip_generics_from_path_segment(segment)?;
2151 if !stripped_segment.is_empty() {
2152 stripped_segments.push(stripped_segment);
2156 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2158 let stripped_path = stripped_segments.join("::");
2160 if !stripped_path.is_empty() {
2163 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2167 fn strip_generics_from_path_segment(
2169 ) -> Result<String, ResolutionFailure<'static>> {
2170 let mut stripped_segment = String::new();
2171 let mut param_depth = 0;
2173 let mut latest_generics_chunk = String::new();
2178 latest_generics_chunk.clear();
2179 } else if c == '>' {
2181 if latest_generics_chunk.contains(" as ") {
2182 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2183 // Give a helpful error message instead of completely ignoring the angle brackets.
2184 return Err(ResolutionFailure::MalformedGenerics(
2185 MalformedGenerics::HasFullyQualifiedSyntax,
2189 if param_depth == 0 {
2190 stripped_segment.push(c);
2192 latest_generics_chunk.push(c);
2197 if param_depth == 0 {
2198 Ok(stripped_segment)
2200 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2201 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))