1 //! This module implements [RFC 1946]: Intra-rustdoc-links
3 //! [RFC 1946]: https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md
6 use rustc_data_structures::{fx::FxHashMap, stable_set::FxHashSet};
7 use rustc_errors::{Applicability, DiagnosticBuilder};
8 use rustc_expand::base::SyntaxExtensionKind;
15 use rustc_hir::def_id::{CrateNum, DefId};
16 use rustc_middle::ty::TyCtxt;
17 use rustc_middle::{bug, ty};
18 use rustc_resolve::ParentScope;
19 use rustc_session::lint::Lint;
20 use rustc_span::hygiene::{MacroKind, SyntaxContext};
21 use rustc_span::symbol::{sym, Ident, Symbol};
22 use rustc_span::DUMMY_SP;
23 use smallvec::{smallvec, SmallVec};
25 use pulldown_cmark::LinkType;
29 use std::convert::{TryFrom, TryInto};
33 use crate::clean::{self, utils::find_nearest_parent_module, Crate, Item, ItemLink, PrimitiveType};
34 use crate::core::DocContext;
35 use crate::fold::DocFolder;
36 use crate::html::markdown::{markdown_links, MarkdownLink};
37 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_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: "resolves intra-doc links",
48 crate fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
52 kind_side_channel: Cell::new(None),
53 visited_links: FxHashMap::default(),
58 /// Top-level errors emitted by this pass.
60 Resolve(Box<ResolutionFailure<'a>>),
61 AnchorFailure(AnchorFailure),
64 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
65 fn from(err: ResolutionFailure<'a>) -> Self {
66 ErrorKind::Resolve(box err)
70 #[derive(Copy, Clone, Debug, Hash)]
73 Primitive(PrimitiveType),
76 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
79 fn descr(self) -> &'static str {
81 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
82 Res::Primitive(_) => "builtin type",
86 fn article(self) -> &'static str {
88 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
89 Res::Primitive(_) => "a",
93 fn name(self, tcx: TyCtxt<'_>) -> String {
95 Res::Def(_, id) => tcx.item_name(id).to_string(),
96 Res::Primitive(prim) => prim.as_str().to_string(),
100 fn def_id(self) -> DefId {
101 self.opt_def_id().expect("called def_id() on a primitive")
104 fn opt_def_id(self) -> Option<DefId> {
106 Res::Def(_, id) => Some(id),
107 Res::Primitive(_) => None,
111 fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
113 Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
114 // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
115 Res::Primitive(_) => None,
120 impl TryFrom<ResolveRes> for Res {
123 fn try_from(res: ResolveRes) -> Result<Self, ()> {
124 use rustc_hir::def::Res::*;
126 Def(kind, id) => Ok(Res::Def(kind, id)),
127 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
129 NonMacroAttr(..) | Err => Result::Err(()),
130 other => bug!("unrecognized res {:?}", other),
135 /// A link failed to resolve.
137 enum ResolutionFailure<'a> {
138 /// This resolved, but with the wrong namespace.
140 /// What the link resolved to.
142 /// The expected namespace for the resolution, determined from the link's disambiguator.
144 /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
145 /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
146 expected_ns: Namespace,
148 /// The link failed to resolve. [`resolution_failure`] should look to see if there's
149 /// a more helpful error that can be given.
151 /// The scope the link was resolved in.
153 /// If part of the link resolved, this has the `Res`.
155 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
156 partial_res: Option<Res>,
157 /// The remaining unresolved path segments.
159 /// In `[std::io::Error::x]`, `x` would be unresolved.
160 unresolved: Cow<'a, str>,
162 /// This happens when rustdoc can't determine the parent scope for an item.
163 /// It is always a bug in rustdoc.
165 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
166 MalformedGenerics(MalformedGenerics),
167 /// Used to communicate that this should be ignored, but shouldn't be reported to the user.
169 /// This happens when there is no disambiguator and one of the namespaces
170 /// failed to resolve.
175 enum MalformedGenerics {
176 /// This link has unbalanced angle brackets.
178 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
179 UnbalancedAngleBrackets,
180 /// The generics are not attached to a type.
182 /// For example, `<T>` should trigger this.
184 /// This is detected by checking if the path is empty after the generics are stripped.
186 /// The link uses fully-qualified syntax, which is currently unsupported.
188 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
190 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
192 HasFullyQualifiedSyntax,
193 /// The link has an invalid path separator.
195 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
196 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
199 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
200 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
201 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
203 /// This is detected by checking if there is a colon followed by a non-colon in the link.
204 InvalidPathSeparator,
205 /// The link has too many angle brackets.
207 /// For example, `Vec<<T>>` should trigger this.
208 TooManyAngleBrackets,
209 /// The link has empty angle brackets.
211 /// For example, `Vec<>` should trigger this.
215 impl ResolutionFailure<'a> {
216 /// This resolved fully (not just partially) but is erroneous for some other reason
218 /// Returns the full resolution of the link, if present.
219 fn full_res(&self) -> Option<Res> {
221 Self::WrongNamespace { res, expected_ns: _ } => Some(*res),
228 /// User error: `[std#x#y]` is not valid
230 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
232 /// This is an unfortunate state of affairs. Not every item that can be
233 /// linked to has its own page; sometimes it is a subheading within a page,
234 /// like for associated items. In those cases, rustdoc uses an anchor to
235 /// link to the subheading. Since you can't have two anchors for the same
236 /// link, Rustdoc disallows having a user-specified anchor.
238 /// Most of the time this is fine, because you can just link to the page of
239 /// the item if you want to provide your own anchor. For primitives, though,
240 /// rustdoc uses the anchor as a side channel to know which page to link to;
241 /// it doesn't show up in the generated link. Ideally, rustdoc would remove
242 /// this limitation, allowing you to link to subheaders on primitives.
243 RustdocAnchorConflict(Res),
246 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
247 struct ResolutionInfo {
249 dis: Option<Disambiguator>,
251 extra_fragment: Option<String>,
254 struct DiagnosticInfo<'a> {
258 link_range: Range<usize>,
261 #[derive(Clone, Debug, Hash)]
263 pub res: (Res, Option<String>),
264 pub side_channel: Option<(DefKind, DefId)>,
267 struct LinkCollector<'a, 'tcx> {
268 cx: &'a mut DocContext<'tcx>,
269 /// A stack of modules used to decide what scope to resolve in.
271 /// The last module will be used if the parent scope of the current item is
274 /// This is used to store the kind of associated items,
275 /// because `clean` and the disambiguator code expect them to be different.
276 /// See the code for associated items on inherent impls for details.
277 kind_side_channel: Cell<Option<(DefKind, DefId)>>,
278 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
279 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
280 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
283 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
284 /// Given a full link, parse it as an [enum struct variant].
286 /// In particular, this will return an error whenever there aren't three
287 /// full path segments left in the link.
289 /// [enum struct variant]: hir::VariantData::Struct
292 path_str: &'path str,
294 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
295 let tcx = self.cx.tcx;
296 let no_res = || ResolutionFailure::NotResolved {
299 unresolved: path_str.into(),
302 debug!("looking for enum variant {}", path_str);
303 let mut split = path_str.rsplitn(3, "::");
304 let (variant_field_str, variant_field_name) = split
306 .map(|f| (f, Symbol::intern(f)))
307 .expect("fold_item should ensure link is non-empty");
308 let (variant_str, variant_name) =
309 // we're not sure this is a variant at all, so use the full string
310 // If there's no second component, the link looks like `[path]`.
311 // So there's no partial res and we should say the whole link failed to resolve.
312 split.next().map(|f| (f, Symbol::intern(f))).ok_or_else(no_res)?;
315 .map(|f| f.to_owned())
316 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
317 // So there's no partial res.
318 .ok_or_else(no_res)?;
321 .enter_resolver(|resolver| {
322 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
324 .and_then(|(_, res)| res.try_into())
325 .map_err(|()| no_res())?;
328 Res::Def(DefKind::Enum, did) => {
332 .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
333 .any(|item| item.ident.name == variant_name)
335 // This is just to let `fold_item` know that this shouldn't be considered;
336 // it's a bug for the error to make it to the user
337 return Err(ResolutionFailure::Dummy.into());
339 match tcx.type_of(did).kind() {
340 ty::Adt(def, _) if def.is_enum() => {
341 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
345 "variant.{}.field.{}",
346 variant_str, variant_field_name
350 Err(ResolutionFailure::NotResolved {
352 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
353 unresolved: variant_field_str.into(),
361 _ => Err(ResolutionFailure::NotResolved {
363 partial_res: Some(ty_res),
364 unresolved: variant_str.into(),
370 /// Given a primitive type, try to resolve an associated item.
371 fn resolve_primitive_associated_item(
373 prim_ty: PrimitiveType,
376 ) -> Option<(Res, String, Option<(DefKind, DefId)>)> {
377 let tcx = self.cx.tcx;
379 prim_ty.impls(tcx).into_iter().find_map(|&impl_| {
380 tcx.associated_items(impl_)
381 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
383 let kind = item.kind;
384 let out = match kind {
385 ty::AssocKind::Fn => "method",
386 ty::AssocKind::Const => "associatedconstant",
387 ty::AssocKind::Type => "associatedtype",
389 let fragment = format!("{}#{}.{}", prim_ty.as_str(), out, item_name);
390 (Res::Primitive(prim_ty), fragment, Some((kind.as_def_kind(), item.def_id)))
395 /// Resolves a string as a macro.
397 /// FIXME(jynelson): Can this be unified with `resolve()`?
402 ) -> Result<Res, ResolutionFailure<'a>> {
403 let path = ast::Path::from_ident(Ident::from_str(path_str));
404 self.cx.enter_resolver(|resolver| {
405 // FIXME(jynelson): does this really need 3 separate lookups?
406 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
409 &ParentScope::module(resolver.graph_root(), resolver),
413 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
414 return Ok(res.try_into().unwrap());
417 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
418 return Ok(res.try_into().unwrap());
420 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
421 if let Ok((_, res)) =
422 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
424 // don't resolve builtins like `#[derive]`
425 if let Ok(res) = res.try_into() {
429 Err(ResolutionFailure::NotResolved {
432 unresolved: path_str.into(),
437 /// Convenience wrapper around `resolve_str_path_error`.
439 /// This also handles resolving `true` and `false` as booleans.
440 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
441 /// Associated items will never be resolved by this function.
442 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
443 let result = self.cx.enter_resolver(|resolver| {
445 .resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
446 .and_then(|(_, res)| res.try_into())
448 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
450 // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
452 Err(()) => resolve_primitive(path_str, ns),
453 Ok(res) => Some(res),
457 /// Resolves a string as a path within a particular namespace. Returns an
458 /// optional URL fragment in the case of variants and methods.
461 path_str: &'path str,
464 extra_fragment: &Option<String>,
465 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
466 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
468 // FIXME(#76467): make this fallthrough to lookup the associated
469 // item a separate function.
470 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
471 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
472 Res::Def(DefKind::Variant, _) => {
473 return handle_variant(self.cx, res, extra_fragment);
475 // Not a trait item; just return what we found.
476 Res::Primitive(ty) => {
477 if extra_fragment.is_some() {
478 return Err(ErrorKind::AnchorFailure(
479 AnchorFailure::RustdocAnchorConflict(res),
482 return Ok((res, Some(ty.as_str().to_owned())));
484 _ => return Ok((res, extra_fragment.clone())),
488 // Try looking for methods and associated items.
489 let mut split = path_str.rsplitn(2, "::");
490 // NB: `split`'s first element is always defined, even if the delimiter was not present.
491 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
492 let item_str = split.next().unwrap();
493 let item_name = Symbol::intern(item_str);
494 let path_root = split
496 .map(|f| f.to_owned())
497 // If there's no `::`, it's not an associated item.
498 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
500 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
501 ResolutionFailure::NotResolved {
504 unresolved: item_str.into(),
508 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
509 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
510 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
512 resolve_primitive(&path_root, TypeNS)
513 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
515 let (res, fragment, side_channel) =
516 self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
517 let result = if extra_fragment.is_some() {
518 let diag_res = side_channel.map_or(res, |(k, r)| Res::Def(k, r));
519 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(diag_res)))
521 // HACK(jynelson): `clean` expects the type, not the associated item
522 // but the disambiguator logic expects the associated item.
523 // Store the kind in a side channel so that only the disambiguator logic looks at it.
524 if let Some((kind, id)) = side_channel {
525 self.kind_side_channel.set(Some((kind, id)));
527 Ok((res, Some(fragment)))
532 if ns == Namespace::ValueNS {
533 self.variant_field(path_str, module_id)
535 Err(ResolutionFailure::NotResolved {
538 unresolved: path_root.into(),
546 /// - None if no associated item was found
547 /// - Some((_, _, Some(_))) if an item was found and should go through a side channel
548 /// - Some((_, _, None)) otherwise
549 fn resolve_associated_item(
555 ) -> Option<(Res, String, Option<(DefKind, DefId)>)> {
556 let tcx = self.cx.tcx;
559 Res::Primitive(prim) => self.resolve_primitive_associated_item(prim, ns, item_name),
565 | DefKind::ForeignTy,
568 debug!("looking for associated item named {} for item {:?}", item_name, did);
569 // Checks if item_name belongs to `impl SomeItem`
574 tcx.associated_items(imp).find_by_name_and_namespace(
576 Ident::with_dummy_span(item_name),
581 .map(|item| (item.kind, item.def_id))
582 // There should only ever be one associated item that matches from any inherent impl
584 // Check if item_name belongs to `impl SomeTrait for SomeItem`
585 // FIXME(#74563): This gives precedence to `impl SomeItem`:
586 // Although having both would be ambiguous, use impl version for compatibility's sake.
587 // To handle that properly resolve() would have to support
588 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
591 resolve_associated_trait_item(did, module_id, item_name, ns, self.cx);
592 debug!("got associated item kind {:?}", kind);
596 if let Some((kind, id)) = assoc_item {
597 let out = match kind {
598 ty::AssocKind::Fn => "method",
599 ty::AssocKind::Const => "associatedconstant",
600 ty::AssocKind::Type => "associatedtype",
602 // HACK(jynelson): `clean` expects the type, not the associated item
603 // but the disambiguator logic expects the associated item.
604 // Store the kind in a side channel so that only the disambiguator logic looks at it.
607 format!("{}.{}", out, item_name),
608 Some((kind.as_def_kind(), id)),
612 if ns != Namespace::ValueNS {
615 debug!("looking for variants or fields named {} for {:?}", item_name, did);
616 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
617 // NOTE: it's different from variant_field because it resolves fields and variants,
618 // not variant fields (2 path segments, not 3).
619 let def = match tcx.type_of(did).kind() {
620 ty::Adt(def, _) => def,
623 let field = if def.is_enum() {
624 def.all_fields().find(|item| item.ident.name == item_name)
626 def.non_enum_variant().fields.iter().find(|item| item.ident.name == item_name)
628 let kind = if def.is_enum() { DefKind::Variant } else { DefKind::Field };
633 if def.is_enum() { "variant" } else { "structfield" },
636 Some((kind, field.did)),
639 Res::Def(DefKind::Trait, did) => tcx
640 .associated_items(did)
641 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
643 let kind = match item.kind {
644 ty::AssocKind::Const => "associatedconstant",
645 ty::AssocKind::Type => "associatedtype",
646 ty::AssocKind::Fn => {
647 if item.defaultness.has_value() {
655 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
656 (res, format!("{}.{}", kind, item_name), None)
662 /// Used for reporting better errors.
664 /// Returns whether the link resolved 'fully' in another namespace.
665 /// 'fully' here means that all parts of the link resolved, not just some path segments.
666 /// This returns the `Res` even if it was erroneous for some reason
667 /// (such as having invalid URL fragments or being in the wrong namespace).
673 extra_fragment: &Option<String>,
675 // resolve() can't be used for macro namespace
676 let result = match ns {
677 Namespace::MacroNS => self.resolve_macro(path_str, module_id).map_err(ErrorKind::from),
678 Namespace::TypeNS | Namespace::ValueNS => {
679 self.resolve(path_str, ns, module_id, extra_fragment).map(|(res, _)| res)
683 let res = match result {
684 Ok(res) => Some(res),
685 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
686 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
687 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
689 self.kind_side_channel.take().map(|(kind, id)| Res::Def(kind, id)).or(res)
693 /// Look to see if a resolved item has an associated item named `item_name`.
695 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
696 /// find `std::error::Error::source` and return
697 /// `<io::Error as error::Error>::source`.
698 fn resolve_associated_trait_item(
703 cx: &mut DocContext<'_>,
704 ) -> Option<(ty::AssocKind, DefId)> {
705 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
706 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
707 // meantime, just don't look for these blanket impls.
709 // Next consider explicit impls: `impl MyTrait for MyType`
710 // Give precedence to inherent impls.
711 let traits = traits_implemented_by(cx, did, module);
712 debug!("considering traits {:?}", traits);
713 let mut candidates = traits.iter().filter_map(|&trait_| {
715 .associated_items(trait_)
716 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
717 .map(|assoc| (assoc.kind, assoc.def_id))
719 // FIXME(#74563): warn about ambiguity
720 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
724 /// Given a type, return all traits in scope in `module` implemented by that type.
726 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
727 /// So it is not stable to serialize cross-crate.
728 fn traits_implemented_by(cx: &mut DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
729 let mut resolver = cx.resolver.borrow_mut();
730 let in_scope_traits = cx.module_trait_cache.entry(module).or_insert_with(|| {
731 resolver.access(|resolver| {
732 let parent_scope = &ParentScope::module(resolver.get_module(module), resolver);
734 .traits_in_scope(None, parent_scope, SyntaxContext::root(), None)
736 .map(|candidate| candidate.def_id)
742 let ty = tcx.type_of(type_);
743 let iter = in_scope_traits.iter().flat_map(|&trait_| {
744 trace!("considering explicit impl for trait {:?}", trait_);
746 // Look at each trait implementation to see if it's an impl for `did`
747 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
748 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
749 // Check if these are the same type.
750 let impl_type = trait_ref.self_ty();
752 "comparing type {} with kind {:?} against type {:?}",
757 // Fast path: if this is a primitive simple `==` will work
758 let saw_impl = impl_type == ty
759 || match impl_type.kind() {
760 // Check if these are the same def_id
762 debug!("adt def_id: {:?}", def.did);
765 ty::Foreign(def_id) => *def_id == type_,
769 if saw_impl { Some(trait_) } else { None }
775 /// Check for resolve collisions between a trait and its derive.
777 /// These are common and we should just resolve to the trait in that case.
778 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
782 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
783 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
789 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
790 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
791 use rustc_middle::ty::DefIdTree;
793 let parent_node = if item.is_fake() {
796 find_nearest_parent_module(self.cx.tcx, item.def_id)
799 if parent_node.is_some() {
800 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
803 // find item's parent to resolve `Self` in item's docs below
804 debug!("looking for the `Self` type");
805 let self_id = if item.is_fake() {
807 // Checking if the item is a field in an enum variant
808 } else if (matches!(self.cx.tcx.def_kind(item.def_id), DefKind::Field)
810 self.cx.tcx.def_kind(self.cx.tcx.parent(item.def_id).unwrap()),
814 self.cx.tcx.parent(item.def_id).and_then(|item_id| self.cx.tcx.parent(item_id))
816 self.cx.tcx.def_kind(item.def_id),
823 self.cx.tcx.parent(item.def_id)
824 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
825 // Fixing this breaks `fn render_deref_methods`.
826 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
827 // regardless of what rustdoc wants to call it.
828 } else if let Some(parent) = self.cx.tcx.parent(item.def_id) {
829 let parent_kind = self.cx.tcx.def_kind(parent);
830 Some(if parent_kind == DefKind::Impl { parent } else { item.def_id })
835 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
836 let self_name = self_id.and_then(|self_id| {
837 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
838 // using `ty.to_string()` (or any variant) has issues with raw idents
839 let ty = self.cx.tcx.type_of(self_id);
840 let name = match ty.kind() {
841 ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
842 other if other.is_primitive() => Some(ty.to_string()),
845 debug!("using type_of(): {:?}", name);
848 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
849 debug!("using item_name(): {:?}", name);
854 if item.is_mod() && item.attrs.inner_docs {
855 self.mod_ids.push(item.def_id);
858 // We want to resolve in the lexical scope of the documentation.
859 // In the presence of re-exports, this is not the same as the module of the item.
860 // Rather than merging all documentation into one, resolve it one attribute at a time
861 // so we know which module it came from.
862 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
863 debug!("combined_docs={}", doc);
865 let (krate, parent_node) = if let Some(id) = parent_module {
868 (item.def_id.krate, parent_node)
870 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
871 // This is a degenerate case and it's not supported by rustdoc.
872 for md_link in markdown_links(&doc) {
873 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
874 if let Some(link) = link {
875 item.attrs.links.push(link);
880 Some(if item.is_mod() {
881 if !item.attrs.inner_docs {
882 self.mod_ids.push(item.def_id);
885 let ret = self.fold_item_recur(item);
889 self.fold_item_recur(item)
894 impl LinkCollector<'_, '_> {
895 /// This is the entry point for resolving an intra-doc link.
897 /// FIXME(jynelson): this is way too many arguments
902 self_name: &Option<String>,
903 parent_node: Option<DefId>,
905 ori_link: MarkdownLink,
906 ) -> Option<ItemLink> {
907 trace!("considering link '{}'", ori_link.link);
909 // Bail early for real links.
910 if ori_link.link.contains('/') {
914 // [] is mostly likely not supposed to be a link
915 if ori_link.link.is_empty() {
919 let link = ori_link.link.replace("`", "");
920 let no_backticks_range = range_between_backticks(&ori_link);
921 let parts = link.split('#').collect::<Vec<_>>();
922 let (link, extra_fragment) = if parts.len() > 2 {
923 // A valid link can't have multiple #'s
930 AnchorFailure::MultipleAnchors,
933 } else if parts.len() == 2 {
934 if parts[0].trim().is_empty() {
935 // This is an anchor to an element of the current page, nothing to do in here!
938 (parts[0], Some(parts[1].to_owned()))
943 // Parse and strip the disambiguator from the link, if present.
944 let (mut path_str, disambiguator) = match Disambiguator::from_str(&link) {
945 Ok(Some((d, path))) => (path.trim(), Some(d)),
946 Ok(None) => (link.trim(), None),
947 Err((err_msg, relative_range)) => {
948 let disambiguator_range = (no_backticks_range.start + relative_range.start)
949 ..(no_backticks_range.start + relative_range.end);
950 disambiguator_error(self.cx, &item, dox, disambiguator_range, &err_msg);
955 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch))) {
959 // We stripped `()` and `!` when parsing the disambiguator.
960 // Add them back to be displayed, but not prefix disambiguators.
962 disambiguator.map(|d| d.display_for(path_str)).unwrap_or_else(|| path_str.to_owned());
964 // In order to correctly resolve intra-doc links we need to
965 // pick a base AST node to work from. If the documentation for
966 // this module came from an inner comment (//!) then we anchor
967 // our name resolution *inside* the module. If, on the other
968 // hand it was an outer comment (///) then we anchor the name
969 // resolution in the parent module on the basis that the names
970 // used are more likely to be intended to be parent names. For
971 // this, we set base_node to None for inner comments since
972 // we've already pushed this node onto the resolution stack but
973 // for outer comments we explicitly try and resolve against the
974 // parent_node first.
975 let base_node = if item.is_mod() && item.attrs.inner_docs {
976 self.mod_ids.last().copied()
981 let mut module_id = if let Some(id) = base_node {
985 debug!("attempting to resolve item without parent module: {}", path_str);
993 smallvec![ResolutionFailure::NoParentItem],
999 // replace `Self` with suitable item's parent name
1000 let is_lone_self = path_str == "Self";
1001 let is_lone_crate = path_str == "crate";
1002 if path_str.starts_with("Self::") || is_lone_self {
1003 if let Some(ref name) = self_name {
1007 resolved_self = format!("{}::{}", name, &path_str[6..]);
1008 path_str = &resolved_self;
1011 } else if path_str.starts_with("crate::") || is_lone_crate {
1012 use rustc_span::def_id::CRATE_DEF_INDEX;
1014 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1015 // But rustdoc wants it to mean the crate this item was originally present in.
1016 // To work around this, remove it and resolve relative to the crate root instead.
1017 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1018 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1019 // FIXME(#78696): This doesn't always work.
1023 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1024 path_str = &resolved_self;
1026 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1029 // Strip generics from the path.
1030 let stripped_path_string;
1031 if path_str.contains(['<', '>'].as_slice()) {
1032 stripped_path_string = match strip_generics_from_path(path_str) {
1035 debug!("link has malformed generics: {}", path_str);
1043 smallvec![err_kind],
1048 path_str = &stripped_path_string;
1050 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1051 assert!(!path_str.contains(['<', '>'].as_slice()));
1053 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1054 if path_str.contains(' ') {
1058 let diag_info = DiagnosticInfo {
1061 ori_link: &ori_link.link,
1062 link_range: ori_link.range.clone(),
1064 let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(
1068 path_str: path_str.to_owned(),
1072 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1075 // Check for a primitive which might conflict with a module
1076 // Report the ambiguity and require that the user specify which one they meant.
1077 // FIXME: could there ever be a primitive not in the type namespace?
1080 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1081 ) && !matches!(res, Res::Primitive(_))
1083 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1085 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1086 if fragment.is_some() {
1093 AnchorFailure::RustdocAnchorConflict(prim),
1098 fragment = Some(prim.name(self.cx.tcx));
1100 // `[char]` when a `char` module is in scope
1101 let candidates = vec![res, prim];
1102 ambiguity_error(self.cx, &item, path_str, dox, ori_link.range, candidates);
1108 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1109 // The resolved item did not match the disambiguator; give a better error than 'not found'
1110 let msg = format!("incompatible link kind for `{}`", path_str);
1111 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1113 "this link resolved to {} {}, which is not {} {}",
1116 specified.article(),
1120 suggest_disambiguator(resolved, diag, path_str, dox, sp, &ori_link.range);
1124 BROKEN_INTRA_DOC_LINKS,
1133 let verify = |kind: DefKind, id: DefId| {
1134 let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id));
1135 debug!("intra-doc link to {} resolved to {:?} (id: {:?})", path_str, res, id);
1137 // Disallow e.g. linking to enums with `struct@`
1138 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1139 match (kind, disambiguator) {
1140 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1141 // NOTE: this allows 'method' to mean both normal functions and associated functions
1142 // This can't cause ambiguity because both are in the same namespace.
1143 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1144 // These are namespaces; allow anything in the namespace to match
1145 | (_, Some(Disambiguator::Namespace(_)))
1146 // If no disambiguator given, allow anything
1148 // All of these are valid, so do nothing
1150 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1151 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1152 report_mismatch(specified, Disambiguator::Kind(kind));
1157 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1158 if let Some((src_id, dst_id)) = id
1160 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
1162 use rustc_hir::def_id::LOCAL_CRATE;
1164 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1165 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1167 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
1168 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
1170 privacy_error(self.cx, &item, &path_str, dox, &ori_link);
1178 Res::Primitive(prim) => {
1179 if let Some((kind, id)) = self.kind_side_channel.take() {
1180 // We're actually resolving an associated item of a primitive, so we need to
1181 // verify the disambiguator (if any) matches the type of the associated item.
1182 // This case should really follow the same flow as the `Res::Def` branch below,
1183 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1184 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1185 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1186 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1187 // for discussion on the matter.
1190 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1191 // However I'm not sure how to check that across crates.
1192 if prim == PrimitiveType::RawPointer
1193 && item.def_id.is_local()
1194 && !self.cx.tcx.features().intra_doc_pointers
1196 let span = super::source_span_for_markdown_range(
1202 .unwrap_or_else(|| span_of_attrs(&item.attrs).unwrap_or(item.span.inner()));
1204 rustc_session::parse::feature_err(
1205 &self.cx.tcx.sess.parse_sess,
1206 sym::intra_doc_pointers,
1208 "linking to associated items of raw pointers is experimental",
1210 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1214 match disambiguator {
1215 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1217 report_mismatch(other, Disambiguator::Primitive);
1223 Some(ItemLink { link: ori_link.link, link_text, did: None, fragment })
1225 Res::Def(kind, id) => {
1227 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1228 Some(ItemLink { link: ori_link.link, link_text, did: Some(id), fragment })
1233 fn resolve_with_disambiguator_cached(
1235 key: ResolutionInfo,
1236 diag: DiagnosticInfo<'_>,
1237 cache_resolution_failure: bool,
1238 ) -> Option<(Res, Option<String>)> {
1239 // Try to look up both the result and the corresponding side channel value
1240 if let Some(ref cached) = self.visited_links.get(&key) {
1243 self.kind_side_channel.set(cached.side_channel.clone());
1244 return Some(cached.res.clone());
1246 None if cache_resolution_failure => return None,
1248 // Although we hit the cache and found a resolution error, this link isn't
1249 // supposed to cache those. Run link resolution again to emit the expected
1250 // resolution error.
1255 let res = self.resolve_with_disambiguator(&key, diag);
1257 // Cache only if resolved successfully - don't silence duplicate errors
1258 if let Some(res) = res {
1259 // Store result for the actual namespace
1260 self.visited_links.insert(
1264 side_channel: self.kind_side_channel.clone().into_inner(),
1270 if cache_resolution_failure {
1271 // For reference-style links we only want to report one resolution error
1272 // so let's cache them as well.
1273 self.visited_links.insert(key, None);
1280 /// After parsing the disambiguator, resolve the main part of the link.
1281 // FIXME(jynelson): wow this is just so much
1282 fn resolve_with_disambiguator(
1284 key: &ResolutionInfo,
1285 diag: DiagnosticInfo<'_>,
1286 ) -> Option<(Res, Option<String>)> {
1287 let disambiguator = key.dis;
1288 let path_str = &key.path_str;
1289 let base_node = key.module_id;
1290 let extra_fragment = &key.extra_fragment;
1292 match disambiguator.map(Disambiguator::ns) {
1293 Some(expected_ns @ (ValueNS | TypeNS)) => {
1294 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1295 Ok(res) => Some(res),
1296 Err(ErrorKind::Resolve(box mut kind)) => {
1297 // We only looked in one namespace. Try to give a better error if possible.
1298 if kind.full_res().is_none() {
1299 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1300 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1301 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1302 for &new_ns in &[other_ns, MacroNS] {
1304 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1306 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1320 // This could just be a normal link or a broken link
1321 // we could potentially check if something is
1322 // "intra-doc-link-like" and warn in that case.
1325 Err(ErrorKind::AnchorFailure(msg)) => {
1340 let mut candidates = PerNS {
1342 .resolve_macro(path_str, base_node)
1343 .map(|res| (res, extra_fragment.clone())),
1344 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1346 debug!("got res in TypeNS: {:?}", res);
1349 Err(ErrorKind::AnchorFailure(msg)) => {
1360 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1362 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1364 Err(ErrorKind::AnchorFailure(msg)) => {
1375 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1377 .and_then(|(res, fragment)| {
1378 // Constructors are picked up in the type namespace.
1380 Res::Def(DefKind::Ctor(..), _) => {
1381 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1384 match (fragment, extra_fragment.clone()) {
1385 (Some(fragment), Some(_)) => {
1386 // Shouldn't happen but who knows?
1387 Ok((res, Some(fragment)))
1389 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1396 let len = candidates.iter().filter(|res| res.is_ok()).count();
1406 candidates.into_iter().filter_map(|res| res.err()).collect(),
1408 // this could just be a normal link
1413 Some(candidates.into_iter().filter_map(|res| res.ok()).next().unwrap())
1414 } else if len == 2 && is_derive_trait_collision(&candidates) {
1415 Some(candidates.type_ns.unwrap())
1417 if is_derive_trait_collision(&candidates) {
1418 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1420 // If we're reporting an ambiguity, don't mention the namespaces that failed
1421 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1428 candidates.present_items().collect(),
1434 match self.resolve_macro(path_str, base_node) {
1435 Ok(res) => Some((res, extra_fragment.clone())),
1437 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1438 for &ns in &[TypeNS, ValueNS] {
1440 self.check_full_res(ns, path_str, base_node, extra_fragment)
1443 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1464 /// Get the section of a link between the backticks,
1465 /// or the whole link if there aren't any backticks.
1473 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1474 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1475 let before_second_backtick_group = ori_link
1478 .skip(after_first_backtick_group)
1479 .position(|b| b == b'`')
1480 .unwrap_or(ori_link.link.len());
1481 (ori_link.range.start + after_first_backtick_group)
1482 ..(ori_link.range.start + before_second_backtick_group)
1485 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1486 /// Disambiguators for a link.
1487 crate enum Disambiguator {
1490 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1492 /// `struct@` or `f()`
1495 Namespace(Namespace),
1498 impl Disambiguator {
1499 /// The text that should be displayed when the path is rendered as HTML.
1501 /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1502 fn display_for(&self, path: &str) -> String {
1504 // FIXME: this will have different output if the user had `m!()` originally.
1505 Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1506 Self::Kind(DefKind::Fn) => format!("{}()", path),
1507 _ => path.to_owned(),
1511 /// Given a link, parse and return `(disambiguator, path_str)`.
1513 /// This returns `Ok(Some(...))` if a disambiguator was found,
1514 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1515 /// if there was a problem with the disambiguator.
1516 crate fn from_str(link: &str) -> Result<Option<(Self, &str)>, (String, Range<usize>)> {
1517 use Disambiguator::{Kind, Namespace as NS, Primitive};
1519 if let Some(idx) = link.find('@') {
1520 let (prefix, rest) = link.split_at(idx);
1521 let d = match prefix {
1522 "struct" => Kind(DefKind::Struct),
1523 "enum" => Kind(DefKind::Enum),
1524 "trait" => Kind(DefKind::Trait),
1525 "union" => Kind(DefKind::Union),
1526 "module" | "mod" => Kind(DefKind::Mod),
1527 "const" | "constant" => Kind(DefKind::Const),
1528 "static" => Kind(DefKind::Static),
1529 "function" | "fn" | "method" => Kind(DefKind::Fn),
1530 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1531 "type" => NS(Namespace::TypeNS),
1532 "value" => NS(Namespace::ValueNS),
1533 "macro" => NS(Namespace::MacroNS),
1534 "prim" | "primitive" => Primitive,
1535 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1537 Ok(Some((d, &rest[1..])))
1540 ("!()", DefKind::Macro(MacroKind::Bang)),
1541 ("()", DefKind::Fn),
1542 ("!", DefKind::Macro(MacroKind::Bang)),
1544 for &(suffix, kind) in &suffixes {
1545 if let Some(link) = link.strip_suffix(suffix) {
1546 // Avoid turning `!` or `()` into an empty string
1547 if !link.is_empty() {
1548 return Ok(Some((Kind(kind), link)));
1556 fn from_res(res: Res) -> Self {
1558 Res::Def(kind, _) => Disambiguator::Kind(kind),
1559 Res::Primitive(_) => Disambiguator::Primitive,
1563 /// Used for error reporting.
1564 fn suggestion(self) -> Suggestion {
1565 let kind = match self {
1566 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1567 Disambiguator::Kind(kind) => kind,
1568 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1570 if kind == DefKind::Macro(MacroKind::Bang) {
1571 return Suggestion::Macro;
1572 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1573 return Suggestion::Function;
1576 let prefix = match kind {
1577 DefKind::Struct => "struct",
1578 DefKind::Enum => "enum",
1579 DefKind::Trait => "trait",
1580 DefKind::Union => "union",
1581 DefKind::Mod => "mod",
1582 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1585 DefKind::Static => "static",
1586 DefKind::Macro(MacroKind::Derive) => "derive",
1587 // Now handle things that don't have a specific disambiguator
1590 .expect("tried to calculate a disambiguator for a def without a namespace?")
1592 Namespace::TypeNS => "type",
1593 Namespace::ValueNS => "value",
1594 Namespace::MacroNS => "macro",
1598 Suggestion::Prefix(prefix)
1601 fn ns(self) -> Namespace {
1603 Self::Namespace(n) => n,
1605 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1607 Self::Primitive => TypeNS,
1611 fn article(self) -> &'static str {
1613 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1614 Self::Kind(k) => k.article(),
1615 Self::Primitive => "a",
1619 fn descr(self) -> &'static str {
1621 Self::Namespace(n) => n.descr(),
1622 // HACK(jynelson): by looking at the source I saw the DefId we pass
1623 // for `expected.descr()` doesn't matter, since it's not a crate
1624 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1625 Self::Primitive => "builtin type",
1630 /// A suggestion to show in a diagnostic.
1633 Prefix(&'static str),
1641 fn descr(&self) -> Cow<'static, str> {
1643 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1644 Self::Function => "add parentheses".into(),
1645 Self::Macro => "add an exclamation mark".into(),
1649 fn as_help(&self, path_str: &str) -> String {
1650 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1652 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1653 Self::Function => format!("{}()", path_str),
1654 Self::Macro => format!("{}!", path_str),
1659 /// Reports a diagnostic for an intra-doc link.
1661 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1662 /// the entire documentation block is used for the lint. If a range is provided but the span
1663 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1665 /// The `decorate` callback is invoked in all cases to allow further customization of the
1666 /// diagnostic before emission. If the span of the link was able to be determined, the second
1667 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1669 fn report_diagnostic(
1671 lint: &'static Lint,
1675 link_range: &Range<usize>,
1676 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1678 let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1679 Some(hir_id) => hir_id,
1681 // If non-local, no need to check anything.
1682 info!("ignoring warning from parent crate: {}", msg);
1687 let attrs = &item.attrs;
1688 let sp = span_of_attrs(attrs).unwrap_or(item.span.inner());
1690 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1691 let mut diag = lint.build(msg);
1693 let span = super::source_span_for_markdown_range(tcx, dox, link_range, attrs);
1695 if let Some(sp) = span {
1698 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1701 // last_new_line_offset
1702 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1703 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1705 // Print the line containing the `link_range` and manually mark it with '^'s.
1707 "the link appears in this line:\n\n{line}\n\
1708 {indicator: <before$}{indicator:^<found$}",
1711 before = link_range.start - last_new_line_offset,
1712 found = link_range.len(),
1716 decorate(&mut diag, span);
1722 /// Reports a link that failed to resolve.
1724 /// This also tries to resolve any intermediate path segments that weren't
1725 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1726 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1727 fn resolution_failure(
1728 collector: &mut LinkCollector<'_, '_>,
1731 disambiguator: Option<Disambiguator>,
1733 link_range: Range<usize>,
1734 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1736 let tcx = collector.cx.tcx;
1739 BROKEN_INTRA_DOC_LINKS,
1740 &format!("unresolved link to `{}`", path_str),
1745 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1746 let assoc_item_not_allowed = |res: Res| {
1747 let name = res.name(tcx);
1749 "`{}` is {} {}, not a module or type, and cannot have associated items",
1755 // ignore duplicates
1756 let mut variants_seen = SmallVec::<[_; 3]>::new();
1757 for mut failure in kinds {
1758 let variant = std::mem::discriminant(&failure);
1759 if variants_seen.contains(&variant) {
1762 variants_seen.push(variant);
1764 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1769 let module_id = *module_id;
1770 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1771 // FIXME: maybe use itertools `collect_tuple` instead?
1772 fn split(path: &str) -> Option<(&str, &str)> {
1773 let mut splitter = path.rsplitn(2, "::");
1774 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1777 // Check if _any_ parent of the path gets resolved.
1778 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1779 let mut name = path_str;
1781 let (start, end) = if let Some(x) = split(name) {
1784 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1785 if partial_res.is_none() {
1786 *unresolved = name.into();
1791 for &ns in &[TypeNS, ValueNS, MacroNS] {
1793 collector.check_full_res(ns, &start, module_id, &None)
1795 debug!("found partial_res={:?}", res);
1796 *partial_res = Some(res);
1797 *unresolved = end.into();
1801 *unresolved = end.into();
1804 let last_found_module = match *partial_res {
1805 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1806 None => Some(module_id),
1809 // See if this was a module: `[path]` or `[std::io::nope]`
1810 if let Some(module) = last_found_module {
1811 let note = if partial_res.is_some() {
1812 // Part of the link resolved; e.g. `std::io::nonexistent`
1813 let module_name = tcx.item_name(module);
1814 format!("no item named `{}` in module `{}`", unresolved, module_name)
1816 // None of the link resolved; e.g. `Notimported`
1817 format!("no item named `{}` in scope", unresolved)
1819 if let Some(span) = sp {
1820 diag.span_label(span, ¬e);
1825 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1826 // Otherwise, the `[]` might be unrelated.
1827 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1828 if !path_str.contains("::") {
1829 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1835 // Otherwise, it must be an associated item or variant
1836 let res = partial_res.expect("None case was handled by `last_found_module`");
1837 let name = res.name(tcx);
1838 let kind = match res {
1839 Res::Def(kind, _) => Some(kind),
1840 Res::Primitive(_) => None,
1842 let path_description = if let Some(kind) = kind {
1844 Mod | ForeignMod => "inner item",
1845 Struct => "field or associated item",
1846 Enum | Union => "variant or associated item",
1863 let note = assoc_item_not_allowed(res);
1864 if let Some(span) = sp {
1865 diag.span_label(span, ¬e);
1871 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1872 | Static => "associated item",
1873 Impl | GlobalAsm => unreachable!("not a path"),
1879 "the {} `{}` has no {} named `{}`",
1882 disambiguator.map_or(path_description, |d| d.descr()),
1885 if let Some(span) = sp {
1886 diag.span_label(span, ¬e);
1893 let note = match failure {
1894 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1895 ResolutionFailure::Dummy => continue,
1896 ResolutionFailure::WrongNamespace { res, expected_ns } => {
1897 if let Res::Def(kind, _) = res {
1898 let disambiguator = Disambiguator::Kind(kind);
1899 suggest_disambiguator(
1910 "this link resolves to {}, which is not in the {} namespace",
1915 ResolutionFailure::NoParentItem => {
1916 diag.level = rustc_errors::Level::Bug;
1917 "all intra-doc links should have a parent item".to_owned()
1919 ResolutionFailure::MalformedGenerics(variant) => match variant {
1920 MalformedGenerics::UnbalancedAngleBrackets => {
1921 String::from("unbalanced angle brackets")
1923 MalformedGenerics::MissingType => {
1924 String::from("missing type for generic parameters")
1926 MalformedGenerics::HasFullyQualifiedSyntax => {
1927 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1928 String::from("fully-qualified syntax is unsupported")
1930 MalformedGenerics::InvalidPathSeparator => {
1931 String::from("has invalid path separator")
1933 MalformedGenerics::TooManyAngleBrackets => {
1934 String::from("too many angle brackets")
1936 MalformedGenerics::EmptyAngleBrackets => {
1937 String::from("empty angle brackets")
1941 if let Some(span) = sp {
1942 diag.span_label(span, ¬e);
1951 /// Report an anchor failure.
1953 cx: &DocContext<'_>,
1957 link_range: Range<usize>,
1958 failure: AnchorFailure,
1960 let msg = match failure {
1961 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1962 AnchorFailure::RustdocAnchorConflict(res) => format!(
1963 "`{}` contains an anchor, but links to {kind}s are already anchored",
1969 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1970 if let Some(sp) = sp {
1971 diag.span_label(sp, "contains invalid anchor");
1976 /// Report an error in the link disambiguator.
1977 fn disambiguator_error(
1978 cx: &DocContext<'_>,
1981 link_range: Range<usize>,
1984 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, item, dox, &link_range, |_diag, _sp| {});
1987 /// Report an ambiguity error, where there were multiple possible resolutions.
1989 cx: &DocContext<'_>,
1993 link_range: Range<usize>,
1994 candidates: Vec<Res>,
1996 let mut msg = format!("`{}` is ", path_str);
1998 match candidates.as_slice() {
1999 [first_def, second_def] => {
2001 "both {} {} and {} {}",
2002 first_def.article(),
2004 second_def.article(),
2009 let mut candidates = candidates.iter().peekable();
2010 while let Some(res) = candidates.next() {
2011 if candidates.peek().is_some() {
2012 msg += &format!("{} {}, ", res.article(), res.descr());
2014 msg += &format!("and {} {}", res.article(), res.descr());
2020 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
2021 if let Some(sp) = sp {
2022 diag.span_label(sp, "ambiguous link");
2024 diag.note("ambiguous link");
2027 for res in candidates {
2028 let disambiguator = Disambiguator::from_res(res);
2029 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
2034 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2036 fn suggest_disambiguator(
2037 disambiguator: Disambiguator,
2038 diag: &mut DiagnosticBuilder<'_>,
2041 sp: Option<rustc_span::Span>,
2042 link_range: &Range<usize>,
2044 let suggestion = disambiguator.suggestion();
2045 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
2047 if let Some(sp) = sp {
2048 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
2049 format!("`{}`", suggestion.as_help(path_str))
2051 suggestion.as_help(path_str)
2054 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
2056 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2060 /// Report a link from a public item to a private one.
2061 fn privacy_error(cx: &DocContext<'_>, item: &Item, path_str: &str, dox: &str, link: &MarkdownLink) {
2063 let item_name = match item.name {
2065 sym = name.as_str();
2068 None => "<unknown>",
2071 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2073 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, item, dox, &link.range, |diag, sp| {
2074 if let Some(sp) = sp {
2075 diag.span_label(sp, "this item is private");
2078 let note_msg = if cx.render_options.document_private {
2079 "this link resolves only because you passed `--document-private-items`, but will break without"
2081 "this link will resolve properly if you pass `--document-private-items`"
2083 diag.note(note_msg);
2087 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2089 cx: &DocContext<'_>,
2091 extra_fragment: &Option<String>,
2092 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
2093 use rustc_middle::ty::DefIdTree;
2095 if extra_fragment.is_some() {
2096 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2099 .parent(res.def_id())
2101 let parent_def = Res::Def(DefKind::Enum, parent);
2102 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2103 (parent_def, Some(format!("variant.{}", variant.ident.name)))
2105 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2108 /// Resolve a primitive type or value.
2109 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2113 use PrimitiveType::*;
2114 let prim = match path_str {
2130 "bool" | "true" | "false" => Bool,
2131 "str" | "&str" => Str,
2132 // See #80181 for why these don't have symbols associated.
2137 "pointer" | "*const" | "*mut" => RawPointer,
2138 "reference" | "&" | "&mut" => Reference,
2140 "never" | "!" => Never,
2143 debug!("resolved primitives {:?}", prim);
2144 Some(Res::Primitive(prim))
2147 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2148 let mut stripped_segments = vec![];
2149 let mut path = path_str.chars().peekable();
2150 let mut segment = Vec::new();
2152 while let Some(chr) = path.next() {
2155 if path.next_if_eq(&':').is_some() {
2156 let stripped_segment =
2157 strip_generics_from_path_segment(mem::take(&mut segment))?;
2158 if !stripped_segment.is_empty() {
2159 stripped_segments.push(stripped_segment);
2162 return Err(ResolutionFailure::MalformedGenerics(
2163 MalformedGenerics::InvalidPathSeparator,
2172 return Err(ResolutionFailure::MalformedGenerics(
2173 MalformedGenerics::TooManyAngleBrackets,
2177 return Err(ResolutionFailure::MalformedGenerics(
2178 MalformedGenerics::EmptyAngleBrackets,
2184 while let Some(chr) = path.next_if(|c| *c != '>') {
2191 _ => segment.push(chr),
2193 trace!("raw segment: {:?}", segment);
2196 if !segment.is_empty() {
2197 let stripped_segment = strip_generics_from_path_segment(segment)?;
2198 if !stripped_segment.is_empty() {
2199 stripped_segments.push(stripped_segment);
2203 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2205 let stripped_path = stripped_segments.join("::");
2207 if !stripped_path.is_empty() {
2210 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2214 fn strip_generics_from_path_segment(
2216 ) -> Result<String, ResolutionFailure<'static>> {
2217 let mut stripped_segment = String::new();
2218 let mut param_depth = 0;
2220 let mut latest_generics_chunk = String::new();
2225 latest_generics_chunk.clear();
2226 } else if c == '>' {
2228 if latest_generics_chunk.contains(" as ") {
2229 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2230 // Give a helpful error message instead of completely ignoring the angle brackets.
2231 return Err(ResolutionFailure::MalformedGenerics(
2232 MalformedGenerics::HasFullyQualifiedSyntax,
2236 if param_depth == 0 {
2237 stripped_segment.push(c);
2239 latest_generics_chunk.push(c);
2244 if param_depth == 0 {
2245 Ok(stripped_segment)
2247 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2248 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))