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, 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 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
689 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
690 // meantime, just don't look for these blanket impls.
692 // Next consider explicit impls: `impl MyTrait for MyType`
693 // Give precedence to inherent impls.
694 let traits = traits_implemented_by(cx, did, module);
695 debug!("considering traits {:?}", traits);
696 let mut candidates = traits.iter().filter_map(|&trait_| {
698 .associated_items(trait_)
699 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
700 .map(|assoc| (assoc.kind, assoc.def_id))
702 // FIXME(#74563): warn about ambiguity
703 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
707 /// Given a type, return all traits in scope in `module` implemented by that type.
709 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
710 /// So it is not stable to serialize cross-crate.
711 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
712 let mut cache = cx.module_trait_cache.borrow_mut();
713 let in_scope_traits = cache.entry(module).or_insert_with(|| {
714 cx.enter_resolver(|resolver| {
715 resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
719 let ty = cx.tcx.type_of(type_);
720 let iter = in_scope_traits.iter().flat_map(|&trait_| {
721 trace!("considering explicit impl for trait {:?}", trait_);
723 // Look at each trait implementation to see if it's an impl for `did`
724 cx.tcx.find_map_relevant_impl(trait_, ty, |impl_| {
725 let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
726 // Check if these are the same type.
727 let impl_type = trait_ref.self_ty();
729 "comparing type {} with kind {:?} against type {:?}",
734 // Fast path: if this is a primitive simple `==` will work
735 let saw_impl = impl_type == ty
736 || match impl_type.kind() {
737 // Check if these are the same def_id
739 debug!("adt def_id: {:?}", def.did);
742 ty::Foreign(def_id) => *def_id == type_,
746 if saw_impl { Some(trait_) } else { None }
752 /// Check for resolve collisions between a trait and its derive.
754 /// These are common and we should just resolve to the trait in that case.
755 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
756 matches!(*ns, PerNS {
757 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
758 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
763 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
764 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
765 use rustc_middle::ty::DefIdTree;
767 let parent_node = if item.is_fake() {
768 // FIXME: is this correct?
770 // If we're documenting the crate root itself, it has no parent. Use the root instead.
771 } else if item.def_id.is_top_level_module() {
774 let mut current = item.def_id;
775 // The immediate parent might not always be a module.
776 // Find the first parent which is.
778 if let Some(parent) = self.cx.tcx.parent(current) {
779 if self.cx.tcx.def_kind(parent) == DefKind::Mod {
785 "{:?} has no parent (kind={:?}, original was {:?})",
787 self.cx.tcx.def_kind(current),
795 if parent_node.is_some() {
796 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
799 // find item's parent to resolve `Self` in item's docs below
800 debug!("looking for the `Self` type");
801 let self_id = if item.is_fake() {
804 self.cx.tcx.def_kind(item.def_id),
811 self.cx.tcx.parent(item.def_id)
812 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
813 // Fixing this breaks `fn render_deref_methods`.
814 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
815 // regardless of what rustdoc wants to call it.
816 } else if let Some(parent) = self.cx.tcx.parent(item.def_id) {
817 let parent_kind = self.cx.tcx.def_kind(parent);
818 Some(if parent_kind == DefKind::Impl { parent } else { item.def_id })
823 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
824 let self_name = self_id.and_then(|self_id| {
826 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
827 // using `ty.to_string()` (or any variant) has issues with raw idents
828 let ty = self.cx.tcx.type_of(self_id);
829 let name = match ty.kind() {
830 TyKind::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
831 other if other.is_primitive() => Some(ty.to_string()),
834 debug!("using type_of(): {:?}", name);
837 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
838 debug!("using item_name(): {:?}", name);
843 if item.is_mod() && item.attrs.inner_docs {
844 self.mod_ids.push(item.def_id);
847 // We want to resolve in the lexical scope of the documentation.
848 // In the presence of re-exports, this is not the same as the module of the item.
849 // Rather than merging all documentation into one, resolve it one attribute at a time
850 // so we know which module it came from.
851 let mut attrs = item.attrs.doc_strings.iter().peekable();
852 while let Some(attr) = attrs.next() {
853 // `collapse_docs` does not have the behavior we want:
854 // we want `///` and `#[doc]` to count as the same attribute,
855 // but currently it will treat them as separate.
856 // As a workaround, combine all attributes with the same parent module into the same attribute.
857 let mut combined_docs = attr.doc.clone();
860 Some(next) if next.parent_module == attr.parent_module => {
861 combined_docs.push('\n');
862 combined_docs.push_str(&attrs.next().unwrap().doc);
867 debug!("combined_docs={}", combined_docs);
869 let (krate, parent_node) = if let Some(id) = attr.parent_module {
870 trace!("docs {:?} came from {:?}", attr.doc, id);
873 trace!("no parent found for {:?}", attr.doc);
874 (item.def_id.krate, parent_node)
876 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
877 // This is a degenerate case and it's not supported by rustdoc.
878 for (ori_link, link_range) in markdown_links(&combined_docs) {
879 let link = self.resolve_link(
888 if let Some(link) = link {
889 item.attrs.links.push(link);
894 Some(if item.is_mod() {
895 if !item.attrs.inner_docs {
896 self.mod_ids.push(item.def_id);
899 let ret = self.fold_item_recur(item);
903 self.fold_item_recur(item)
908 impl LinkCollector<'_, '_> {
909 /// This is the entry point for resolving an intra-doc link.
911 /// FIXME(jynelson): this is way too many arguments
916 self_name: &Option<String>,
917 parent_node: Option<DefId>,
920 link_range: Option<Range<usize>>,
921 ) -> Option<ItemLink> {
922 trace!("considering link '{}'", ori_link);
924 // Bail early for real links.
925 if ori_link.contains('/') {
929 // [] is mostly likely not supposed to be a link
930 if ori_link.is_empty() {
935 let link = ori_link.replace("`", "");
936 let parts = link.split('#').collect::<Vec<_>>();
937 let (link, extra_fragment) = if parts.len() > 2 {
938 // A valid link can't have multiple #'s
939 anchor_failure(cx, &item, &link, dox, link_range, AnchorFailure::MultipleAnchors);
941 } else if parts.len() == 2 {
942 if parts[0].trim().is_empty() {
943 // This is an anchor to an element of the current page, nothing to do in here!
946 (parts[0], Some(parts[1].to_owned()))
951 // Parse and strip the disambiguator from the link, if present.
952 let (mut path_str, disambiguator) = if let Ok((d, path)) = Disambiguator::from_str(&link) {
953 (path.trim(), Some(d))
958 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !".contains(ch))) {
962 // We stripped `()` and `!` when parsing the disambiguator.
963 // Add them back to be displayed, but not prefix disambiguators.
965 disambiguator.map(|d| d.display_for(path_str)).unwrap_or_else(|| path_str.to_owned());
967 // In order to correctly resolve intra-doc-links we need to
968 // pick a base AST node to work from. If the documentation for
969 // this module came from an inner comment (//!) then we anchor
970 // our name resolution *inside* the module. If, on the other
971 // hand it was an outer comment (///) then we anchor the name
972 // resolution in the parent module on the basis that the names
973 // used are more likely to be intended to be parent names. For
974 // this, we set base_node to None for inner comments since
975 // we've already pushed this node onto the resolution stack but
976 // for outer comments we explicitly try and resolve against the
977 // parent_node first.
978 let base_node = if item.is_mod() && item.attrs.inner_docs {
979 self.mod_ids.last().copied()
984 let mut module_id = if let Some(id) = base_node {
988 debug!("attempting to resolve item without parent module: {}", path_str);
996 smallvec![ResolutionFailure::NoParentItem],
1002 // replace `Self` with suitable item's parent name
1003 if path_str.starts_with("Self::") {
1004 if let Some(ref name) = self_name {
1005 resolved_self = format!("{}::{}", name, &path_str[6..]);
1006 path_str = &resolved_self;
1008 } else if path_str.starts_with("crate::") {
1009 use rustc_span::def_id::CRATE_DEF_INDEX;
1011 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1012 // But rustdoc wants it to mean the crate this item was originally present in.
1013 // To work around this, remove it and resolve relative to the crate root instead.
1014 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1015 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1016 // FIXME(#78696): This doesn't always work.
1017 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1018 path_str = &resolved_self;
1019 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1022 // Strip generics from the path.
1023 let stripped_path_string;
1024 if path_str.contains(['<', '>'].as_slice()) {
1025 stripped_path_string = match strip_generics_from_path(path_str) {
1028 debug!("link has malformed generics: {}", path_str);
1036 smallvec![err_kind],
1041 path_str = &stripped_path_string;
1043 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1044 assert!(!path_str.contains(['<', '>'].as_slice()));
1046 // The link is not an intra-doc link if it still contains commas or spaces after
1047 // stripping generics.
1048 if path_str.contains([',', ' '].as_slice()) {
1052 let key = ResolutionInfo {
1055 path_str: path_str.to_owned(),
1059 DiagnosticInfo { item, dox, ori_link: &ori_link, link_range: link_range.clone() };
1060 let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(key, diag)?;
1062 // Check for a primitive which might conflict with a module
1063 // Report the ambiguity and require that the user specify which one they meant.
1064 // FIXME: could there ever be a primitive not in the type namespace?
1067 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1068 ) && !matches!(res, Res::PrimTy(_))
1070 if let Some((path, prim)) = resolve_primitive(path_str, TypeNS) {
1072 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1073 if fragment.is_some() {
1080 AnchorFailure::RustdocAnchorConflict(prim),
1085 fragment = Some(path.as_str().to_string());
1087 // `[char]` when a `char` module is in scope
1088 let candidates = vec![res, prim];
1089 ambiguity_error(cx, &item, path_str, dox, link_range, candidates);
1095 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1096 // The resolved item did not match the disambiguator; give a better error than 'not found'
1097 let msg = format!("incompatible link kind for `{}`", path_str);
1098 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1100 "this link resolved to {} {}, which is not {} {}",
1103 specified.article(),
1107 suggest_disambiguator(resolved, diag, path_str, dox, sp, &link_range);
1109 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, &item, dox, &link_range, callback);
1111 if let Res::PrimTy(..) = res {
1112 match disambiguator {
1113 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
1114 Some(ItemLink { link: ori_link, link_text, did: None, fragment })
1117 report_mismatch(other, Disambiguator::Primitive);
1122 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
1124 // Disallow e.g. linking to enums with `struct@`
1125 if let Res::Def(kind, _) = res {
1126 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1127 match (self.kind_side_channel.take().map(|(kind, _)| kind).unwrap_or(kind), disambiguator) {
1128 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1129 // NOTE: this allows 'method' to mean both normal functions and associated functions
1130 // This can't cause ambiguity because both are in the same namespace.
1131 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1132 // These are namespaces; allow anything in the namespace to match
1133 | (_, Some(Disambiguator::Namespace(_)))
1134 // If no disambiguator given, allow anything
1136 // All of these are valid, so do nothing
1138 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1139 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1140 report_mismatch(specified, Disambiguator::Kind(kind));
1146 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1147 if let Some((src_id, dst_id)) = res
1149 .and_then(|def_id| def_id.as_local())
1150 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
1152 use rustc_hir::def_id::LOCAL_CRATE;
1154 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1155 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1157 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
1158 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
1160 privacy_error(cx, &item, &path_str, dox, link_range);
1163 let id = clean::register_res(cx, res);
1164 Some(ItemLink { link: ori_link, link_text, did: Some(id), fragment })
1168 fn resolve_with_disambiguator_cached(
1170 key: ResolutionInfo,
1171 diag: DiagnosticInfo<'_>,
1172 ) -> Option<(Res, Option<String>)> {
1173 // Try to look up both the result and the corresponding side channel value
1174 if let Some(ref cached) = self.visited_links.get(&key) {
1175 self.kind_side_channel.set(cached.side_channel.clone());
1176 return Some(cached.res.clone());
1179 let res = self.resolve_with_disambiguator(&key, diag);
1181 // Cache only if resolved successfully - don't silence duplicate errors
1182 if let Some(res) = &res {
1183 // Store result for the actual namespace
1184 self.visited_links.insert(
1188 side_channel: self.kind_side_channel.clone().into_inner(),
1196 /// After parsing the disambiguator, resolve the main part of the link.
1197 // FIXME(jynelson): wow this is just so much
1198 fn resolve_with_disambiguator(
1200 key: &ResolutionInfo,
1201 diag: DiagnosticInfo<'_>,
1202 ) -> Option<(Res, Option<String>)> {
1203 let disambiguator = key.dis;
1204 let path_str = &key.path_str;
1205 let base_node = key.module_id;
1206 let extra_fragment = &key.extra_fragment;
1208 match disambiguator.map(Disambiguator::ns) {
1209 Some(ns @ (ValueNS | TypeNS)) => {
1210 match self.resolve(path_str, ns, base_node, extra_fragment) {
1211 Ok(res) => Some(res),
1212 Err(ErrorKind::Resolve(box mut kind)) => {
1213 // We only looked in one namespace. Try to give a better error if possible.
1214 if kind.full_res().is_none() {
1215 let other_ns = if ns == ValueNS { TypeNS } else { ValueNS };
1216 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1217 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1218 for &new_ns in &[other_ns, MacroNS] {
1220 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1222 kind = ResolutionFailure::WrongNamespace(res, ns);
1236 // This could just be a normal link or a broken link
1237 // we could potentially check if something is
1238 // "intra-doc-link-like" and warn in that case.
1241 Err(ErrorKind::AnchorFailure(msg)) => {
1256 let mut candidates = PerNS {
1258 .resolve_macro(path_str, base_node)
1259 .map(|res| (res, extra_fragment.clone())),
1260 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1262 debug!("got res in TypeNS: {:?}", res);
1265 Err(ErrorKind::AnchorFailure(msg)) => {
1276 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1278 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1280 Err(ErrorKind::AnchorFailure(msg)) => {
1291 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1293 .and_then(|(res, fragment)| {
1294 // Constructors are picked up in the type namespace.
1296 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => {
1297 Err(ResolutionFailure::WrongNamespace(res, TypeNS))
1299 _ => match (fragment, extra_fragment.clone()) {
1300 (Some(fragment), Some(_)) => {
1301 // Shouldn't happen but who knows?
1302 Ok((res, Some(fragment)))
1304 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1310 let len = candidates.iter().filter(|res| res.is_ok()).count();
1320 candidates.into_iter().filter_map(|res| res.err()).collect(),
1322 // this could just be a normal link
1327 Some(candidates.into_iter().filter_map(|res| res.ok()).next().unwrap())
1328 } else if len == 2 && is_derive_trait_collision(&candidates) {
1329 Some(candidates.type_ns.unwrap())
1331 if is_derive_trait_collision(&candidates) {
1332 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1334 // If we're reporting an ambiguity, don't mention the namespaces that failed
1335 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1342 candidates.present_items().collect(),
1348 match self.resolve_macro(path_str, base_node) {
1349 Ok(res) => Some((res, extra_fragment.clone())),
1351 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1352 for &ns in &[TypeNS, ValueNS] {
1354 self.check_full_res(ns, path_str, base_node, extra_fragment)
1356 kind = ResolutionFailure::WrongNamespace(res, MacroNS);
1377 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1378 /// Disambiguators for a link.
1379 enum Disambiguator {
1382 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1384 /// `struct@` or `f()`
1387 Namespace(Namespace),
1390 impl Disambiguator {
1391 /// The text that should be displayed when the path is rendered as HTML.
1393 /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1394 fn display_for(&self, path: &str) -> String {
1396 // FIXME: this will have different output if the user had `m!()` originally.
1397 Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1398 Self::Kind(DefKind::Fn) => format!("{}()", path),
1399 _ => path.to_owned(),
1403 /// Given a link, parse and return `(disambiguator, path_str)`
1404 fn from_str(link: &str) -> Result<(Self, &str), ()> {
1405 use Disambiguator::{Kind, Namespace as NS, Primitive};
1407 let find_suffix = || {
1409 ("!()", DefKind::Macro(MacroKind::Bang)),
1410 ("()", DefKind::Fn),
1411 ("!", DefKind::Macro(MacroKind::Bang)),
1413 for &(suffix, kind) in &suffixes {
1414 if link.ends_with(suffix) {
1415 return Ok((Kind(kind), link.trim_end_matches(suffix)));
1421 if let Some(idx) = link.find('@') {
1422 let (prefix, rest) = link.split_at(idx);
1423 let d = match prefix {
1424 "struct" => Kind(DefKind::Struct),
1425 "enum" => Kind(DefKind::Enum),
1426 "trait" => Kind(DefKind::Trait),
1427 "union" => Kind(DefKind::Union),
1428 "module" | "mod" => Kind(DefKind::Mod),
1429 "const" | "constant" => Kind(DefKind::Const),
1430 "static" => Kind(DefKind::Static),
1431 "function" | "fn" | "method" => Kind(DefKind::Fn),
1432 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1433 "type" => NS(Namespace::TypeNS),
1434 "value" => NS(Namespace::ValueNS),
1435 "macro" => NS(Namespace::MacroNS),
1436 "prim" | "primitive" => Primitive,
1437 _ => return find_suffix(),
1445 /// WARNING: panics on `Res::Err`
1446 fn from_res(res: Res) -> Self {
1448 Res::Def(kind, _) => Disambiguator::Kind(kind),
1449 Res::PrimTy(_) => Disambiguator::Primitive,
1450 _ => Disambiguator::Namespace(res.ns().expect("can't call `from_res` on Res::err")),
1454 /// Used for error reporting.
1455 fn suggestion(self) -> Suggestion {
1456 let kind = match self {
1457 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1458 Disambiguator::Kind(kind) => kind,
1459 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1461 if kind == DefKind::Macro(MacroKind::Bang) {
1462 return Suggestion::Macro;
1463 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1464 return Suggestion::Function;
1467 let prefix = match kind {
1468 DefKind::Struct => "struct",
1469 DefKind::Enum => "enum",
1470 DefKind::Trait => "trait",
1471 DefKind::Union => "union",
1472 DefKind::Mod => "mod",
1473 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1476 DefKind::Static => "static",
1477 DefKind::Macro(MacroKind::Derive) => "derive",
1478 // Now handle things that don't have a specific disambiguator
1481 .expect("tried to calculate a disambiguator for a def without a namespace?")
1483 Namespace::TypeNS => "type",
1484 Namespace::ValueNS => "value",
1485 Namespace::MacroNS => "macro",
1489 Suggestion::Prefix(prefix)
1492 fn ns(self) -> Namespace {
1494 Self::Namespace(n) => n,
1496 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1498 Self::Primitive => TypeNS,
1502 fn article(self) -> &'static str {
1504 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1505 Self::Kind(k) => k.article(),
1506 Self::Primitive => "a",
1510 fn descr(self) -> &'static str {
1512 Self::Namespace(n) => n.descr(),
1513 // HACK(jynelson): by looking at the source I saw the DefId we pass
1514 // for `expected.descr()` doesn't matter, since it's not a crate
1515 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1516 Self::Primitive => "builtin type",
1521 /// A suggestion to show in a diagnostic.
1524 Prefix(&'static str),
1532 fn descr(&self) -> Cow<'static, str> {
1534 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1535 Self::Function => "add parentheses".into(),
1536 Self::Macro => "add an exclamation mark".into(),
1540 fn as_help(&self, path_str: &str) -> String {
1541 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1543 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1544 Self::Function => format!("{}()", path_str),
1545 Self::Macro => format!("{}!", path_str),
1550 /// Reports a diagnostic for an intra-doc link.
1552 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1553 /// the entire documentation block is used for the lint. If a range is provided but the span
1554 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1556 /// The `decorate` callback is invoked in all cases to allow further customization of the
1557 /// diagnostic before emission. If the span of the link was able to be determined, the second
1558 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1560 fn report_diagnostic(
1561 cx: &DocContext<'_>,
1562 lint: &'static Lint,
1566 link_range: &Option<Range<usize>>,
1567 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1569 let hir_id = match cx.as_local_hir_id(item.def_id) {
1570 Some(hir_id) => hir_id,
1572 // If non-local, no need to check anything.
1573 info!("ignoring warning from parent crate: {}", msg);
1578 let attrs = &item.attrs;
1579 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1581 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1582 let mut diag = lint.build(msg);
1584 let span = link_range
1586 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
1588 if let Some(link_range) = link_range {
1589 if let Some(sp) = span {
1592 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1595 // last_new_line_offset
1596 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1597 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1599 // Print the line containing the `link_range` and manually mark it with '^'s.
1601 "the link appears in this line:\n\n{line}\n\
1602 {indicator: <before$}{indicator:^<found$}",
1605 before = link_range.start - last_new_line_offset,
1606 found = link_range.len(),
1611 decorate(&mut diag, span);
1617 /// Reports a link that failed to resolve.
1619 /// This also tries to resolve any intermediate path segments that weren't
1620 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1621 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1622 fn resolution_failure(
1623 collector: &LinkCollector<'_, '_>,
1626 disambiguator: Option<Disambiguator>,
1628 link_range: Option<Range<usize>>,
1629 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1633 BROKEN_INTRA_DOC_LINKS,
1634 &format!("unresolved link to `{}`", path_str),
1639 let item = |res: Res| {
1643 collector.cx.tcx.item_name(res.def_id()).to_string()
1646 let assoc_item_not_allowed = |res: Res| {
1647 let def_id = res.def_id();
1648 let name = collector.cx.tcx.item_name(def_id);
1650 "`{}` is {} {}, not a module or type, and cannot have associated items",
1656 // ignore duplicates
1657 let mut variants_seen = SmallVec::<[_; 3]>::new();
1658 for mut failure in kinds {
1659 let variant = std::mem::discriminant(&failure);
1660 if variants_seen.contains(&variant) {
1663 variants_seen.push(variant);
1665 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1670 let module_id = *module_id;
1671 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1672 // FIXME: maybe use itertools `collect_tuple` instead?
1673 fn split(path: &str) -> Option<(&str, &str)> {
1674 let mut splitter = path.rsplitn(2, "::");
1675 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1678 // Check if _any_ parent of the path gets resolved.
1679 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1680 let mut name = path_str;
1682 let (start, end) = if let Some(x) = split(name) {
1685 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1686 if partial_res.is_none() {
1687 *unresolved = name.into();
1692 for &ns in &[TypeNS, ValueNS, MacroNS] {
1694 collector.check_full_res(ns, &start, module_id, &None)
1696 debug!("found partial_res={:?}", res);
1697 *partial_res = Some(res);
1698 *unresolved = end.into();
1702 *unresolved = end.into();
1705 let last_found_module = match *partial_res {
1706 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1707 None => Some(module_id),
1710 // See if this was a module: `[path]` or `[std::io::nope]`
1711 if let Some(module) = last_found_module {
1712 let note = if partial_res.is_some() {
1713 // Part of the link resolved; e.g. `std::io::nonexistent`
1714 let module_name = collector.cx.tcx.item_name(module);
1715 format!("no item named `{}` in module `{}`", unresolved, module_name)
1717 // None of the link resolved; e.g. `Notimported`
1718 format!("no item named `{}` in scope", unresolved)
1720 if let Some(span) = sp {
1721 diag.span_label(span, ¬e);
1726 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1727 // Otherwise, the `[]` might be unrelated.
1728 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1729 if !path_str.contains("::") {
1730 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1736 // Otherwise, it must be an associated item or variant
1737 let res = partial_res.expect("None case was handled by `last_found_module`");
1738 let diagnostic_name;
1739 let (kind, name) = match res {
1740 Res::Def(kind, def_id) => {
1741 diagnostic_name = collector.cx.tcx.item_name(def_id).as_str();
1742 (Some(kind), &*diagnostic_name)
1744 Res::PrimTy(ty) => (None, ty.name_str()),
1745 _ => unreachable!("only ADTs and primitives are in scope at module level"),
1747 let path_description = if let Some(kind) = kind {
1749 Mod | ForeignMod => "inner item",
1750 Struct => "field or associated item",
1751 Enum | Union => "variant or associated item",
1768 let note = assoc_item_not_allowed(res);
1769 if let Some(span) = sp {
1770 diag.span_label(span, ¬e);
1776 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1777 | Static => "associated item",
1778 Impl | GlobalAsm => unreachable!("not a path"),
1784 "the {} `{}` has no {} named `{}`",
1787 disambiguator.map_or(path_description, |d| d.descr()),
1790 if let Some(span) = sp {
1791 diag.span_label(span, ¬e);
1798 let note = match failure {
1799 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1800 ResolutionFailure::Dummy => continue,
1801 ResolutionFailure::WrongNamespace(res, expected_ns) => {
1802 if let Res::Def(kind, _) = res {
1803 let disambiguator = Disambiguator::Kind(kind);
1804 suggest_disambiguator(
1815 "this link resolves to {}, which is not in the {} namespace",
1820 ResolutionFailure::NoParentItem => {
1821 diag.level = rustc_errors::Level::Bug;
1822 "all intra doc links should have a parent item".to_owned()
1824 ResolutionFailure::MalformedGenerics(variant) => match variant {
1825 MalformedGenerics::UnbalancedAngleBrackets => {
1826 String::from("unbalanced angle brackets")
1828 MalformedGenerics::MissingType => {
1829 String::from("missing type for generic parameters")
1831 MalformedGenerics::HasFullyQualifiedSyntax => {
1832 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1833 String::from("fully-qualified syntax is unsupported")
1835 MalformedGenerics::InvalidPathSeparator => {
1836 String::from("has invalid path separator")
1838 MalformedGenerics::TooManyAngleBrackets => {
1839 String::from("too many angle brackets")
1841 MalformedGenerics::EmptyAngleBrackets => {
1842 String::from("empty angle brackets")
1846 if let Some(span) = sp {
1847 diag.span_label(span, ¬e);
1856 /// Report an anchor failure.
1858 cx: &DocContext<'_>,
1862 link_range: Option<Range<usize>>,
1863 failure: AnchorFailure,
1865 let msg = match failure {
1866 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1867 AnchorFailure::RustdocAnchorConflict(res) => format!(
1868 "`{}` contains an anchor, but links to {kind}s are already anchored",
1874 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1875 if let Some(sp) = sp {
1876 diag.span_label(sp, "contains invalid anchor");
1881 /// Report an ambiguity error, where there were multiple possible resolutions.
1883 cx: &DocContext<'_>,
1887 link_range: Option<Range<usize>>,
1888 candidates: Vec<Res>,
1890 let mut msg = format!("`{}` is ", path_str);
1892 match candidates.as_slice() {
1893 [first_def, second_def] => {
1895 "both {} {} and {} {}",
1896 first_def.article(),
1898 second_def.article(),
1903 let mut candidates = candidates.iter().peekable();
1904 while let Some(res) = candidates.next() {
1905 if candidates.peek().is_some() {
1906 msg += &format!("{} {}, ", res.article(), res.descr());
1908 msg += &format!("and {} {}", res.article(), res.descr());
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, "ambiguous link");
1918 diag.note("ambiguous link");
1921 for res in candidates {
1922 let disambiguator = Disambiguator::from_res(res);
1923 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1928 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
1930 fn suggest_disambiguator(
1931 disambiguator: Disambiguator,
1932 diag: &mut DiagnosticBuilder<'_>,
1935 sp: Option<rustc_span::Span>,
1936 link_range: &Option<Range<usize>>,
1938 let suggestion = disambiguator.suggestion();
1939 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
1941 if let Some(sp) = sp {
1942 let link_range = link_range.as_ref().expect("must have a link range if we have a span");
1943 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
1944 format!("`{}`", suggestion.as_help(path_str))
1946 suggestion.as_help(path_str)
1949 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
1951 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
1955 /// Report a link from a public item to a private one.
1957 cx: &DocContext<'_>,
1961 link_range: Option<Range<usize>>,
1964 let item_name = match item.name {
1966 sym = name.as_str();
1969 None => "<unknown>",
1972 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1974 report_diagnostic(cx, PRIVATE_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1975 if let Some(sp) = sp {
1976 diag.span_label(sp, "this item is private");
1979 let note_msg = if cx.render_options.document_private {
1980 "this link resolves only because you passed `--document-private-items`, but will break without"
1982 "this link will resolve properly if you pass `--document-private-items`"
1984 diag.note(note_msg);
1988 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1990 cx: &DocContext<'_>,
1992 extra_fragment: &Option<String>,
1993 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
1994 use rustc_middle::ty::DefIdTree;
1996 if extra_fragment.is_some() {
1997 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2000 .parent(res.def_id())
2002 let parent_def = Res::Def(DefKind::Enum, parent);
2003 let variant = cx.tcx.expect_variant_res(res);
2004 (parent_def, Some(format!("variant.{}", variant.ident.name)))
2006 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2009 // FIXME: At this point, this is basically a copy of the PrimitiveTypeTable
2010 const PRIMITIVES: &[(Symbol, Res)] = &[
2011 (sym::u8, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
2012 (sym::u16, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
2013 (sym::u32, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
2014 (sym::u64, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
2015 (sym::u128, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
2016 (sym::usize, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
2017 (sym::i8, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
2018 (sym::i16, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
2019 (sym::i32, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
2020 (sym::i64, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
2021 (sym::i128, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
2022 (sym::isize, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
2023 (sym::f32, Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
2024 (sym::f64, Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
2025 (sym::str, Res::PrimTy(hir::PrimTy::Str)),
2026 (sym::bool, Res::PrimTy(hir::PrimTy::Bool)),
2027 (sym::char, Res::PrimTy(hir::PrimTy::Char)),
2030 /// Resolve a primitive type or value.
2031 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<(Symbol, Res)> {
2032 is_bool_value(path_str, ns).or_else(|| {
2034 // FIXME: this should be replaced by a lookup in PrimitiveTypeTable
2035 let maybe_primitive = Symbol::intern(path_str);
2036 PRIMITIVES.iter().find(|x| x.0 == maybe_primitive).copied()
2043 /// Resolve a primitive value.
2044 fn is_bool_value(path_str: &str, ns: Namespace) -> Option<(Symbol, Res)> {
2045 if ns == TypeNS && (path_str == "true" || path_str == "false") {
2046 Some((sym::bool, Res::PrimTy(hir::PrimTy::Bool)))
2052 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2053 let mut stripped_segments = vec![];
2054 let mut path = path_str.chars().peekable();
2055 let mut segment = Vec::new();
2057 while let Some(chr) = path.next() {
2060 if path.next_if_eq(&':').is_some() {
2061 let stripped_segment =
2062 strip_generics_from_path_segment(mem::take(&mut segment))?;
2063 if !stripped_segment.is_empty() {
2064 stripped_segments.push(stripped_segment);
2067 return Err(ResolutionFailure::MalformedGenerics(
2068 MalformedGenerics::InvalidPathSeparator,
2077 return Err(ResolutionFailure::MalformedGenerics(
2078 MalformedGenerics::TooManyAngleBrackets,
2082 return Err(ResolutionFailure::MalformedGenerics(
2083 MalformedGenerics::EmptyAngleBrackets,
2089 while let Some(chr) = path.next_if(|c| *c != '>') {
2096 _ => segment.push(chr),
2098 trace!("raw segment: {:?}", segment);
2101 if !segment.is_empty() {
2102 let stripped_segment = strip_generics_from_path_segment(segment)?;
2103 if !stripped_segment.is_empty() {
2104 stripped_segments.push(stripped_segment);
2108 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2110 let stripped_path = stripped_segments.join("::");
2112 if !stripped_path.is_empty() {
2115 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2119 fn strip_generics_from_path_segment(
2121 ) -> Result<String, ResolutionFailure<'static>> {
2122 let mut stripped_segment = String::new();
2123 let mut param_depth = 0;
2125 let mut latest_generics_chunk = String::new();
2130 latest_generics_chunk.clear();
2131 } else if c == '>' {
2133 if latest_generics_chunk.contains(" as ") {
2134 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2135 // Give a helpful error message instead of completely ignoring the angle brackets.
2136 return Err(ResolutionFailure::MalformedGenerics(
2137 MalformedGenerics::HasFullyQualifiedSyntax,
2141 if param_depth == 0 {
2142 stripped_segment.push(c);
2144 latest_generics_chunk.push(c);
2149 if param_depth == 0 {
2150 Ok(stripped_segment)
2152 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2153 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))