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, span_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::{BytePos, 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::html::markdown::{markdown_links, MarkdownLink};
36 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
37 use crate::passes::Pass;
38 use crate::visit::DocVisitor;
41 crate use early::load_intra_link_crates;
43 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
44 name: "collect-intra-doc-links",
45 run: collect_intra_doc_links,
46 description: "resolves intra-doc links",
49 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
50 let mut collector = LinkCollector {
53 kind_side_channel: Cell::new(None),
54 visited_links: FxHashMap::default(),
56 collector.visit_crate(&krate);
60 /// Top-level errors emitted by this pass.
62 Resolve(Box<ResolutionFailure<'a>>),
63 AnchorFailure(AnchorFailure),
66 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
67 fn from(err: ResolutionFailure<'a>) -> Self {
68 ErrorKind::Resolve(box err)
72 #[derive(Copy, Clone, Debug, Hash)]
75 Primitive(PrimitiveType),
78 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
81 fn descr(self) -> &'static str {
83 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
84 Res::Primitive(_) => "builtin type",
88 fn article(self) -> &'static str {
90 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
91 Res::Primitive(_) => "a",
95 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
97 Res::Def(_, id) => tcx.item_name(id),
98 Res::Primitive(prim) => prim.as_sym(),
102 fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
104 Res::Def(_, id) => id,
105 Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
109 fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
111 Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
112 // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
113 Res::Primitive(_) => None,
118 impl TryFrom<ResolveRes> for Res {
121 fn try_from(res: ResolveRes) -> Result<Self, ()> {
122 use rustc_hir::def::Res::*;
124 Def(kind, id) => Ok(Res::Def(kind, id)),
125 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
127 NonMacroAttr(..) | Err => Result::Err(()),
128 other => bug!("unrecognized res {:?}", other),
133 /// A link failed to resolve.
135 enum ResolutionFailure<'a> {
136 /// This resolved, but with the wrong namespace.
138 /// What the link resolved to.
140 /// The expected namespace for the resolution, determined from the link's disambiguator.
142 /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
143 /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
144 expected_ns: Namespace,
146 /// The link failed to resolve. [`resolution_failure`] should look to see if there's
147 /// a more helpful error that can be given.
149 /// The scope the link was resolved in.
151 /// If part of the link resolved, this has the `Res`.
153 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
154 partial_res: Option<Res>,
155 /// The remaining unresolved path segments.
157 /// In `[std::io::Error::x]`, `x` would be unresolved.
158 unresolved: Cow<'a, str>,
160 /// This happens when rustdoc can't determine the parent scope for an item.
161 /// It is always a bug in rustdoc.
163 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
164 MalformedGenerics(MalformedGenerics),
165 /// Used to communicate that this should be ignored, but shouldn't be reported to the user.
167 /// This happens when there is no disambiguator and one of the namespaces
168 /// failed to resolve.
173 enum MalformedGenerics {
174 /// This link has unbalanced angle brackets.
176 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
177 UnbalancedAngleBrackets,
178 /// The generics are not attached to a type.
180 /// For example, `<T>` should trigger this.
182 /// This is detected by checking if the path is empty after the generics are stripped.
184 /// The link uses fully-qualified syntax, which is currently unsupported.
186 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
188 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
190 HasFullyQualifiedSyntax,
191 /// The link has an invalid path separator.
193 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
194 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
197 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
198 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
199 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
201 /// This is detected by checking if there is a colon followed by a non-colon in the link.
202 InvalidPathSeparator,
203 /// The link has too many angle brackets.
205 /// For example, `Vec<<T>>` should trigger this.
206 TooManyAngleBrackets,
207 /// The link has empty angle brackets.
209 /// For example, `Vec<>` should trigger this.
213 impl ResolutionFailure<'a> {
214 /// This resolved fully (not just partially) but is erroneous for some other reason
216 /// Returns the full resolution of the link, if present.
217 fn full_res(&self) -> Option<Res> {
219 Self::WrongNamespace { res, expected_ns: _ } => Some(*res),
226 /// User error: `[std#x#y]` is not valid
228 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
230 /// This is an unfortunate state of affairs. Not every item that can be
231 /// linked to has its own page; sometimes it is a subheading within a page,
232 /// like for associated items. In those cases, rustdoc uses an anchor to
233 /// link to the subheading. Since you can't have two anchors for the same
234 /// link, Rustdoc disallows having a user-specified anchor.
236 /// Most of the time this is fine, because you can just link to the page of
237 /// the item if you want to provide your own anchor.
238 RustdocAnchorConflict(Res),
241 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
242 crate enum UrlFragment {
245 AssociatedConstant(Symbol),
246 AssociatedType(Symbol),
250 VariantField { variant: Symbol, field: Symbol },
256 /// Create a fragment for an associated item.
258 /// `is_prototype` is whether this associated item is a trait method
259 /// without a default definition.
260 fn from_assoc_item(name: Symbol, kind: ty::AssocKind, is_prototype: bool) -> Self {
262 ty::AssocKind::Fn => {
264 UrlFragment::TyMethod(name)
266 UrlFragment::Method(name)
269 ty::AssocKind::Const => UrlFragment::AssociatedConstant(name),
270 ty::AssocKind::Type => UrlFragment::AssociatedType(name),
275 /// Render the fragment, including the leading `#`.
276 impl std::fmt::Display for UrlFragment {
277 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280 UrlFragment::Method(name) => write!(f, "method.{}", name),
281 UrlFragment::TyMethod(name) => write!(f, "tymethod.{}", name),
282 UrlFragment::AssociatedConstant(name) => write!(f, "associatedconstant.{}", name),
283 UrlFragment::AssociatedType(name) => write!(f, "associatedtype.{}", name),
284 UrlFragment::StructField(name) => write!(f, "structfield.{}", name),
285 UrlFragment::Variant(name) => write!(f, "variant.{}", name),
286 UrlFragment::VariantField { variant, field } => {
287 write!(f, "variant.{}.field.{}", variant, field)
289 UrlFragment::UserWritten(raw) => write!(f, "{}", raw),
294 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
295 struct ResolutionInfo {
297 dis: Option<Disambiguator>,
299 extra_fragment: Option<UrlFragment>,
303 struct DiagnosticInfo<'a> {
307 link_range: Range<usize>,
310 #[derive(Clone, Debug, Hash)]
312 pub res: (Res, Option<UrlFragment>),
313 pub side_channel: Option<(DefKind, DefId)>,
316 struct LinkCollector<'a, 'tcx> {
317 cx: &'a mut DocContext<'tcx>,
318 /// A stack of modules used to decide what scope to resolve in.
320 /// The last module will be used if the parent scope of the current item is
323 /// This is used to store the kind of associated items,
324 /// because `clean` and the disambiguator code expect them to be different.
325 /// See the code for associated items on inherent impls for details.
326 kind_side_channel: Cell<Option<(DefKind, DefId)>>,
327 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
328 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
329 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
332 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
333 /// Given a full link, parse it as an [enum struct variant].
335 /// In particular, this will return an error whenever there aren't three
336 /// full path segments left in the link.
338 /// [enum struct variant]: hir::VariantData::Struct
341 path_str: &'path str,
343 ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'path>> {
344 let tcx = self.cx.tcx;
345 let no_res = || ResolutionFailure::NotResolved {
348 unresolved: path_str.into(),
351 debug!("looking for enum variant {}", path_str);
352 let mut split = path_str.rsplitn(3, "::");
353 let variant_field_name = split
355 .map(|f| Symbol::intern(f))
356 .expect("fold_item should ensure link is non-empty");
358 // we're not sure this is a variant at all, so use the full string
359 // If there's no second component, the link looks like `[path]`.
360 // So there's no partial res and we should say the whole link failed to resolve.
361 split.next().map(|f| Symbol::intern(f)).ok_or_else(no_res)?;
364 .map(|f| f.to_owned())
365 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
366 // So there's no partial res.
367 .ok_or_else(no_res)?;
370 .enter_resolver(|resolver| {
371 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
373 .and_then(|(_, res)| res.try_into())
374 .map_err(|()| no_res())?;
377 Res::Def(DefKind::Enum, did) => {
381 .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
382 .any(|item| item.ident.name == variant_name)
384 // This is just to let `fold_item` know that this shouldn't be considered;
385 // it's a bug for the error to make it to the user
386 return Err(ResolutionFailure::Dummy.into());
388 match tcx.type_of(did).kind() {
389 ty::Adt(def, _) if def.is_enum() => {
390 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
393 Some(UrlFragment::VariantField {
394 variant: variant_name,
395 field: variant_field_name,
399 Err(ResolutionFailure::NotResolved {
401 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
402 unresolved: variant_field_name.to_string().into(),
410 _ => Err(ResolutionFailure::NotResolved {
412 partial_res: Some(ty_res),
413 unresolved: variant_name.to_string().into(),
419 /// Given a primitive type, try to resolve an associated item.
420 fn resolve_primitive_associated_item(
422 prim_ty: PrimitiveType,
425 ) -> Option<(Res, UrlFragment, Option<(DefKind, DefId)>)> {
426 let tcx = self.cx.tcx;
428 prim_ty.impls(tcx).into_iter().find_map(|&impl_| {
429 tcx.associated_items(impl_)
430 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
432 let kind = item.kind;
433 let fragment = UrlFragment::from_assoc_item(item_name, kind, false);
434 (Res::Primitive(prim_ty), fragment, Some((kind.as_def_kind(), item.def_id)))
439 /// Resolves a string as a macro.
441 /// FIXME(jynelson): Can this be unified with `resolve()`?
446 ) -> Result<Res, ResolutionFailure<'a>> {
447 let path = ast::Path::from_ident(Ident::from_str(path_str));
448 self.cx.enter_resolver(|resolver| {
449 // FIXME(jynelson): does this really need 3 separate lookups?
450 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
453 &ParentScope::module(resolver.graph_root(), resolver),
457 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
458 return Ok(res.try_into().unwrap());
461 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
462 return Ok(res.try_into().unwrap());
464 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
465 if let Ok((_, res)) =
466 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
468 // don't resolve builtins like `#[derive]`
469 if let Ok(res) = res.try_into() {
473 Err(ResolutionFailure::NotResolved {
476 unresolved: path_str.into(),
481 /// Convenience wrapper around `resolve_str_path_error`.
483 /// This also handles resolving `true` and `false` as booleans.
484 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
485 /// Associated items will never be resolved by this function.
486 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
487 let result = self.cx.enter_resolver(|resolver| {
489 .resolve_str_path_error(DUMMY_SP, path_str, ns, module_id)
490 .and_then(|(_, res)| res.try_into())
492 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
494 // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
496 Err(()) => resolve_primitive(path_str, ns),
497 Ok(res) => Some(res),
501 /// Resolves a string as a path within a particular namespace. Returns an
502 /// optional URL fragment in the case of variants and methods.
505 path_str: &'path str,
508 extra_fragment: &Option<UrlFragment>,
509 ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'path>> {
510 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
512 // FIXME(#76467): make this fallthrough to lookup the associated
513 // item a separate function.
514 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
515 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
516 Res::Def(DefKind::Variant, _) => {
517 return handle_variant(self.cx, res, extra_fragment);
519 // Not a trait item; just return what we found.
520 _ => return Ok((res, extra_fragment.clone())),
524 // Try looking for methods and associated items.
525 let mut split = path_str.rsplitn(2, "::");
526 // NB: `split`'s first element is always defined, even if the delimiter was not present.
527 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
528 let item_str = split.next().unwrap();
529 let item_name = Symbol::intern(item_str);
530 let path_root = split
532 .map(|f| f.to_owned())
533 // If there's no `::`, it's not an associated item.
534 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
536 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
537 ResolutionFailure::NotResolved {
540 unresolved: item_str.into(),
544 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
545 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
546 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
548 resolve_primitive(&path_root, TypeNS)
549 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
551 let (res, fragment, side_channel) =
552 self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
553 let result = if extra_fragment.is_some() {
554 // NOTE: can never be a primitive since `side_channel.is_none()` only when `res`
555 // is a trait (and the side channel DefId is always an associated item).
556 let diag_res = side_channel.map_or(res, |(k, r)| Res::Def(k, r));
557 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(diag_res)))
559 // HACK(jynelson): `clean` expects the type, not the associated item
560 // but the disambiguator logic expects the associated item.
561 // Store the kind in a side channel so that only the disambiguator logic looks at it.
562 if let Some((kind, id)) = side_channel {
563 self.kind_side_channel.set(Some((kind, id)));
565 Ok((res, Some(fragment)))
570 if ns == Namespace::ValueNS {
571 self.variant_field(path_str, module_id)
573 Err(ResolutionFailure::NotResolved {
576 unresolved: path_root.into(),
583 /// Convert a DefId to a Res, where possible.
585 /// This is used for resolving type aliases.
586 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
587 use PrimitiveType::*;
588 Some(match *self.cx.tcx.type_of(ty_id).kind() {
589 ty::Bool => Res::Primitive(Bool),
590 ty::Char => Res::Primitive(Char),
591 ty::Int(ity) => Res::Primitive(ity.into()),
592 ty::Uint(uty) => Res::Primitive(uty.into()),
593 ty::Float(fty) => Res::Primitive(fty.into()),
594 ty::Str => Res::Primitive(Str),
595 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
596 ty::Tuple(_) => Res::Primitive(Tuple),
597 ty::Array(..) => Res::Primitive(Array),
598 ty::Slice(_) => Res::Primitive(Slice),
599 ty::RawPtr(_) => Res::Primitive(RawPointer),
600 ty::Ref(..) => Res::Primitive(Reference),
601 ty::FnDef(..) => panic!("type alias to a function definition"),
602 ty::FnPtr(_) => Res::Primitive(Fn),
603 ty::Never => Res::Primitive(Never),
604 ty::Adt(&ty::AdtDef { did, .. }, _) | ty::Foreign(did) => {
605 Res::Def(self.cx.tcx.def_kind(did), did)
610 | ty::GeneratorWitness(_)
617 | ty::Error(_) => return None,
622 /// - None if no associated item was found
623 /// - Some((_, _, Some(_))) if an item was found and should go through a side channel
624 /// - Some((_, _, None)) otherwise
625 fn resolve_associated_item(
631 ) -> Option<(Res, UrlFragment, Option<(DefKind, DefId)>)> {
632 let tcx = self.cx.tcx;
635 Res::Primitive(prim) => self.resolve_primitive_associated_item(prim, ns, item_name),
636 Res::Def(DefKind::TyAlias, did) => {
637 // Resolve the link on the type the alias points to.
638 // FIXME: if the associated item is defined directly on the type alias,
639 // it will show up on its documentation page, we should link there instead.
640 let res = self.def_id_to_res(did)?;
641 self.resolve_associated_item(res, item_name, ns, module_id)
644 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy,
647 debug!("looking for associated item named {} for item {:?}", item_name, did);
648 // Checks if item_name belongs to `impl SomeItem`
653 tcx.associated_items(imp).find_by_name_and_namespace(
655 Ident::with_dummy_span(item_name),
661 // There should only ever be one associated item that matches from any inherent impl
663 // Check if item_name belongs to `impl SomeTrait for SomeItem`
664 // FIXME(#74563): This gives precedence to `impl SomeItem`:
665 // Although having both would be ambiguous, use impl version for compatibility's sake.
666 // To handle that properly resolve() would have to support
667 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
670 resolve_associated_trait_item(did, module_id, item_name, ns, self.cx);
671 debug!("got associated item {:?}", item);
675 if let Some(item) = assoc_item {
676 let kind = item.kind;
677 let fragment = UrlFragment::from_assoc_item(item_name, kind, false);
678 // HACK(jynelson): `clean` expects the type, not the associated item
679 // but the disambiguator logic expects the associated item.
680 // Store the kind in a side channel so that only the disambiguator logic looks at it.
681 return Some((root_res, fragment, Some((kind.as_def_kind(), item.def_id))));
684 if ns != Namespace::ValueNS {
687 debug!("looking for variants or fields named {} for {:?}", item_name, did);
688 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
689 // NOTE: it's different from variant_field because it resolves fields and variants,
690 // not variant fields (2 path segments, not 3).
691 let def = match tcx.type_of(did).kind() {
692 ty::Adt(def, _) => def,
695 let field = if def.is_enum() {
696 def.all_fields().find(|item| item.ident.name == item_name)
698 def.non_enum_variant().fields.iter().find(|item| item.ident.name == item_name)
700 let kind = if def.is_enum() { DefKind::Variant } else { DefKind::Field };
701 let fragment = if def.is_enum() {
702 // FIXME: how can the field be a variant?
703 UrlFragment::Variant(field.ident.name)
705 UrlFragment::StructField(field.ident.name)
707 Some((root_res, fragment, Some((kind, field.did))))
709 Res::Def(DefKind::Trait, did) => tcx
710 .associated_items(did)
711 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
713 let fragment = UrlFragment::from_assoc_item(
716 !item.defaultness.has_value(),
718 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
719 (res, fragment, None)
725 /// Used for reporting better errors.
727 /// Returns whether the link resolved 'fully' in another namespace.
728 /// 'fully' here means that all parts of the link resolved, not just some path segments.
729 /// This returns the `Res` even if it was erroneous for some reason
730 /// (such as having invalid URL fragments or being in the wrong namespace).
736 extra_fragment: &Option<UrlFragment>,
738 // resolve() can't be used for macro namespace
739 let result = match ns {
740 Namespace::MacroNS => self.resolve_macro(path_str, module_id).map_err(ErrorKind::from),
741 Namespace::TypeNS | Namespace::ValueNS => {
742 self.resolve(path_str, ns, module_id, extra_fragment).map(|(res, _)| res)
746 let res = match result {
747 Ok(res) => Some(res),
748 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
749 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
750 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
752 self.kind_side_channel.take().map(|(kind, id)| Res::Def(kind, id)).or(res)
756 /// Look to see if a resolved item has an associated item named `item_name`.
758 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
759 /// find `std::error::Error::source` and return
760 /// `<io::Error as error::Error>::source`.
761 fn resolve_associated_trait_item(
766 cx: &mut DocContext<'_>,
767 ) -> Option<ty::AssocItem> {
768 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
769 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
770 // meantime, just don't look for these blanket impls.
772 // Next consider explicit impls: `impl MyTrait for MyType`
773 // Give precedence to inherent impls.
774 let traits = traits_implemented_by(cx, did, module);
775 debug!("considering traits {:?}", traits);
776 let mut candidates = traits.iter().filter_map(|&trait_| {
777 cx.tcx.associated_items(trait_).find_by_name_and_namespace(
779 Ident::with_dummy_span(item_name),
784 // FIXME(#74563): warn about ambiguity
785 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
786 candidates.next().copied()
789 /// Given a type, return all traits in scope in `module` implemented by that type.
791 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
792 /// So it is not stable to serialize cross-crate.
793 fn traits_implemented_by(cx: &mut DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
794 let mut resolver = cx.resolver.borrow_mut();
795 let in_scope_traits = cx.module_trait_cache.entry(module).or_insert_with(|| {
796 resolver.access(|resolver| {
797 let parent_scope = &ParentScope::module(resolver.expect_module(module), resolver);
799 .traits_in_scope(None, parent_scope, SyntaxContext::root(), None)
801 .map(|candidate| candidate.def_id)
807 let ty = tcx.type_of(type_);
808 let iter = in_scope_traits.iter().flat_map(|&trait_| {
809 trace!("considering explicit impl for trait {:?}", trait_);
811 // Look at each trait implementation to see if it's an impl for `did`
812 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
813 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
814 // Check if these are the same type.
815 let impl_type = trait_ref.self_ty();
817 "comparing type {} with kind {:?} against type {:?}",
822 // Fast path: if this is a primitive simple `==` will work
823 let saw_impl = impl_type == ty
824 || match impl_type.kind() {
825 // Check if these are the same def_id
827 debug!("adt def_id: {:?}", def.did);
830 ty::Foreign(def_id) => *def_id == type_,
834 if saw_impl { Some(trait_) } else { None }
840 /// Check for resolve collisions between a trait and its derive.
842 /// These are common and we should just resolve to the trait in that case.
843 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
847 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
848 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
854 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
855 fn visit_item(&mut self, item: &Item) {
856 use rustc_middle::ty::DefIdTree;
859 item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
860 if parent_node.is_some() {
861 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
864 // find item's parent to resolve `Self` in item's docs below
865 debug!("looking for the `Self` type");
866 let self_id = match item.def_id.as_def_id() {
869 if (matches!(self.cx.tcx.def_kind(did), DefKind::Field)
871 self.cx.tcx.def_kind(self.cx.tcx.parent(did).unwrap()),
875 self.cx.tcx.parent(did).and_then(|item_id| self.cx.tcx.parent(item_id))
879 self.cx.tcx.def_kind(did),
887 self.cx.tcx.parent(did)
889 Some(did) => match self.cx.tcx.parent(did) {
890 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
891 // Fixing this breaks `fn render_deref_methods`.
892 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
893 // regardless of what rustdoc wants to call it.
895 let parent_kind = self.cx.tcx.def_kind(parent);
896 Some(if parent_kind == DefKind::Impl { parent } else { did })
902 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
903 let self_name = self_id.and_then(|self_id| {
904 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
905 // using `ty.to_string()` (or any variant) has issues with raw idents
906 let ty = self.cx.tcx.type_of(self_id);
907 let name = match ty.kind() {
908 ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
909 other if other.is_primitive() => Some(ty.to_string()),
912 debug!("using type_of(): {:?}", name);
915 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
916 debug!("using item_name(): {:?}", name);
921 let inner_docs = item.inner_docs(self.cx.tcx);
923 if item.is_mod() && inner_docs {
924 self.mod_ids.push(item.def_id.expect_def_id());
927 // We want to resolve in the lexical scope of the documentation.
928 // In the presence of re-exports, this is not the same as the module of the item.
929 // Rather than merging all documentation into one, resolve it one attribute at a time
930 // so we know which module it came from.
931 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
932 debug!("combined_docs={}", doc);
934 let (krate, parent_node) = if let Some(id) = parent_module {
937 (item.def_id.krate(), parent_node)
939 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
940 // This is a degenerate case and it's not supported by rustdoc.
941 for md_link in markdown_links(&doc) {
942 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
943 if let Some(link) = link {
944 self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
951 self.mod_ids.push(item.def_id.expect_def_id());
954 self.visit_item_recur(item);
957 self.visit_item_recur(item)
962 enum PreprocessingError<'a> {
963 Anchor(AnchorFailure),
964 Disambiguator(Range<usize>, String),
965 Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
968 impl From<AnchorFailure> for PreprocessingError<'_> {
969 fn from(err: AnchorFailure) -> Self {
974 struct PreprocessingInfo {
976 disambiguator: Option<Disambiguator>,
977 extra_fragment: Option<UrlFragment>,
982 /// - `None` if the link should be ignored.
983 /// - `Some(Err)` if the link should emit an error
984 /// - `Some(Ok)` if the link is valid
986 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
987 fn preprocess_link<'a>(
988 ori_link: &'a MarkdownLink,
989 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
990 // [] is mostly likely not supposed to be a link
991 if ori_link.link.is_empty() {
995 // Bail early for real links.
996 if ori_link.link.contains('/') {
1000 let stripped = ori_link.link.replace('`', "");
1001 let mut parts = stripped.split('#');
1003 let link = parts.next().unwrap();
1004 if link.trim().is_empty() {
1005 // This is an anchor to an element of the current page, nothing to do in here!
1008 let extra_fragment = parts.next();
1009 if parts.next().is_some() {
1010 // A valid link can't have multiple #'s
1011 return Some(Err(AnchorFailure::MultipleAnchors.into()));
1014 // Parse and strip the disambiguator from the link, if present.
1015 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1016 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1017 Ok(None) => (None, link.trim(), link.trim()),
1018 Err((err_msg, relative_range)) => {
1019 // Only report error if we would not have ignored this link. See issue #83859.
1020 if !should_ignore_link_with_disambiguators(link) {
1021 let no_backticks_range = range_between_backticks(ori_link);
1022 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1023 ..(no_backticks_range.start + relative_range.end);
1024 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1031 if should_ignore_link(path_str) {
1035 // Strip generics from the path.
1036 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1037 match strip_generics_from_path(path_str) {
1040 debug!("link has malformed generics: {}", path_str);
1041 return Some(Err(PreprocessingError::Resolution(
1043 path_str.to_owned(),
1052 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1053 assert!(!path_str.contains(['<', '>'].as_slice()));
1055 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1056 if path_str.contains(' ') {
1060 Some(Ok(PreprocessingInfo {
1063 extra_fragment: extra_fragment.map(|frag| UrlFragment::UserWritten(frag.to_owned())),
1064 link_text: link_text.to_owned(),
1068 impl LinkCollector<'_, '_> {
1069 /// This is the entry point for resolving an intra-doc link.
1071 /// FIXME(jynelson): this is way too many arguments
1076 self_name: &Option<String>,
1077 parent_node: Option<DefId>,
1079 ori_link: MarkdownLink,
1080 ) -> Option<ItemLink> {
1081 trace!("considering link '{}'", ori_link.link);
1083 let diag_info = DiagnosticInfo {
1086 ori_link: &ori_link.link,
1087 link_range: ori_link.range.clone(),
1090 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1091 match preprocess_link(&ori_link)? {
1095 PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1096 PreprocessingError::Disambiguator(range, msg) => {
1097 disambiguator_error(self.cx, diag_info, range, &msg)
1099 PreprocessingError::Resolution(err, path_str, disambiguator) => {
1112 let mut path_str = &*path_str;
1114 let inner_docs = item.inner_docs(self.cx.tcx);
1116 // In order to correctly resolve intra-doc links we need to
1117 // pick a base AST node to work from. If the documentation for
1118 // this module came from an inner comment (//!) then we anchor
1119 // our name resolution *inside* the module. If, on the other
1120 // hand it was an outer comment (///) then we anchor the name
1121 // resolution in the parent module on the basis that the names
1122 // used are more likely to be intended to be parent names. For
1123 // this, we set base_node to None for inner comments since
1124 // we've already pushed this node onto the resolution stack but
1125 // for outer comments we explicitly try and resolve against the
1126 // parent_node first.
1128 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1130 let mut module_id = if let Some(id) = base_node {
1134 debug!("attempting to resolve item without parent module: {}", path_str);
1140 smallvec![ResolutionFailure::NoParentItem],
1146 // replace `Self` with suitable item's parent name
1147 let is_lone_self = path_str == "Self";
1148 let is_lone_crate = path_str == "crate";
1149 if path_str.starts_with("Self::") || is_lone_self {
1150 if let Some(ref name) = self_name {
1154 resolved_self = format!("{}::{}", name, &path_str[6..]);
1155 path_str = &resolved_self;
1158 } else if path_str.starts_with("crate::") || is_lone_crate {
1159 use rustc_span::def_id::CRATE_DEF_INDEX;
1161 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1162 // But rustdoc wants it to mean the crate this item was originally present in.
1163 // To work around this, remove it and resolve relative to the crate root instead.
1164 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1165 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1166 // FIXME(#78696): This doesn't always work.
1170 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1171 path_str = &resolved_self;
1173 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1176 let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1180 path_str: path_str.to_owned(),
1183 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1184 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1187 // Check for a primitive which might conflict with a module
1188 // Report the ambiguity and require that the user specify which one they meant.
1189 // FIXME: could there ever be a primitive not in the type namespace?
1192 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1193 ) && !matches!(res, Res::Primitive(_))
1195 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1197 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1200 // `[char]` when a `char` module is in scope
1201 let candidates = vec![res, prim];
1202 ambiguity_error(self.cx, diag_info, path_str, candidates);
1208 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1209 // The resolved item did not match the disambiguator; give a better error than 'not found'
1210 let msg = format!("incompatible link kind for `{}`", path_str);
1211 let callback = |diag: &mut DiagnosticBuilder<'_>, sp: Option<rustc_span::Span>| {
1213 "this link resolved to {} {}, which is not {} {}",
1216 specified.article(),
1219 if let Some(sp) = sp {
1220 diag.span_label(sp, ¬e);
1224 suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1226 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1229 let verify = |kind: DefKind, id: DefId| {
1230 let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id));
1231 debug!("intra-doc link to {} resolved to {:?} (id: {:?})", path_str, res, id);
1233 // Disallow e.g. linking to enums with `struct@`
1234 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1235 match (kind, disambiguator) {
1236 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1237 // NOTE: this allows 'method' to mean both normal functions and associated functions
1238 // This can't cause ambiguity because both are in the same namespace.
1239 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1240 // These are namespaces; allow anything in the namespace to match
1241 | (_, Some(Disambiguator::Namespace(_)))
1242 // If no disambiguator given, allow anything
1244 // All of these are valid, so do nothing
1246 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1247 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1248 report_mismatch(specified, Disambiguator::Kind(kind));
1253 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1254 if let Some((src_id, dst_id)) = id
1256 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1257 // would presumably panic if a fake `DefIndex` were passed.
1258 .and_then(|dst_id| {
1259 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1262 if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1263 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1265 privacy_error(self.cx, &diag_info, path_str);
1273 Res::Primitive(prim) => {
1274 if let Some((kind, id)) = self.kind_side_channel.take() {
1275 // We're actually resolving an associated item of a primitive, so we need to
1276 // verify the disambiguator (if any) matches the type of the associated item.
1277 // This case should really follow the same flow as the `Res::Def` branch below,
1278 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1279 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1280 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1281 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1282 // for discussion on the matter.
1285 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1286 // However I'm not sure how to check that across crates.
1287 if prim == PrimitiveType::RawPointer
1288 && item.def_id.is_local()
1289 && !self.cx.tcx.features().intra_doc_pointers
1291 let span = super::source_span_for_markdown_range(
1297 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1299 rustc_session::parse::feature_err(
1300 &self.cx.tcx.sess.parse_sess,
1301 sym::intra_doc_pointers,
1303 "linking to associated items of raw pointers is experimental",
1305 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1309 match disambiguator {
1310 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1312 report_mismatch(other, Disambiguator::Primitive);
1319 link: ori_link.link,
1321 did: res.def_id(self.cx.tcx),
1325 Res::Def(kind, id) => {
1327 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1328 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1333 fn resolve_with_disambiguator_cached(
1335 key: ResolutionInfo,
1336 diag: DiagnosticInfo<'_>,
1337 cache_resolution_failure: bool,
1338 ) -> Option<(Res, Option<UrlFragment>)> {
1339 // Try to look up both the result and the corresponding side channel value
1340 if let Some(ref cached) = self.visited_links.get(&key) {
1343 self.kind_side_channel.set(cached.side_channel);
1344 return Some(cached.res.clone());
1346 None if cache_resolution_failure => return None,
1348 // Although we hit the cache and found a resolution error, this link isn't
1349 // supposed to cache those. Run link resolution again to emit the expected
1350 // resolution error.
1355 let res = self.resolve_with_disambiguator(&key, diag);
1357 // Cache only if resolved successfully - don't silence duplicate errors
1358 if let Some(res) = res {
1359 // Store result for the actual namespace
1360 self.visited_links.insert(
1364 side_channel: self.kind_side_channel.clone().into_inner(),
1370 if cache_resolution_failure {
1371 // For reference-style links we only want to report one resolution error
1372 // so let's cache them as well.
1373 self.visited_links.insert(key, None);
1380 /// After parsing the disambiguator, resolve the main part of the link.
1381 // FIXME(jynelson): wow this is just so much
1382 fn resolve_with_disambiguator(
1384 key: &ResolutionInfo,
1385 diag: DiagnosticInfo<'_>,
1386 ) -> Option<(Res, Option<UrlFragment>)> {
1387 let disambiguator = key.dis;
1388 let path_str = &key.path_str;
1389 let base_node = key.module_id;
1390 let extra_fragment = &key.extra_fragment;
1392 match disambiguator.map(Disambiguator::ns) {
1393 Some(expected_ns @ (ValueNS | TypeNS)) => {
1394 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1395 Ok(res) => Some(res),
1396 Err(ErrorKind::Resolve(box mut kind)) => {
1397 // We only looked in one namespace. Try to give a better error if possible.
1398 if kind.full_res().is_none() {
1399 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1400 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1401 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1402 for new_ns in [other_ns, MacroNS] {
1404 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1406 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1411 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1412 // This could just be a normal link or a broken link
1413 // we could potentially check if something is
1414 // "intra-doc-link-like" and warn in that case.
1417 Err(ErrorKind::AnchorFailure(msg)) => {
1418 anchor_failure(self.cx, diag, msg);
1425 let mut candidates = PerNS {
1427 .resolve_macro(path_str, base_node)
1428 .map(|res| (res, extra_fragment.clone())),
1429 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1431 debug!("got res in TypeNS: {:?}", res);
1434 Err(ErrorKind::AnchorFailure(msg)) => {
1435 anchor_failure(self.cx, diag, msg);
1438 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1440 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1442 Err(ErrorKind::AnchorFailure(msg)) => {
1443 anchor_failure(self.cx, diag, msg);
1446 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1448 .and_then(|(res, fragment)| {
1449 // Constructors are picked up in the type namespace.
1451 Res::Def(DefKind::Ctor(..), _) => {
1452 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1455 match (fragment, extra_fragment.clone()) {
1456 (Some(fragment), Some(_)) => {
1457 // Shouldn't happen but who knows?
1458 Ok((res, Some(fragment)))
1460 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1467 let len = candidates.iter().filter(|res| res.is_ok()).count();
1475 candidates.into_iter().filter_map(|res| res.err()).collect(),
1477 // this could just be a normal link
1482 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1483 } else if len == 2 && is_derive_trait_collision(&candidates) {
1484 Some(candidates.type_ns.unwrap())
1486 if is_derive_trait_collision(&candidates) {
1487 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1489 // If we're reporting an ambiguity, don't mention the namespaces that failed
1490 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1491 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1496 match self.resolve_macro(path_str, base_node) {
1497 Ok(res) => Some((res, extra_fragment.clone())),
1499 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1500 for ns in [TypeNS, ValueNS] {
1502 self.check_full_res(ns, path_str, base_node, extra_fragment)
1505 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1509 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1518 /// Get the section of a link between the backticks,
1519 /// or the whole link if there aren't any backticks.
1527 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1528 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1529 let before_second_backtick_group = ori_link
1532 .skip(after_first_backtick_group)
1533 .position(|b| b == b'`')
1534 .unwrap_or(ori_link.link.len());
1535 (ori_link.range.start + after_first_backtick_group)
1536 ..(ori_link.range.start + before_second_backtick_group)
1539 /// Returns true if we should ignore `link` due to it being unlikely
1540 /// that it is an intra-doc link. `link` should still have disambiguators
1541 /// if there were any.
1543 /// The difference between this and [`should_ignore_link()`] is that this
1544 /// check should only be used on links that still have disambiguators.
1545 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1546 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1549 /// Returns true if we should ignore `path_str` due to it being unlikely
1550 /// that it is an intra-doc link.
1551 fn should_ignore_link(path_str: &str) -> bool {
1552 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1555 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1556 /// Disambiguators for a link.
1557 enum Disambiguator {
1560 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1562 /// `struct@` or `f()`
1565 Namespace(Namespace),
1568 impl Disambiguator {
1569 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1571 /// This returns `Ok(Some(...))` if a disambiguator was found,
1572 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1573 /// if there was a problem with the disambiguator.
1574 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1575 use Disambiguator::{Kind, Namespace as NS, Primitive};
1577 if let Some(idx) = link.find('@') {
1578 let (prefix, rest) = link.split_at(idx);
1579 let d = match prefix {
1580 "struct" => Kind(DefKind::Struct),
1581 "enum" => Kind(DefKind::Enum),
1582 "trait" => Kind(DefKind::Trait),
1583 "union" => Kind(DefKind::Union),
1584 "module" | "mod" => Kind(DefKind::Mod),
1585 "const" | "constant" => Kind(DefKind::Const),
1586 "static" => Kind(DefKind::Static),
1587 "function" | "fn" | "method" => Kind(DefKind::Fn),
1588 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1589 "type" => NS(Namespace::TypeNS),
1590 "value" => NS(Namespace::ValueNS),
1591 "macro" => NS(Namespace::MacroNS),
1592 "prim" | "primitive" => Primitive,
1593 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1595 Ok(Some((d, &rest[1..], &rest[1..])))
1598 ("!()", DefKind::Macro(MacroKind::Bang)),
1599 ("!{}", DefKind::Macro(MacroKind::Bang)),
1600 ("![]", DefKind::Macro(MacroKind::Bang)),
1601 ("()", DefKind::Fn),
1602 ("!", DefKind::Macro(MacroKind::Bang)),
1604 for (suffix, kind) in suffixes {
1605 if let Some(path_str) = link.strip_suffix(suffix) {
1606 // Avoid turning `!` or `()` into an empty string
1607 if !path_str.is_empty() {
1608 return Ok(Some((Kind(kind), path_str, link)));
1616 fn from_res(res: Res) -> Self {
1618 Res::Def(kind, _) => Disambiguator::Kind(kind),
1619 Res::Primitive(_) => Disambiguator::Primitive,
1623 /// Used for error reporting.
1624 fn suggestion(self) -> Suggestion {
1625 let kind = match self {
1626 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1627 Disambiguator::Kind(kind) => kind,
1628 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1630 if kind == DefKind::Macro(MacroKind::Bang) {
1631 return Suggestion::Macro;
1632 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1633 return Suggestion::Function;
1634 } else if kind == DefKind::Field {
1635 return Suggestion::RemoveDisambiguator;
1638 let prefix = match kind {
1639 DefKind::Struct => "struct",
1640 DefKind::Enum => "enum",
1641 DefKind::Trait => "trait",
1642 DefKind::Union => "union",
1643 DefKind::Mod => "mod",
1644 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1647 DefKind::Static => "static",
1648 DefKind::Macro(MacroKind::Derive) => "derive",
1649 // Now handle things that don't have a specific disambiguator
1652 .expect("tried to calculate a disambiguator for a def without a namespace?")
1654 Namespace::TypeNS => "type",
1655 Namespace::ValueNS => "value",
1656 Namespace::MacroNS => "macro",
1660 Suggestion::Prefix(prefix)
1663 fn ns(self) -> Namespace {
1665 Self::Namespace(n) => n,
1667 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1669 Self::Primitive => TypeNS,
1673 fn article(self) -> &'static str {
1675 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1676 Self::Kind(k) => k.article(),
1677 Self::Primitive => "a",
1681 fn descr(self) -> &'static str {
1683 Self::Namespace(n) => n.descr(),
1684 // HACK(jynelson): by looking at the source I saw the DefId we pass
1685 // for `expected.descr()` doesn't matter, since it's not a crate
1686 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1687 Self::Primitive => "builtin type",
1692 /// A suggestion to show in a diagnostic.
1695 Prefix(&'static str),
1700 /// `foo` without any disambiguator
1701 RemoveDisambiguator,
1705 fn descr(&self) -> Cow<'static, str> {
1707 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1708 Self::Function => "add parentheses".into(),
1709 Self::Macro => "add an exclamation mark".into(),
1710 Self::RemoveDisambiguator => "remove the disambiguator".into(),
1714 fn as_help(&self, path_str: &str) -> String {
1715 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1717 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1718 Self::Function => format!("{}()", path_str),
1719 Self::Macro => format!("{}!", path_str),
1720 Self::RemoveDisambiguator => path_str.into(),
1728 sp: rustc_span::Span,
1729 ) -> Vec<(rustc_span::Span, String)> {
1730 let inner_sp = match ori_link.find('(') {
1731 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1734 let inner_sp = match ori_link.find('!') {
1735 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1738 let inner_sp = match ori_link.find('@') {
1739 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1743 Self::Prefix(prefix) => {
1744 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1745 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1746 if sp.hi() != inner_sp.hi() {
1747 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1752 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1753 if sp.lo() != inner_sp.lo() {
1754 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1759 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1760 if sp.lo() != inner_sp.lo() {
1761 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1765 Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1770 /// Reports a diagnostic for an intra-doc link.
1772 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1773 /// the entire documentation block is used for the lint. If a range is provided but the span
1774 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1776 /// The `decorate` callback is invoked in all cases to allow further customization of the
1777 /// diagnostic before emission. If the span of the link was able to be determined, the second
1778 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1780 fn report_diagnostic(
1782 lint: &'static Lint,
1784 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1785 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1787 let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1788 Some(hir_id) => hir_id,
1790 // If non-local, no need to check anything.
1791 info!("ignoring warning from parent crate: {}", msg);
1796 let sp = item.attr_span(tcx);
1798 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1799 let mut diag = lint.build(msg);
1802 super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1803 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1804 && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1806 sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1812 if let Some(sp) = span {
1815 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1818 // last_new_line_offset
1819 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1820 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1822 // Print the line containing the `link_range` and manually mark it with '^'s.
1824 "the link appears in this line:\n\n{line}\n\
1825 {indicator: <before$}{indicator:^<found$}",
1828 before = link_range.start - last_new_line_offset,
1829 found = link_range.len(),
1833 decorate(&mut diag, span);
1839 /// Reports a link that failed to resolve.
1841 /// This also tries to resolve any intermediate path segments that weren't
1842 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1843 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1844 fn resolution_failure(
1845 collector: &mut LinkCollector<'_, '_>,
1846 diag_info: DiagnosticInfo<'_>,
1848 disambiguator: Option<Disambiguator>,
1849 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1851 let tcx = collector.cx.tcx;
1854 BROKEN_INTRA_DOC_LINKS,
1855 &format!("unresolved link to `{}`", path_str),
1858 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1859 let assoc_item_not_allowed = |res: Res| {
1860 let name = res.name(tcx);
1862 "`{}` is {} {}, not a module or type, and cannot have associated items",
1868 // ignore duplicates
1869 let mut variants_seen = SmallVec::<[_; 3]>::new();
1870 for mut failure in kinds {
1871 let variant = std::mem::discriminant(&failure);
1872 if variants_seen.contains(&variant) {
1875 variants_seen.push(variant);
1877 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1882 let module_id = *module_id;
1883 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1884 // FIXME: maybe use itertools `collect_tuple` instead?
1885 fn split(path: &str) -> Option<(&str, &str)> {
1886 let mut splitter = path.rsplitn(2, "::");
1887 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1890 // Check if _any_ parent of the path gets resolved.
1891 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1892 let mut name = path_str;
1894 let (start, end) = if let Some(x) = split(name) {
1897 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1898 if partial_res.is_none() {
1899 *unresolved = name.into();
1904 for ns in [TypeNS, ValueNS, MacroNS] {
1905 if let Some(res) = collector.check_full_res(ns, start, module_id, &None)
1907 debug!("found partial_res={:?}", res);
1908 *partial_res = Some(res);
1909 *unresolved = end.into();
1913 *unresolved = end.into();
1916 let last_found_module = match *partial_res {
1917 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1918 None => Some(module_id),
1921 // See if this was a module: `[path]` or `[std::io::nope]`
1922 if let Some(module) = last_found_module {
1923 let note = if partial_res.is_some() {
1924 // Part of the link resolved; e.g. `std::io::nonexistent`
1925 let module_name = tcx.item_name(module);
1926 format!("no item named `{}` in module `{}`", unresolved, module_name)
1928 // None of the link resolved; e.g. `Notimported`
1929 format!("no item named `{}` in scope", unresolved)
1931 if let Some(span) = sp {
1932 diag.span_label(span, ¬e);
1937 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1938 // Otherwise, the `[]` might be unrelated.
1939 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1940 if !path_str.contains("::") {
1941 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1947 // Otherwise, it must be an associated item or variant
1948 let res = partial_res.expect("None case was handled by `last_found_module`");
1949 let name = res.name(tcx);
1950 let kind = match res {
1951 Res::Def(kind, _) => Some(kind),
1952 Res::Primitive(_) => None,
1954 let path_description = if let Some(kind) = kind {
1956 Mod | ForeignMod => "inner item",
1957 Struct => "field or associated item",
1958 Enum | Union => "variant or associated item",
1976 let note = assoc_item_not_allowed(res);
1977 if let Some(span) = sp {
1978 diag.span_label(span, ¬e);
1984 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1985 | Static => "associated item",
1986 Impl | GlobalAsm => unreachable!("not a path"),
1992 "the {} `{}` has no {} named `{}`",
1995 disambiguator.map_or(path_description, |d| d.descr()),
1998 if let Some(span) = sp {
1999 diag.span_label(span, ¬e);
2006 let note = match failure {
2007 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2008 ResolutionFailure::Dummy => continue,
2009 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2010 if let Res::Def(kind, _) = res {
2011 let disambiguator = Disambiguator::Kind(kind);
2012 suggest_disambiguator(
2022 "this link resolves to {}, which is not in the {} namespace",
2027 ResolutionFailure::NoParentItem => {
2028 diag.level = rustc_errors::Level::Bug;
2029 "all intra-doc links should have a parent item".to_owned()
2031 ResolutionFailure::MalformedGenerics(variant) => match variant {
2032 MalformedGenerics::UnbalancedAngleBrackets => {
2033 String::from("unbalanced angle brackets")
2035 MalformedGenerics::MissingType => {
2036 String::from("missing type for generic parameters")
2038 MalformedGenerics::HasFullyQualifiedSyntax => {
2039 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2040 String::from("fully-qualified syntax is unsupported")
2042 MalformedGenerics::InvalidPathSeparator => {
2043 String::from("has invalid path separator")
2045 MalformedGenerics::TooManyAngleBrackets => {
2046 String::from("too many angle brackets")
2048 MalformedGenerics::EmptyAngleBrackets => {
2049 String::from("empty angle brackets")
2053 if let Some(span) = sp {
2054 diag.span_label(span, ¬e);
2063 /// Report an anchor failure.
2064 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2065 let (msg, anchor_idx) = match failure {
2066 AnchorFailure::MultipleAnchors => {
2067 (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2069 AnchorFailure::RustdocAnchorConflict(res) => (
2071 "`{}` contains an anchor, but links to {kind}s are already anchored",
2079 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2080 if let Some(mut sp) = sp {
2081 if let Some((fragment_offset, _)) =
2082 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2084 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2086 diag.span_label(sp, "invalid anchor");
2088 if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2089 if let Some(sp) = sp {
2090 span_bug!(sp, "anchors should be allowed now");
2092 bug!("anchors should be allowed now");
2098 /// Report an error in the link disambiguator.
2099 fn disambiguator_error(
2100 cx: &DocContext<'_>,
2101 mut diag_info: DiagnosticInfo<'_>,
2102 disambiguator_range: Range<usize>,
2105 diag_info.link_range = disambiguator_range;
2106 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2108 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2109 crate::DOC_RUST_LANG_ORG_CHANNEL
2115 /// Report an ambiguity error, where there were multiple possible resolutions.
2117 cx: &DocContext<'_>,
2118 diag_info: DiagnosticInfo<'_>,
2120 candidates: Vec<Res>,
2122 let mut msg = format!("`{}` is ", path_str);
2124 match candidates.as_slice() {
2125 [first_def, second_def] => {
2127 "both {} {} and {} {}",
2128 first_def.article(),
2130 second_def.article(),
2135 let mut candidates = candidates.iter().peekable();
2136 while let Some(res) = candidates.next() {
2137 if candidates.peek().is_some() {
2138 msg += &format!("{} {}, ", res.article(), res.descr());
2140 msg += &format!("and {} {}", res.article(), res.descr());
2146 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2147 if let Some(sp) = sp {
2148 diag.span_label(sp, "ambiguous link");
2150 diag.note("ambiguous link");
2153 for res in candidates {
2154 let disambiguator = Disambiguator::from_res(res);
2155 suggest_disambiguator(disambiguator, diag, path_str, diag_info.ori_link, sp);
2160 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2162 fn suggest_disambiguator(
2163 disambiguator: Disambiguator,
2164 diag: &mut DiagnosticBuilder<'_>,
2167 sp: Option<rustc_span::Span>,
2169 let suggestion = disambiguator.suggestion();
2170 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
2172 if let Some(sp) = sp {
2173 let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2174 if spans.len() > 1 {
2175 diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2177 let (sp, suggestion_text) = spans.pop().unwrap();
2178 diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2181 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2185 /// Report a link from a public item to a private one.
2186 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2188 let item_name = match diag_info.item.name {
2193 None => "<unknown>",
2196 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2198 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2199 if let Some(sp) = sp {
2200 diag.span_label(sp, "this item is private");
2203 let note_msg = if cx.render_options.document_private {
2204 "this link resolves only because you passed `--document-private-items`, but will break without"
2206 "this link will resolve properly if you pass `--document-private-items`"
2208 diag.note(note_msg);
2212 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2214 cx: &DocContext<'_>,
2216 extra_fragment: &Option<UrlFragment>,
2217 ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'static>> {
2218 use rustc_middle::ty::DefIdTree;
2220 if extra_fragment.is_some() {
2221 // NOTE: `res` can never be a primitive since this function is only called when `tcx.def_kind(res) == DefKind::Variant`.
2222 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2225 .parent(res.def_id(cx.tcx))
2227 let parent_def = Res::Def(DefKind::Enum, parent);
2228 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2229 (parent_def, Some(UrlFragment::Variant(variant.ident.name)))
2231 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2234 /// Resolve a primitive type or value.
2235 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2239 use PrimitiveType::*;
2240 let prim = match path_str {
2256 "bool" | "true" | "false" => Bool,
2257 "str" | "&str" => Str,
2258 // See #80181 for why these don't have symbols associated.
2263 "pointer" | "*const" | "*mut" => RawPointer,
2264 "reference" | "&" | "&mut" => Reference,
2266 "never" | "!" => Never,
2269 debug!("resolved primitives {:?}", prim);
2270 Some(Res::Primitive(prim))
2273 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2274 let mut stripped_segments = vec![];
2275 let mut path = path_str.chars().peekable();
2276 let mut segment = Vec::new();
2278 while let Some(chr) = path.next() {
2281 if path.next_if_eq(&':').is_some() {
2282 let stripped_segment =
2283 strip_generics_from_path_segment(mem::take(&mut segment))?;
2284 if !stripped_segment.is_empty() {
2285 stripped_segments.push(stripped_segment);
2288 return Err(ResolutionFailure::MalformedGenerics(
2289 MalformedGenerics::InvalidPathSeparator,
2298 return Err(ResolutionFailure::MalformedGenerics(
2299 MalformedGenerics::TooManyAngleBrackets,
2303 return Err(ResolutionFailure::MalformedGenerics(
2304 MalformedGenerics::EmptyAngleBrackets,
2310 while let Some(chr) = path.next_if(|c| *c != '>') {
2317 _ => segment.push(chr),
2319 trace!("raw segment: {:?}", segment);
2322 if !segment.is_empty() {
2323 let stripped_segment = strip_generics_from_path_segment(segment)?;
2324 if !stripped_segment.is_empty() {
2325 stripped_segments.push(stripped_segment);
2329 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2331 let stripped_path = stripped_segments.join("::");
2333 if !stripped_path.is_empty() {
2336 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2340 fn strip_generics_from_path_segment(
2342 ) -> Result<String, ResolutionFailure<'static>> {
2343 let mut stripped_segment = String::new();
2344 let mut param_depth = 0;
2346 let mut latest_generics_chunk = String::new();
2351 latest_generics_chunk.clear();
2352 } else if c == '>' {
2354 if latest_generics_chunk.contains(" as ") {
2355 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2356 // Give a helpful error message instead of completely ignoring the angle brackets.
2357 return Err(ResolutionFailure::MalformedGenerics(
2358 MalformedGenerics::HasFullyQualifiedSyntax,
2362 if param_depth == 0 {
2363 stripped_segment.push(c);
2365 latest_generics_chunk.push(c);
2370 if param_depth == 0 {
2371 Ok(stripped_segment)
2373 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2374 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))