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::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 struct LinkCollector<'a, 'tcx> {
172 cx: &'a DocContext<'tcx>,
173 /// A stack of modules used to decide what scope to resolve in.
175 /// The last module will be used if the parent scope of the current item is
178 /// This is used to store the kind of associated items,
179 /// because `clean` and the disambiguator code expect them to be different.
180 /// See the code for associated items on inherent impls for details.
181 kind_side_channel: Cell<Option<(DefKind, DefId)>>,
184 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
185 fn new(cx: &'a DocContext<'tcx>) -> Self {
186 LinkCollector { cx, mod_ids: Vec::new(), kind_side_channel: Cell::new(None) }
189 /// Given a full link, parse it as an [enum struct variant].
191 /// In particular, this will return an error whenever there aren't three
192 /// full path segments left in the link.
194 /// [enum struct variant]: hir::VariantData::Struct
197 path_str: &'path str,
199 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
201 let no_res = || ResolutionFailure::NotResolved {
204 unresolved: path_str.into(),
207 debug!("looking for enum variant {}", path_str);
208 let mut split = path_str.rsplitn(3, "::");
209 let (variant_field_str, variant_field_name) = split
211 .map(|f| (f, Symbol::intern(f)))
212 .expect("fold_item should ensure link is non-empty");
213 let (variant_str, variant_name) =
214 // we're not sure this is a variant at all, so use the full string
215 // If there's no second component, the link looks like `[path]`.
216 // So there's no partial res and we should say the whole link failed to resolve.
217 split.next().map(|f| (f, Symbol::intern(f))).ok_or_else(no_res)?;
220 .map(|f| f.to_owned())
221 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
222 // So there's no partial res.
223 .ok_or_else(no_res)?;
225 .enter_resolver(|resolver| {
226 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
229 .unwrap_or(Res::Err);
230 if let Res::Err = ty_res {
231 return Err(no_res().into());
233 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
235 Res::Def(DefKind::Enum, did) => {
240 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
241 .any(|item| item.ident.name == variant_name)
243 // This is just to let `fold_item` know that this shouldn't be considered;
244 // it's a bug for the error to make it to the user
245 return Err(ResolutionFailure::Dummy.into());
247 match cx.tcx.type_of(did).kind() {
248 ty::Adt(def, _) if def.is_enum() => {
249 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
253 "variant.{}.field.{}",
254 variant_str, variant_field_name
258 Err(ResolutionFailure::NotResolved {
260 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
261 unresolved: variant_field_str.into(),
269 _ => Err(ResolutionFailure::NotResolved {
271 partial_res: Some(ty_res),
272 unresolved: variant_str.into(),
278 /// Given a primitive type, try to resolve an associated item.
280 /// HACK(jynelson): `item_str` is passed in instead of derived from `item_name` so the
281 /// lifetimes on `&'path` will work.
282 fn resolve_primitive_associated_item(
284 prim_ty: hir::PrimTy,
288 item_str: &'path str,
289 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
292 PrimitiveType::from_hir(prim_ty)
297 .associated_items(impl_)
298 .find_by_name_and_namespace(
300 Ident::with_dummy_span(item_name),
304 .map(|item| match item.kind {
305 ty::AssocKind::Fn => "method",
306 ty::AssocKind::Const => "associatedconstant",
307 ty::AssocKind::Type => "associatedtype",
311 Res::PrimTy(prim_ty),
312 Some(format!("{}#{}.{}", prim_ty.name(), out, item_str)),
318 "returning primitive error for {}::{} in {} namespace",
323 ResolutionFailure::NotResolved {
325 partial_res: Some(Res::PrimTy(prim_ty)),
326 unresolved: item_str.into(),
332 /// Resolves a string as a macro.
334 /// FIXME(jynelson): Can this be unified with `resolve()`?
339 ) -> Result<Res, ResolutionFailure<'a>> {
341 let path = ast::Path::from_ident(Ident::from_str(path_str));
342 cx.enter_resolver(|resolver| {
343 // FIXME(jynelson): does this really need 3 separate lookups?
344 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
347 &ParentScope::module(resolver.graph_root(), resolver),
351 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
352 return Ok(res.map_id(|_| panic!("unexpected id")));
355 if let Some(res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
356 return Ok(res.map_id(|_| panic!("unexpected id")));
358 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
359 if let Ok((_, res)) =
360 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
362 // don't resolve builtins like `#[derive]`
363 if let Res::Def(..) = res {
364 let res = res.map_id(|_| panic!("unexpected node_id"));
368 Err(ResolutionFailure::NotResolved {
371 unresolved: path_str.into(),
376 /// Convenience wrapper around `resolve_str_path_error`.
378 /// This also handles resolving `true` and `false` as booleans.
379 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
380 /// Associated items will never be resolved by this function.
381 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
382 let result = self.cx.enter_resolver(|resolver| {
383 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
385 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
386 match result.map(|(_, res)| res) {
387 // resolver doesn't know about true and false so we'll have to resolve them
389 Ok(Res::Err) | Err(()) => is_bool_value(path_str, ns).map(|(_, res)| res),
390 Ok(res) => Some(res.map_id(|_| panic!("unexpected node_id"))),
394 /// Resolves a string as a path within a particular namespace. Returns an
395 /// optional URL fragment in the case of variants and methods.
398 path_str: &'path str,
401 extra_fragment: &Option<String>,
402 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
405 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
407 // FIXME(#76467): make this fallthrough to lookup the associated
408 // item a separate function.
409 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => {
410 assert_eq!(ns, ValueNS);
412 Res::Def(DefKind::AssocTy, _) => {
413 assert_eq!(ns, TypeNS);
415 Res::Def(DefKind::Variant, _) => {
416 return handle_variant(cx, res, extra_fragment);
418 // Not a trait item; just return what we found.
420 if extra_fragment.is_some() {
421 return Err(ErrorKind::AnchorFailure(
422 AnchorFailure::RustdocAnchorConflict(res),
425 return Ok((res, Some(ty.name_str().to_owned())));
427 Res::Def(DefKind::Mod, _) => {
428 return Ok((res, extra_fragment.clone()));
431 return Ok((res, extra_fragment.clone()));
436 // Try looking for methods and associated items.
437 let mut split = path_str.rsplitn(2, "::");
438 // NB: `split`'s first element is always defined, even if the delimiter was not present.
439 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
440 let item_str = split.next().unwrap();
441 let item_name = Symbol::intern(item_str);
442 let path_root = split
444 .map(|f| f.to_owned())
445 // If there's no `::`, it's not an associated item.
446 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
448 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
449 ResolutionFailure::NotResolved {
452 unresolved: item_str.into(),
456 // FIXME: are these both necessary?
457 let ty_res = if let Some(ty_res) = resolve_primitive(&path_root, TypeNS)
459 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
463 // FIXME: this is duplicated on the end of this function.
464 return if ns == Namespace::ValueNS {
465 self.variant_field(path_str, module_id)
467 Err(ResolutionFailure::NotResolved {
470 unresolved: path_root.into(),
476 let res = match ty_res {
477 Res::PrimTy(prim) => Some(
478 self.resolve_primitive_associated_item(prim, ns, module_id, item_name, item_str),
485 | DefKind::ForeignTy,
488 debug!("looking for associated item named {} for item {:?}", item_name, did);
489 // Checks if item_name belongs to `impl SomeItem`
495 cx.tcx.associated_items(imp).find_by_name_and_namespace(
497 Ident::with_dummy_span(item_name),
502 .map(|item| (item.kind, item.def_id))
503 // There should only ever be one associated item that matches from any inherent impl
505 // Check if item_name belongs to `impl SomeTrait for SomeItem`
506 // FIXME(#74563): This gives precedence to `impl SomeItem`:
507 // Although having both would be ambiguous, use impl version for compatibility's sake.
508 // To handle that properly resolve() would have to support
509 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
512 resolve_associated_trait_item(did, module_id, item_name, ns, &self.cx);
513 debug!("got associated item kind {:?}", kind);
517 if let Some((kind, id)) = assoc_item {
518 let out = match kind {
519 ty::AssocKind::Fn => "method",
520 ty::AssocKind::Const => "associatedconstant",
521 ty::AssocKind::Type => "associatedtype",
523 Some(if extra_fragment.is_some() {
524 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
526 // HACK(jynelson): `clean` expects the type, not the associated item
527 // but the disambiguator logic expects the associated item.
528 // Store the kind in a side channel so that only the disambiguator logic looks at it.
529 self.kind_side_channel.set(Some((kind.as_def_kind(), id)));
530 Ok((ty_res, Some(format!("{}.{}", out, item_str))))
532 } else if ns == Namespace::ValueNS {
533 debug!("looking for variants or fields named {} for {:?}", item_name, did);
534 // FIXME(jynelson): why is this different from
536 match cx.tcx.type_of(did).kind() {
538 let field = if def.is_enum() {
539 def.all_fields().find(|item| item.ident.name == item_name)
541 def.non_enum_variant()
544 .find(|item| item.ident.name == item_name)
547 if extra_fragment.is_some() {
556 Err(ErrorKind::AnchorFailure(
557 AnchorFailure::RustdocAnchorConflict(res),
564 if def.is_enum() { "variant" } else { "structfield" },
577 Res::Def(DefKind::Trait, did) => cx
579 .associated_items(did)
580 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, did)
582 let kind = match item.kind {
583 ty::AssocKind::Const => "associatedconstant",
584 ty::AssocKind::Type => "associatedtype",
585 ty::AssocKind::Fn => {
586 if item.defaultness.has_value() {
594 if extra_fragment.is_some() {
595 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(ty_res)))
597 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
598 Ok((res, Some(format!("{}.{}", kind, item_str))))
603 res.unwrap_or_else(|| {
604 if ns == Namespace::ValueNS {
605 self.variant_field(path_str, module_id)
607 Err(ResolutionFailure::NotResolved {
609 partial_res: Some(ty_res),
610 unresolved: item_str.into(),
617 /// Used for reporting better errors.
619 /// Returns whether the link resolved 'fully' in another namespace.
620 /// 'fully' here means that all parts of the link resolved, not just some path segments.
621 /// This returns the `Res` even if it was erroneous for some reason
622 /// (such as having invalid URL fragments or being in the wrong namespace).
628 extra_fragment: &Option<String>,
630 // resolve() can't be used for macro namespace
631 let result = match ns {
632 Namespace::MacroNS => self.resolve_macro(path_str, module_id).map_err(ErrorKind::from),
633 Namespace::TypeNS | Namespace::ValueNS => {
634 self.resolve(path_str, ns, module_id, extra_fragment).map(|(res, _)| res)
638 let res = match result {
639 Ok(res) => Some(res),
640 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
641 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
642 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
644 self.kind_side_channel.take().map(|(kind, id)| Res::Def(kind, id)).or(res)
648 /// Look to see if a resolved item has an associated item named `item_name`.
650 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
651 /// find `std::error::Error::source` and return
652 /// `<io::Error as error::Error>::source`.
653 fn resolve_associated_trait_item(
659 ) -> Option<(ty::AssocKind, DefId)> {
660 let ty = cx.tcx.type_of(did);
661 // First consider blanket impls: `impl From<T> for T`
662 let implicit_impls = crate::clean::get_auto_trait_and_blanket_impls(cx, ty, did);
663 let mut candidates: Vec<_> = implicit_impls
664 .flat_map(|impl_outer| {
665 match impl_outer.kind {
666 clean::ImplItem(impl_) => {
667 debug!("considering auto or blanket impl for trait {:?}", impl_.trait_);
668 // Give precedence to methods that were overridden
669 if !impl_.provided_trait_methods.contains(&*item_name.as_str()) {
670 let mut items = impl_.items.into_iter().filter_map(|assoc| {
671 if assoc.name.as_deref() != Some(&*item_name.as_str()) {
677 .expect("inner items for a trait should be associated items");
678 if kind.namespace() != ns {
682 trace!("considering associated item {:?}", assoc.kind);
683 // We have a slight issue: normal methods come from `clean` types,
684 // but provided methods come directly from `tcx`.
685 // Fortunately, we don't need the whole method, we just need to know
686 // what kind of associated item it is.
687 Some((kind, assoc.def_id))
689 let assoc = items.next();
690 debug_assert_eq!(items.count(), 0);
693 // These are provided methods or default types:
697 // fn has_default() -> A { 0 }
700 let trait_ = impl_.trait_.unwrap().def_id().unwrap();
702 .associated_items(trait_)
703 .find_by_name_and_namespace(
705 Ident::with_dummy_span(item_name),
709 .map(|assoc| (assoc.kind, assoc.def_id))
712 _ => panic!("get_impls returned something that wasn't an impl"),
717 // Next consider explicit impls: `impl MyTrait for MyType`
718 // Give precedence to inherent impls.
719 if candidates.is_empty() {
720 let traits = traits_implemented_by(cx, did, module);
721 debug!("considering traits {:?}", traits);
722 candidates.extend(traits.iter().filter_map(|&trait_| {
724 .associated_items(trait_)
725 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
726 .map(|assoc| (assoc.kind, assoc.def_id))
729 // FIXME(#74563): warn about ambiguity
730 debug!("the candidates were {:?}", candidates);
734 /// Given a type, return all traits in scope in `module` implemented by that type.
736 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
737 /// So it is not stable to serialize cross-crate.
738 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
739 let mut cache = cx.module_trait_cache.borrow_mut();
740 let in_scope_traits = cache.entry(module).or_insert_with(|| {
741 cx.enter_resolver(|resolver| {
742 resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
746 let ty = cx.tcx.type_of(type_);
747 let iter = in_scope_traits.iter().flat_map(|&trait_| {
748 trace!("considering explicit impl for trait {:?}", trait_);
750 // Look at each trait implementation to see if it's an impl for `did`
751 cx.tcx.find_map_relevant_impl(trait_, ty, |impl_| {
752 let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
753 // Check if these are the same type.
754 let impl_type = trait_ref.self_ty();
756 "comparing type {} with kind {:?} against type {:?}",
761 // Fast path: if this is a primitive simple `==` will work
762 let saw_impl = impl_type == ty
763 || match impl_type.kind() {
764 // Check if these are the same def_id
766 debug!("adt def_id: {:?}", def.did);
769 ty::Foreign(def_id) => *def_id == type_,
773 if saw_impl { Some(trait_) } else { None }
779 /// Check for resolve collisions between a trait and its derive.
781 /// These are common and we should just resolve to the trait in that case.
782 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
783 matches!(*ns, PerNS {
784 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
785 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
790 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
791 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
792 use rustc_middle::ty::DefIdTree;
794 let parent_node = if item.is_fake() {
795 // FIXME: is this correct?
797 // If we're documenting the crate root itself, it has no parent. Use the root instead.
798 } else if item.def_id.is_top_level_module() {
801 let mut current = item.def_id;
802 // The immediate parent might not always be a module.
803 // Find the first parent which is.
805 if let Some(parent) = self.cx.tcx.parent(current) {
806 if self.cx.tcx.def_kind(parent) == DefKind::Mod {
812 "{:?} has no parent (kind={:?}, original was {:?})",
814 self.cx.tcx.def_kind(current),
822 if parent_node.is_some() {
823 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
826 // find item's parent to resolve `Self` in item's docs below
827 debug!("looking for the `Self` type");
828 let self_id = if item.is_fake() {
831 self.cx.tcx.def_kind(item.def_id),
838 self.cx.tcx.parent(item.def_id)
839 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
840 // Fixing this breaks `fn render_deref_methods`.
841 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
842 // regardless of what rustdoc wants to call it.
843 } else if let Some(parent) = self.cx.tcx.parent(item.def_id) {
844 let parent_kind = self.cx.tcx.def_kind(parent);
845 Some(if parent_kind == DefKind::Impl { parent } else { item.def_id })
850 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
851 let self_name = self_id.and_then(|self_id| {
853 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
854 // using `ty.to_string()` (or any variant) has issues with raw idents
855 let ty = self.cx.tcx.type_of(self_id);
856 let name = match ty.kind() {
857 TyKind::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
858 other if other.is_primitive() => Some(ty.to_string()),
861 debug!("using type_of(): {:?}", name);
864 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
865 debug!("using item_name(): {:?}", name);
870 if item.is_mod() && item.attrs.inner_docs {
871 self.mod_ids.push(item.def_id);
874 // We want to resolve in the lexical scope of the documentation.
875 // In the presence of re-exports, this is not the same as the module of the item.
876 // Rather than merging all documentation into one, resolve it one attribute at a time
877 // so we know which module it came from.
878 let mut attrs = item.attrs.doc_strings.iter().peekable();
879 while let Some(attr) = attrs.next() {
880 // `collapse_docs` does not have the behavior we want:
881 // we want `///` and `#[doc]` to count as the same attribute,
882 // but currently it will treat them as separate.
883 // As a workaround, combine all attributes with the same parent module into the same attribute.
884 let mut combined_docs = attr.doc.clone();
887 Some(next) if next.parent_module == attr.parent_module => {
888 combined_docs.push('\n');
889 combined_docs.push_str(&attrs.next().unwrap().doc);
894 debug!("combined_docs={}", combined_docs);
896 let (krate, parent_node) = if let Some(id) = attr.parent_module {
897 trace!("docs {:?} came from {:?}", attr.doc, id);
900 trace!("no parent found for {:?}", attr.doc);
901 (item.def_id.krate, parent_node)
903 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
904 // This is a degenerate case and it's not supported by rustdoc.
905 for (ori_link, link_range) in markdown_links(&combined_docs) {
906 let link = self.resolve_link(
915 if let Some(link) = link {
916 item.attrs.links.push(link);
921 Some(if item.is_mod() {
922 if !item.attrs.inner_docs {
923 self.mod_ids.push(item.def_id);
926 let ret = self.fold_item_recur(item);
930 self.fold_item_recur(item)
935 impl LinkCollector<'_, '_> {
936 /// This is the entry point for resolving an intra-doc link.
938 /// FIXME(jynelson): this is way too many arguments
943 self_name: &Option<String>,
944 parent_node: Option<DefId>,
947 link_range: Option<Range<usize>>,
948 ) -> Option<ItemLink> {
949 trace!("considering link '{}'", ori_link);
951 // Bail early for real links.
952 if ori_link.contains('/') {
956 // [] is mostly likely not supposed to be a link
957 if ori_link.is_empty() {
962 let link = ori_link.replace("`", "");
963 let parts = link.split('#').collect::<Vec<_>>();
964 let (link, extra_fragment) = if parts.len() > 2 {
965 anchor_failure(cx, &item, &link, dox, link_range, AnchorFailure::MultipleAnchors);
967 } else if parts.len() == 2 {
968 if parts[0].trim().is_empty() {
969 // This is an anchor to an element of the current page, nothing to do in here!
972 (parts[0], Some(parts[1].to_owned()))
977 // Parse and strip the disambiguator from the link, if present.
978 let (mut path_str, disambiguator) = if let Ok((d, path)) = Disambiguator::from_str(&link) {
979 (path.trim(), Some(d))
984 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !".contains(ch))) {
988 // We stripped `()` and `!` when parsing the disambiguator.
989 // Add them back to be displayed, but not prefix disambiguators.
991 disambiguator.map(|d| d.display_for(path_str)).unwrap_or_else(|| path_str.to_owned());
993 // In order to correctly resolve intra-doc-links we need to
994 // pick a base AST node to work from. If the documentation for
995 // this module came from an inner comment (//!) then we anchor
996 // our name resolution *inside* the module. If, on the other
997 // hand it was an outer comment (///) then we anchor the name
998 // resolution in the parent module on the basis that the names
999 // used are more likely to be intended to be parent names. For
1000 // this, we set base_node to None for inner comments since
1001 // we've already pushed this node onto the resolution stack but
1002 // for outer comments we explicitly try and resolve against the
1003 // parent_node first.
1004 let base_node = if item.is_mod() && item.attrs.inner_docs {
1005 self.mod_ids.last().copied()
1010 let mut module_id = if let Some(id) = base_node {
1014 debug!("attempting to resolve item without parent module: {}", path_str);
1015 let err_kind = ResolutionFailure::NoParentItem.into();
1023 smallvec![err_kind],
1029 // replace `Self` with suitable item's parent name
1030 if path_str.starts_with("Self::") {
1031 if let Some(ref name) = self_name {
1032 resolved_self = format!("{}::{}", name, &path_str[6..]);
1033 path_str = &resolved_self;
1035 } else if path_str.starts_with("crate::") {
1036 use rustc_span::def_id::CRATE_DEF_INDEX;
1038 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1039 // But rustdoc wants it to mean the crate this item was originally present in.
1040 // To work around this, remove it and resolve relative to the crate root instead.
1041 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1042 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1043 // FIXME(#78696): This doesn't always work.
1044 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1045 path_str = &resolved_self;
1046 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1049 // Strip generics from the path.
1050 let stripped_path_string;
1051 if path_str.contains(['<', '>'].as_slice()) {
1052 stripped_path_string = match strip_generics_from_path(path_str) {
1055 debug!("link has malformed generics: {}", path_str);
1063 smallvec![err_kind],
1068 path_str = &stripped_path_string;
1070 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1071 assert!(!path_str.contains(['<', '>'].as_slice()));
1073 // The link is not an intra-doc link if it still contains commas or spaces after
1074 // stripping generics.
1075 if path_str.contains([',', ' '].as_slice()) {
1079 let (mut res, mut fragment) = self.resolve_with_disambiguator(
1090 // Check for a primitive which might conflict with a module
1091 // Report the ambiguity and require that the user specify which one they meant.
1092 // FIXME: could there ever be a primitive not in the type namespace?
1095 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1096 ) && !matches!(res, Res::PrimTy(_))
1098 if let Some((path, prim)) = resolve_primitive(path_str, TypeNS) {
1100 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1101 if fragment.is_some() {
1108 AnchorFailure::RustdocAnchorConflict(prim),
1113 fragment = Some(path.as_str().to_string());
1115 // `[char]` when a `char` module is in scope
1116 let candidates = vec![res, prim];
1117 ambiguity_error(cx, &item, path_str, dox, link_range, candidates);
1123 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1124 // The resolved item did not match the disambiguator; give a better error than 'not found'
1125 let msg = format!("incompatible link kind for `{}`", path_str);
1126 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1128 "this link resolved to {} {}, which is not {} {}",
1131 specified.article(),
1135 suggest_disambiguator(resolved, diag, path_str, dox, sp, &link_range);
1137 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, &item, dox, &link_range, callback);
1139 if let Res::PrimTy(..) = res {
1140 match disambiguator {
1141 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
1142 Some(ItemLink { link: ori_link, link_text, did: None, fragment })
1145 report_mismatch(other, Disambiguator::Primitive);
1150 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
1152 // Disallow e.g. linking to enums with `struct@`
1153 if let Res::Def(kind, _) = res {
1154 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1155 match (self.kind_side_channel.take().map(|(kind, _)| kind).unwrap_or(kind), disambiguator) {
1156 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1157 // NOTE: this allows 'method' to mean both normal functions and associated functions
1158 // This can't cause ambiguity because both are in the same namespace.
1159 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1160 // These are namespaces; allow anything in the namespace to match
1161 | (_, Some(Disambiguator::Namespace(_)))
1162 // If no disambiguator given, allow anything
1164 // All of these are valid, so do nothing
1166 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1167 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1168 report_mismatch(specified, Disambiguator::Kind(kind));
1174 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1175 if let Some((src_id, dst_id)) = res
1177 .and_then(|def_id| def_id.as_local())
1178 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
1180 use rustc_hir::def_id::LOCAL_CRATE;
1182 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1183 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1185 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
1186 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
1188 privacy_error(cx, &item, &path_str, dox, link_range);
1191 let id = clean::register_res(cx, res);
1192 Some(ItemLink { link: ori_link, link_text, did: Some(id), fragment })
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 disambiguator: Option<Disambiguator>,
1205 extra_fragment: Option<String>,
1207 link_range: Option<Range<usize>>,
1208 ) -> Option<(Res, Option<String>)> {
1209 match disambiguator.map(Disambiguator::ns) {
1210 Some(ns @ (ValueNS | TypeNS)) => {
1211 match self.resolve(path_str, ns, base_node, &extra_fragment) {
1212 Ok(res) => Some(res),
1213 Err(ErrorKind::Resolve(box mut kind)) => {
1214 // We only looked in one namespace. Try to give a better error if possible.
1215 if kind.full_res().is_none() {
1216 let other_ns = if ns == ValueNS { TypeNS } else { ValueNS };
1217 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1218 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1219 for &new_ns in &[other_ns, MacroNS] {
1220 if let Some(res) = self.check_full_res(
1226 kind = ResolutionFailure::WrongNamespace(res, ns);
1240 // This could just be a normal link or a broken link
1241 // we could potentially check if something is
1242 // "intra-doc-link-like" and warn in that case.
1245 Err(ErrorKind::AnchorFailure(msg)) => {
1246 anchor_failure(self.cx, &item, &ori_link, dox, link_range, msg);
1253 let mut candidates = PerNS {
1255 .resolve_macro(path_str, base_node)
1256 .map(|res| (res, extra_fragment.clone())),
1257 type_ns: match self.resolve(path_str, TypeNS, base_node, &extra_fragment) {
1259 debug!("got res in TypeNS: {:?}", res);
1262 Err(ErrorKind::AnchorFailure(msg)) => {
1263 anchor_failure(self.cx, &item, ori_link, dox, link_range, msg);
1266 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1268 value_ns: match self.resolve(path_str, ValueNS, base_node, &extra_fragment) {
1270 Err(ErrorKind::AnchorFailure(msg)) => {
1271 anchor_failure(self.cx, &item, ori_link, dox, link_range, msg);
1274 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1276 .and_then(|(res, fragment)| {
1277 // Constructors are picked up in the type namespace.
1279 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => {
1280 Err(ResolutionFailure::WrongNamespace(res, TypeNS))
1282 _ => match (fragment, extra_fragment) {
1283 (Some(fragment), Some(_)) => {
1284 // Shouldn't happen but who knows?
1285 Ok((res, Some(fragment)))
1287 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1293 let len = candidates.iter().filter(|res| res.is_ok()).count();
1303 candidates.into_iter().filter_map(|res| res.err()).collect(),
1305 // this could just be a normal link
1310 Some(candidates.into_iter().filter_map(|res| res.ok()).next().unwrap())
1311 } else if len == 2 && is_derive_trait_collision(&candidates) {
1312 Some(candidates.type_ns.unwrap())
1314 if is_derive_trait_collision(&candidates) {
1315 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1317 // If we're reporting an ambiguity, don't mention the namespaces that failed
1318 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1325 candidates.present_items().collect(),
1331 match self.resolve_macro(path_str, base_node) {
1332 Ok(res) => Some((res, extra_fragment)),
1334 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1335 for &ns in &[TypeNS, ValueNS] {
1337 self.check_full_res(ns, path_str, base_node, &extra_fragment)
1339 kind = ResolutionFailure::WrongNamespace(res, MacroNS);
1360 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1361 /// Disambiguators for a link.
1362 enum Disambiguator {
1365 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1367 /// `struct@` or `f()`
1370 Namespace(Namespace),
1373 impl Disambiguator {
1374 /// The text that should be displayed when the path is rendered as HTML.
1376 /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1377 fn display_for(&self, path: &str) -> String {
1379 // FIXME: this will have different output if the user had `m!()` originally.
1380 Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1381 Self::Kind(DefKind::Fn) => format!("{}()", path),
1382 _ => path.to_owned(),
1386 /// Given a link, parse and return `(disambiguator, path_str)`
1387 fn from_str(link: &str) -> Result<(Self, &str), ()> {
1388 use Disambiguator::{Kind, Namespace as NS, Primitive};
1390 let find_suffix = || {
1392 ("!()", DefKind::Macro(MacroKind::Bang)),
1393 ("()", DefKind::Fn),
1394 ("!", DefKind::Macro(MacroKind::Bang)),
1396 for &(suffix, kind) in &suffixes {
1397 if link.ends_with(suffix) {
1398 return Ok((Kind(kind), link.trim_end_matches(suffix)));
1404 if let Some(idx) = link.find('@') {
1405 let (prefix, rest) = link.split_at(idx);
1406 let d = match prefix {
1407 "struct" => Kind(DefKind::Struct),
1408 "enum" => Kind(DefKind::Enum),
1409 "trait" => Kind(DefKind::Trait),
1410 "union" => Kind(DefKind::Union),
1411 "module" | "mod" => Kind(DefKind::Mod),
1412 "const" | "constant" => Kind(DefKind::Const),
1413 "static" => Kind(DefKind::Static),
1414 "function" | "fn" | "method" => Kind(DefKind::Fn),
1415 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1416 "type" => NS(Namespace::TypeNS),
1417 "value" => NS(Namespace::ValueNS),
1418 "macro" => NS(Namespace::MacroNS),
1419 "prim" | "primitive" => Primitive,
1420 _ => return find_suffix(),
1428 /// WARNING: panics on `Res::Err`
1429 fn from_res(res: Res) -> Self {
1431 Res::Def(kind, _) => Disambiguator::Kind(kind),
1432 Res::PrimTy(_) => Disambiguator::Primitive,
1433 _ => Disambiguator::Namespace(res.ns().expect("can't call `from_res` on Res::err")),
1437 /// Used for error reporting.
1438 fn suggestion(self) -> Suggestion {
1439 let kind = match self {
1440 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1441 Disambiguator::Kind(kind) => kind,
1442 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1444 if kind == DefKind::Macro(MacroKind::Bang) {
1445 return Suggestion::Macro;
1446 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1447 return Suggestion::Function;
1450 let prefix = match kind {
1451 DefKind::Struct => "struct",
1452 DefKind::Enum => "enum",
1453 DefKind::Trait => "trait",
1454 DefKind::Union => "union",
1455 DefKind::Mod => "mod",
1456 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1459 DefKind::Static => "static",
1460 DefKind::Macro(MacroKind::Derive) => "derive",
1461 // Now handle things that don't have a specific disambiguator
1464 .expect("tried to calculate a disambiguator for a def without a namespace?")
1466 Namespace::TypeNS => "type",
1467 Namespace::ValueNS => "value",
1468 Namespace::MacroNS => "macro",
1472 Suggestion::Prefix(prefix)
1475 fn ns(self) -> Namespace {
1477 Self::Namespace(n) => n,
1479 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1481 Self::Primitive => TypeNS,
1485 fn article(self) -> &'static str {
1487 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1488 Self::Kind(k) => k.article(),
1489 Self::Primitive => "a",
1493 fn descr(self) -> &'static str {
1495 Self::Namespace(n) => n.descr(),
1496 // HACK(jynelson): by looking at the source I saw the DefId we pass
1497 // for `expected.descr()` doesn't matter, since it's not a crate
1498 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1499 Self::Primitive => "builtin type",
1504 /// A suggestion to show in a diagnostic.
1507 Prefix(&'static str),
1515 fn descr(&self) -> Cow<'static, str> {
1517 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1518 Self::Function => "add parentheses".into(),
1519 Self::Macro => "add an exclamation mark".into(),
1523 fn as_help(&self, path_str: &str) -> String {
1524 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1526 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1527 Self::Function => format!("{}()", path_str),
1528 Self::Macro => format!("{}!", path_str),
1533 /// Reports a diagnostic for an intra-doc link.
1535 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1536 /// the entire documentation block is used for the lint. If a range is provided but the span
1537 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1539 /// The `decorate` callback is invoked in all cases to allow further customization of the
1540 /// diagnostic before emission. If the span of the link was able to be determined, the second
1541 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1543 fn report_diagnostic(
1544 cx: &DocContext<'_>,
1545 lint: &'static Lint,
1549 link_range: &Option<Range<usize>>,
1550 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1552 let hir_id = match cx.as_local_hir_id(item.def_id) {
1553 Some(hir_id) => hir_id,
1555 // If non-local, no need to check anything.
1556 info!("ignoring warning from parent crate: {}", msg);
1561 let attrs = &item.attrs;
1562 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1564 cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1565 let mut diag = lint.build(msg);
1567 let span = link_range
1569 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
1571 if let Some(link_range) = link_range {
1572 if let Some(sp) = span {
1575 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1578 // last_new_line_offset
1579 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1580 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1582 // Print the line containing the `link_range` and manually mark it with '^'s.
1584 "the link appears in this line:\n\n{line}\n\
1585 {indicator: <before$}{indicator:^<found$}",
1588 before = link_range.start - last_new_line_offset,
1589 found = link_range.len(),
1594 decorate(&mut diag, span);
1600 /// Reports a link that failed to resolve.
1602 /// This also tries to resolve any intermediate path segments that weren't
1603 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1604 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1605 fn resolution_failure(
1606 collector: &LinkCollector<'_, '_>,
1609 disambiguator: Option<Disambiguator>,
1611 link_range: Option<Range<usize>>,
1612 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1616 BROKEN_INTRA_DOC_LINKS,
1617 &format!("unresolved link to `{}`", path_str),
1622 let item = |res: Res| {
1626 collector.cx.tcx.item_name(res.def_id()).to_string()
1629 let assoc_item_not_allowed = |res: Res| {
1630 let def_id = res.def_id();
1631 let name = collector.cx.tcx.item_name(def_id);
1633 "`{}` is {} {}, not a module or type, and cannot have associated items",
1639 // ignore duplicates
1640 let mut variants_seen = SmallVec::<[_; 3]>::new();
1641 for mut failure in kinds {
1642 let variant = std::mem::discriminant(&failure);
1643 if variants_seen.contains(&variant) {
1646 variants_seen.push(variant);
1648 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1653 let module_id = *module_id;
1654 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1655 // FIXME: maybe use itertools `collect_tuple` instead?
1656 fn split(path: &str) -> Option<(&str, &str)> {
1657 let mut splitter = path.rsplitn(2, "::");
1658 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1661 // Check if _any_ parent of the path gets resolved.
1662 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1663 let mut name = path_str;
1665 let (start, end) = if let Some(x) = split(name) {
1668 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1669 if partial_res.is_none() {
1670 *unresolved = name.into();
1675 for &ns in &[TypeNS, ValueNS, MacroNS] {
1677 collector.check_full_res(ns, &start, module_id, &None)
1679 debug!("found partial_res={:?}", res);
1680 *partial_res = Some(res);
1681 *unresolved = end.into();
1685 *unresolved = end.into();
1688 let last_found_module = match *partial_res {
1689 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1690 None => Some(module_id),
1693 // See if this was a module: `[path]` or `[std::io::nope]`
1694 if let Some(module) = last_found_module {
1695 let note = if partial_res.is_some() {
1696 // Part of the link resolved; e.g. `std::io::nonexistent`
1697 let module_name = collector.cx.tcx.item_name(module);
1698 format!("no item named `{}` in module `{}`", unresolved, module_name)
1700 // None of the link resolved; e.g. `Notimported`
1701 format!("no item named `{}` in scope", unresolved)
1703 if let Some(span) = sp {
1704 diag.span_label(span, ¬e);
1709 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1710 // Otherwise, the `[]` might be unrelated.
1711 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1712 if !path_str.contains("::") {
1713 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1719 // Otherwise, it must be an associated item or variant
1720 let res = partial_res.expect("None case was handled by `last_found_module`");
1721 let diagnostic_name;
1722 let (kind, name) = match res {
1723 Res::Def(kind, def_id) => {
1724 diagnostic_name = collector.cx.tcx.item_name(def_id).as_str();
1725 (Some(kind), &*diagnostic_name)
1727 Res::PrimTy(ty) => (None, ty.name_str()),
1728 _ => unreachable!("only ADTs and primitives are in scope at module level"),
1730 let path_description = if let Some(kind) = kind {
1732 Mod | ForeignMod => "inner item",
1733 Struct => "field or associated item",
1734 Enum | Union => "variant or associated item",
1751 let note = assoc_item_not_allowed(res);
1752 if let Some(span) = sp {
1753 diag.span_label(span, ¬e);
1759 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1760 | Static => "associated item",
1761 Impl | GlobalAsm => unreachable!("not a path"),
1767 "the {} `{}` has no {} named `{}`",
1770 disambiguator.map_or(path_description, |d| d.descr()),
1773 if let Some(span) = sp {
1774 diag.span_label(span, ¬e);
1781 let note = match failure {
1782 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1783 ResolutionFailure::Dummy => continue,
1784 ResolutionFailure::WrongNamespace(res, expected_ns) => {
1785 if let Res::Def(kind, _) = res {
1786 let disambiguator = Disambiguator::Kind(kind);
1787 suggest_disambiguator(
1798 "this link resolves to {}, which is not in the {} namespace",
1803 ResolutionFailure::NoParentItem => {
1804 diag.level = rustc_errors::Level::Bug;
1805 "all intra doc links should have a parent item".to_owned()
1807 ResolutionFailure::MalformedGenerics(variant) => match variant {
1808 MalformedGenerics::UnbalancedAngleBrackets => {
1809 String::from("unbalanced angle brackets")
1811 MalformedGenerics::MissingType => {
1812 String::from("missing type for generic parameters")
1814 MalformedGenerics::HasFullyQualifiedSyntax => {
1815 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1816 String::from("fully-qualified syntax is unsupported")
1818 MalformedGenerics::InvalidPathSeparator => {
1819 String::from("has invalid path separator")
1821 MalformedGenerics::TooManyAngleBrackets => {
1822 String::from("too many angle brackets")
1824 MalformedGenerics::EmptyAngleBrackets => {
1825 String::from("empty angle brackets")
1829 if let Some(span) = sp {
1830 diag.span_label(span, ¬e);
1839 /// Report an anchor failure.
1841 cx: &DocContext<'_>,
1845 link_range: Option<Range<usize>>,
1846 failure: AnchorFailure,
1848 let msg = match failure {
1849 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1850 AnchorFailure::RustdocAnchorConflict(res) => format!(
1851 "`{}` contains an anchor, but links to {kind}s are already anchored",
1857 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1858 if let Some(sp) = sp {
1859 diag.span_label(sp, "contains invalid anchor");
1864 /// Report an ambiguity error, where there were multiple possible resolutions.
1866 cx: &DocContext<'_>,
1870 link_range: Option<Range<usize>>,
1871 candidates: Vec<Res>,
1873 let mut msg = format!("`{}` is ", path_str);
1875 match candidates.as_slice() {
1876 [first_def, second_def] => {
1878 "both {} {} and {} {}",
1879 first_def.article(),
1881 second_def.article(),
1886 let mut candidates = candidates.iter().peekable();
1887 while let Some(res) = candidates.next() {
1888 if candidates.peek().is_some() {
1889 msg += &format!("{} {}, ", res.article(), res.descr());
1891 msg += &format!("and {} {}", res.article(), res.descr());
1897 report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1898 if let Some(sp) = sp {
1899 diag.span_label(sp, "ambiguous link");
1901 diag.note("ambiguous link");
1904 for res in candidates {
1905 let disambiguator = Disambiguator::from_res(res);
1906 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1911 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
1913 fn suggest_disambiguator(
1914 disambiguator: Disambiguator,
1915 diag: &mut DiagnosticBuilder<'_>,
1918 sp: Option<rustc_span::Span>,
1919 link_range: &Option<Range<usize>>,
1921 let suggestion = disambiguator.suggestion();
1922 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
1924 if let Some(sp) = sp {
1925 let link_range = link_range.as_ref().expect("must have a link range if we have a span");
1926 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
1927 format!("`{}`", suggestion.as_help(path_str))
1929 suggestion.as_help(path_str)
1932 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
1934 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
1938 /// Report a link from a public item to a private one.
1940 cx: &DocContext<'_>,
1944 link_range: Option<Range<usize>>,
1946 let item_name = item.name.as_deref().unwrap_or("<unknown>");
1948 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1950 report_diagnostic(cx, PRIVATE_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1951 if let Some(sp) = sp {
1952 diag.span_label(sp, "this item is private");
1955 let note_msg = if cx.render_options.document_private {
1956 "this link resolves only because you passed `--document-private-items`, but will break without"
1958 "this link will resolve properly if you pass `--document-private-items`"
1960 diag.note(note_msg);
1964 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1966 cx: &DocContext<'_>,
1968 extra_fragment: &Option<String>,
1969 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
1970 use rustc_middle::ty::DefIdTree;
1972 if extra_fragment.is_some() {
1973 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
1976 .parent(res.def_id())
1978 let parent_def = Res::Def(DefKind::Enum, parent);
1979 let variant = cx.tcx.expect_variant_res(res);
1980 (parent_def, Some(format!("variant.{}", variant.ident.name)))
1982 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
1985 // FIXME: At this point, this is basically a copy of the PrimitiveTypeTable
1986 const PRIMITIVES: &[(Symbol, Res)] = &[
1987 (sym::u8, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
1988 (sym::u16, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
1989 (sym::u32, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
1990 (sym::u64, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
1991 (sym::u128, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
1992 (sym::usize, Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
1993 (sym::i8, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
1994 (sym::i16, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
1995 (sym::i32, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
1996 (sym::i64, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
1997 (sym::i128, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
1998 (sym::isize, Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
1999 (sym::f32, Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
2000 (sym::f64, Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
2001 (sym::str, Res::PrimTy(hir::PrimTy::Str)),
2002 (sym::bool, Res::PrimTy(hir::PrimTy::Bool)),
2003 (sym::char, Res::PrimTy(hir::PrimTy::Char)),
2006 /// Resolve a primitive type or value.
2007 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<(Symbol, Res)> {
2008 is_bool_value(path_str, ns).or_else(|| {
2010 // FIXME: this should be replaced by a lookup in PrimitiveTypeTable
2011 let maybe_primitive = Symbol::intern(path_str);
2012 PRIMITIVES.iter().find(|x| x.0 == maybe_primitive).copied()
2019 /// Resolve a primitive value.
2020 fn is_bool_value(path_str: &str, ns: Namespace) -> Option<(Symbol, Res)> {
2021 if ns == TypeNS && (path_str == "true" || path_str == "false") {
2022 Some((sym::bool, Res::PrimTy(hir::PrimTy::Bool)))
2028 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2029 let mut stripped_segments = vec![];
2030 let mut path = path_str.chars().peekable();
2031 let mut segment = Vec::new();
2033 while let Some(chr) = path.next() {
2036 if path.next_if_eq(&':').is_some() {
2037 let stripped_segment =
2038 strip_generics_from_path_segment(mem::take(&mut segment))?;
2039 if !stripped_segment.is_empty() {
2040 stripped_segments.push(stripped_segment);
2043 return Err(ResolutionFailure::MalformedGenerics(
2044 MalformedGenerics::InvalidPathSeparator,
2053 return Err(ResolutionFailure::MalformedGenerics(
2054 MalformedGenerics::TooManyAngleBrackets,
2058 return Err(ResolutionFailure::MalformedGenerics(
2059 MalformedGenerics::EmptyAngleBrackets,
2065 while let Some(chr) = path.next_if(|c| *c != '>') {
2072 _ => segment.push(chr),
2074 trace!("raw segment: {:?}", segment);
2077 if !segment.is_empty() {
2078 let stripped_segment = strip_generics_from_path_segment(segment)?;
2079 if !stripped_segment.is_empty() {
2080 stripped_segments.push(stripped_segment);
2084 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2086 let stripped_path = stripped_segments.join("::");
2088 if !stripped_path.is_empty() {
2091 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2095 fn strip_generics_from_path_segment(
2097 ) -> Result<String, ResolutionFailure<'static>> {
2098 let mut stripped_segment = String::new();
2099 let mut param_depth = 0;
2101 let mut latest_generics_chunk = String::new();
2106 latest_generics_chunk.clear();
2107 } else if c == '>' {
2109 if latest_generics_chunk.contains(" as ") {
2110 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2111 // Give a helpful error message instead of completely ignoring the angle brackets.
2112 return Err(ResolutionFailure::MalformedGenerics(
2113 MalformedGenerics::HasFullyQualifiedSyntax,
2117 if param_depth == 0 {
2118 stripped_segment.push(c);
2120 latest_generics_chunk.push(c);
2125 if param_depth == 0 {
2126 Ok(stripped_segment)
2128 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2129 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))