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 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
41 name: "collect-intra-doc-links",
42 run: collect_intra_doc_links,
43 description: "resolves intra-doc links",
46 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
50 kind_side_channel: Cell::new(None),
51 visited_links: FxHashMap::default(),
56 /// Top-level errors emitted by this pass.
58 Resolve(Box<ResolutionFailure<'a>>),
59 AnchorFailure(AnchorFailure),
62 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
63 fn from(err: ResolutionFailure<'a>) -> Self {
64 ErrorKind::Resolve(box err)
68 #[derive(Copy, Clone, Debug, Hash)]
71 Primitive(PrimitiveType),
74 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
77 fn descr(self) -> &'static str {
79 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
80 Res::Primitive(_) => "builtin type",
84 fn article(self) -> &'static str {
86 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
87 Res::Primitive(_) => "a",
91 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
93 Res::Def(_, id) => tcx.item_name(id),
94 Res::Primitive(prim) => prim.as_sym(),
98 fn def_id(self) -> DefId {
99 self.opt_def_id().expect("called def_id() on a primitive")
102 fn opt_def_id(self) -> Option<DefId> {
104 Res::Def(_, id) => Some(id),
105 Res::Primitive(_) => None,
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. For primitives, though,
238 /// rustdoc uses the anchor as a side channel to know which page to link to;
239 /// it doesn't show up in the generated link. Ideally, rustdoc would remove
240 /// this limitation, allowing you to link to subheaders on primitives.
241 RustdocAnchorConflict(Res),
244 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
245 struct ResolutionInfo {
247 dis: Option<Disambiguator>,
249 extra_fragment: Option<String>,
253 struct DiagnosticInfo<'a> {
257 link_range: Range<usize>,
260 #[derive(Clone, Debug, Hash)]
262 pub res: (Res, Option<String>),
263 pub side_channel: Option<(DefKind, DefId)>,
266 struct LinkCollector<'a, 'tcx> {
267 cx: &'a mut DocContext<'tcx>,
268 /// A stack of modules used to decide what scope to resolve in.
270 /// The last module will be used if the parent scope of the current item is
273 /// This is used to store the kind of associated items,
274 /// because `clean` and the disambiguator code expect them to be different.
275 /// See the code for associated items on inherent impls for details.
276 kind_side_channel: Cell<Option<(DefKind, DefId)>>,
277 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
278 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
279 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
282 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
283 /// Given a full link, parse it as an [enum struct variant].
285 /// In particular, this will return an error whenever there aren't three
286 /// full path segments left in the link.
288 /// [enum struct variant]: hir::VariantData::Struct
291 path_str: &'path str,
293 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
294 let tcx = self.cx.tcx;
295 let no_res = || ResolutionFailure::NotResolved {
296 module_id: module_id.into(),
298 unresolved: path_str.into(),
301 debug!("looking for enum variant {}", path_str);
302 let mut split = path_str.rsplitn(3, "::");
303 let (variant_field_str, variant_field_name) = split
305 .map(|f| (f, Symbol::intern(f)))
306 .expect("fold_item should ensure link is non-empty");
307 let (variant_str, variant_name) =
308 // we're not sure this is a variant at all, so use the full string
309 // If there's no second component, the link looks like `[path]`.
310 // So there's no partial res and we should say the whole link failed to resolve.
311 split.next().map(|f| (f, Symbol::intern(f))).ok_or_else(no_res)?;
314 .map(|f| f.to_owned())
315 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
316 // So there's no partial res.
317 .ok_or_else(no_res)?;
320 .enter_resolver(|resolver| {
321 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
323 .and_then(|(_, res)| res.try_into())
324 .map_err(|()| no_res())?;
327 Res::Def(DefKind::Enum, did) => {
331 .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
332 .any(|item| item.ident.name == variant_name)
334 // This is just to let `fold_item` know that this shouldn't be considered;
335 // it's a bug for the error to make it to the user
336 return Err(ResolutionFailure::Dummy.into());
338 match tcx.type_of(did).kind() {
339 ty::Adt(def, _) if def.is_enum() => {
340 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
344 "variant.{}.field.{}",
345 variant_str, variant_field_name
349 Err(ResolutionFailure::NotResolved {
351 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
352 unresolved: variant_field_str.into(),
360 _ => Err(ResolutionFailure::NotResolved {
362 partial_res: Some(ty_res),
363 unresolved: variant_str.into(),
369 /// Given a primitive type, try to resolve an associated item.
370 fn resolve_primitive_associated_item(
372 prim_ty: PrimitiveType,
375 ) -> Option<(Res, String, Option<(DefKind, DefId)>)> {
376 let tcx = self.cx.tcx;
378 prim_ty.impls(tcx).into_iter().find_map(|&impl_| {
379 tcx.associated_items(impl_)
380 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
382 let kind = item.kind;
383 let out = match kind {
384 ty::AssocKind::Fn => "method",
385 ty::AssocKind::Const => "associatedconstant",
386 ty::AssocKind::Type => "associatedtype",
388 let fragment = format!("{}#{}.{}", prim_ty.as_sym(), out, item_name);
389 (Res::Primitive(prim_ty), fragment, Some((kind.as_def_kind(), item.def_id)))
394 /// Resolves a string as a macro.
396 /// FIXME(jynelson): Can this be unified with `resolve()`?
401 ) -> Result<Res, ResolutionFailure<'a>> {
402 let path = ast::Path::from_ident(Ident::from_str(path_str));
403 self.cx.enter_resolver(|resolver| {
404 // FIXME(jynelson): does this really need 3 separate lookups?
405 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
408 &ParentScope::module(resolver.graph_root(), resolver),
412 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
413 return Ok(res.try_into().unwrap());
416 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
417 return Ok(res.try_into().unwrap());
419 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
420 if let Ok((_, res)) =
421 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
423 // don't resolve builtins like `#[derive]`
424 if let Ok(res) = res.try_into() {
428 Err(ResolutionFailure::NotResolved {
431 unresolved: path_str.into(),
436 /// Convenience wrapper around `resolve_str_path_error`.
438 /// This also handles resolving `true` and `false` as booleans.
439 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
440 /// Associated items will never be resolved by this function.
441 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
442 let result = self.cx.enter_resolver(|resolver| {
444 .resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
445 .and_then(|(_, res)| res.try_into())
447 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
449 // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
451 Err(()) => resolve_primitive(path_str, ns),
452 Ok(res) => Some(res),
456 /// Resolves a string as a path within a particular namespace. Returns an
457 /// optional URL fragment in the case of variants and methods.
460 path_str: &'path str,
463 extra_fragment: &Option<String>,
464 ) -> Result<(Res, Option<String>), ErrorKind<'path>> {
465 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
467 // FIXME(#76467): make this fallthrough to lookup the associated
468 // item a separate function.
469 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
470 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
471 Res::Def(DefKind::Variant, _) => {
472 return handle_variant(self.cx, res, extra_fragment);
474 // Not a trait item; just return what we found.
475 Res::Primitive(ty) => {
476 if extra_fragment.is_some() {
477 return Err(ErrorKind::AnchorFailure(
478 AnchorFailure::RustdocAnchorConflict(res),
481 return Ok((res, Some(ty.as_sym().to_string())));
483 _ => return Ok((res, extra_fragment.clone())),
487 // Try looking for methods and associated items.
488 let mut split = path_str.rsplitn(2, "::");
489 // NB: `split`'s first element is always defined, even if the delimiter was not present.
490 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
491 let item_str = split.next().unwrap();
492 let item_name = Symbol::intern(item_str);
493 let path_root = split
495 .map(|f| f.to_owned())
496 // If there's no `::`, it's not an associated item.
497 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
499 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
500 ResolutionFailure::NotResolved {
503 unresolved: item_str.into(),
507 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
508 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
509 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
511 resolve_primitive(&path_root, TypeNS)
512 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
514 let (res, fragment, side_channel) =
515 self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
516 let result = if extra_fragment.is_some() {
517 let diag_res = side_channel.map_or(res, |(k, r)| Res::Def(k, r));
518 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(diag_res)))
520 // HACK(jynelson): `clean` expects the type, not the associated item
521 // but the disambiguator logic expects the associated item.
522 // Store the kind in a side channel so that only the disambiguator logic looks at it.
523 if let Some((kind, id)) = side_channel {
524 self.kind_side_channel.set(Some((kind, id.into())));
526 Ok((res, Some(fragment)))
531 if ns == Namespace::ValueNS {
532 self.variant_field(path_str, module_id)
534 Err(ResolutionFailure::NotResolved {
537 unresolved: path_root.into(),
544 /// Convert a DefId to a Res, where possible.
546 /// This is used for resolving type aliases.
547 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
548 use PrimitiveType::*;
549 Some(match *self.cx.tcx.type_of(ty_id).kind() {
550 ty::Bool => Res::Primitive(Bool),
551 ty::Char => Res::Primitive(Char),
552 ty::Int(ity) => Res::Primitive(ity.into()),
553 ty::Uint(uty) => Res::Primitive(uty.into()),
554 ty::Float(fty) => Res::Primitive(fty.into()),
555 ty::Str => Res::Primitive(Str),
556 ty::Tuple(ref tys) if tys.is_empty() => Res::Primitive(Unit),
557 ty::Tuple(_) => Res::Primitive(Tuple),
558 ty::Array(..) => Res::Primitive(Array),
559 ty::Slice(_) => Res::Primitive(Slice),
560 ty::RawPtr(_) => Res::Primitive(RawPointer),
561 ty::Ref(..) => Res::Primitive(Reference),
562 ty::FnDef(..) => panic!("type alias to a function definition"),
563 ty::FnPtr(_) => Res::Primitive(Fn),
564 ty::Never => Res::Primitive(Never),
565 ty::Adt(&ty::AdtDef { did, .. }, _) | ty::Foreign(did) => {
566 Res::Def(self.cx.tcx.def_kind(did), did)
571 | ty::GeneratorWitness(_)
578 | ty::Error(_) => return None,
583 /// - None if no associated item was found
584 /// - Some((_, _, Some(_))) if an item was found and should go through a side channel
585 /// - Some((_, _, None)) otherwise
586 fn resolve_associated_item(
592 ) -> Option<(Res, String, Option<(DefKind, DefId)>)> {
593 let tcx = self.cx.tcx;
596 Res::Primitive(prim) => self.resolve_primitive_associated_item(prim, ns, item_name),
597 Res::Def(DefKind::TyAlias, did) => {
598 // Resolve the link on the type the alias points to.
599 // FIXME: if the associated item is defined directly on the type alias,
600 // it will show up on its documentation page, we should link there instead.
601 let res = self.def_id_to_res(did)?;
602 self.resolve_associated_item(res, item_name, ns, module_id)
605 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy,
608 debug!("looking for associated item named {} for item {:?}", item_name, did);
609 // Checks if item_name belongs to `impl SomeItem`
614 tcx.associated_items(imp).find_by_name_and_namespace(
616 Ident::with_dummy_span(item_name),
621 .map(|item| (item.kind, item.def_id))
622 // There should only ever be one associated item that matches from any inherent impl
624 // Check if item_name belongs to `impl SomeTrait for SomeItem`
625 // FIXME(#74563): This gives precedence to `impl SomeItem`:
626 // Although having both would be ambiguous, use impl version for compatibility's sake.
627 // To handle that properly resolve() would have to support
628 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
631 resolve_associated_trait_item(did, module_id, item_name, ns, self.cx);
632 debug!("got associated item kind {:?}", kind);
636 if let Some((kind, id)) = assoc_item {
637 let out = match kind {
638 ty::AssocKind::Fn => "method",
639 ty::AssocKind::Const => "associatedconstant",
640 ty::AssocKind::Type => "associatedtype",
642 // HACK(jynelson): `clean` expects the type, not the associated item
643 // but the disambiguator logic expects the associated item.
644 // Store the kind in a side channel so that only the disambiguator logic looks at it.
647 format!("{}.{}", out, item_name),
648 Some((kind.as_def_kind(), id)),
652 if ns != Namespace::ValueNS {
655 debug!("looking for variants or fields named {} for {:?}", item_name, did);
656 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
657 // NOTE: it's different from variant_field because it resolves fields and variants,
658 // not variant fields (2 path segments, not 3).
659 let def = match tcx.type_of(did).kind() {
660 ty::Adt(def, _) => def,
663 let field = if def.is_enum() {
664 def.all_fields().find(|item| item.ident.name == item_name)
666 def.non_enum_variant().fields.iter().find(|item| item.ident.name == item_name)
668 let kind = if def.is_enum() { DefKind::Variant } else { DefKind::Field };
673 if def.is_enum() { "variant" } else { "structfield" },
676 Some((kind, field.did)),
679 Res::Def(DefKind::Trait, did) => tcx
680 .associated_items(did)
681 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
683 let kind = match item.kind {
684 ty::AssocKind::Const => "associatedconstant",
685 ty::AssocKind::Type => "associatedtype",
686 ty::AssocKind::Fn => {
687 if item.defaultness.has_value() {
695 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
696 (res, format!("{}.{}", kind, item_name), None)
702 /// Used for reporting better errors.
704 /// Returns whether the link resolved 'fully' in another namespace.
705 /// 'fully' here means that all parts of the link resolved, not just some path segments.
706 /// This returns the `Res` even if it was erroneous for some reason
707 /// (such as having invalid URL fragments or being in the wrong namespace).
713 extra_fragment: &Option<String>,
715 // resolve() can't be used for macro namespace
716 let result = match ns {
717 Namespace::MacroNS => self.resolve_macro(path_str, module_id).map_err(ErrorKind::from),
718 Namespace::TypeNS | Namespace::ValueNS => {
719 self.resolve(path_str, ns, module_id, extra_fragment).map(|(res, _)| res)
723 let res = match result {
724 Ok(res) => Some(res),
725 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
726 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
727 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
729 self.kind_side_channel.take().map(|(kind, id)| Res::Def(kind, id)).or(res)
733 /// Look to see if a resolved item has an associated item named `item_name`.
735 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
736 /// find `std::error::Error::source` and return
737 /// `<io::Error as error::Error>::source`.
738 fn resolve_associated_trait_item(
743 cx: &mut DocContext<'_>,
744 ) -> Option<(ty::AssocKind, DefId)> {
745 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
746 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
747 // meantime, just don't look for these blanket impls.
749 // Next consider explicit impls: `impl MyTrait for MyType`
750 // Give precedence to inherent impls.
751 let traits = traits_implemented_by(cx, did, module);
752 debug!("considering traits {:?}", traits);
753 let mut candidates = traits.iter().filter_map(|&trait_| {
755 .associated_items(trait_)
756 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
757 .map(|assoc| (assoc.kind, assoc.def_id))
759 // FIXME(#74563): warn about ambiguity
760 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
764 /// Given a type, return all traits in scope in `module` implemented by that type.
766 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
767 /// So it is not stable to serialize cross-crate.
768 fn traits_implemented_by(cx: &mut DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
769 let mut resolver = cx.resolver.borrow_mut();
770 let in_scope_traits = cx.module_trait_cache.entry(module).or_insert_with(|| {
771 resolver.access(|resolver| {
772 let parent_scope = &ParentScope::module(resolver.get_module(module), resolver);
774 .traits_in_scope(None, parent_scope, SyntaxContext::root(), None)
776 .map(|candidate| candidate.def_id)
782 let ty = tcx.type_of(type_);
783 let iter = in_scope_traits.iter().flat_map(|&trait_| {
784 trace!("considering explicit impl for trait {:?}", trait_);
786 // Look at each trait implementation to see if it's an impl for `did`
787 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
788 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
789 // Check if these are the same type.
790 let impl_type = trait_ref.self_ty();
792 "comparing type {} with kind {:?} against type {:?}",
797 // Fast path: if this is a primitive simple `==` will work
798 let saw_impl = impl_type == ty
799 || match impl_type.kind() {
800 // Check if these are the same def_id
802 debug!("adt def_id: {:?}", def.did);
805 ty::Foreign(def_id) => *def_id == type_,
809 if saw_impl { Some(trait_) } else { None }
815 /// Check for resolve collisions between a trait and its derive.
817 /// These are common and we should just resolve to the trait in that case.
818 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
822 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
823 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
829 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
830 fn fold_item(&mut self, item: Item) -> Option<Item> {
831 use rustc_middle::ty::DefIdTree;
834 item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
835 if parent_node.is_some() {
836 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
839 // find item's parent to resolve `Self` in item's docs below
840 debug!("looking for the `Self` type");
841 let self_id = match item.def_id.as_def_id() {
844 if (matches!(self.cx.tcx.def_kind(did), DefKind::Field)
846 self.cx.tcx.def_kind(self.cx.tcx.parent(did).unwrap()),
850 self.cx.tcx.parent(did).and_then(|item_id| self.cx.tcx.parent(item_id))
854 self.cx.tcx.def_kind(did),
862 self.cx.tcx.parent(did)
864 Some(did) => match self.cx.tcx.parent(did) {
865 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
866 // Fixing this breaks `fn render_deref_methods`.
867 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
868 // regardless of what rustdoc wants to call it.
870 let parent_kind = self.cx.tcx.def_kind(parent);
871 Some(if parent_kind == DefKind::Impl { parent } else { did })
877 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
878 let self_name = self_id.and_then(|self_id| {
879 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
880 // using `ty.to_string()` (or any variant) has issues with raw idents
881 let ty = self.cx.tcx.type_of(self_id);
882 let name = match ty.kind() {
883 ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
884 other if other.is_primitive() => Some(ty.to_string()),
887 debug!("using type_of(): {:?}", name);
890 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
891 debug!("using item_name(): {:?}", name);
896 let inner_docs = item.inner_docs(self.cx.tcx);
898 if item.is_mod() && inner_docs {
899 self.mod_ids.push(item.def_id.expect_def_id());
902 // We want to resolve in the lexical scope of the documentation.
903 // In the presence of re-exports, this is not the same as the module of the item.
904 // Rather than merging all documentation into one, resolve it one attribute at a time
905 // so we know which module it came from.
906 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
907 debug!("combined_docs={}", doc);
909 let (krate, parent_node) = if let Some(id) = parent_module {
912 (item.def_id.krate(), parent_node)
914 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
915 // This is a degenerate case and it's not supported by rustdoc.
916 for md_link in markdown_links(&doc) {
917 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
918 if let Some(link) = link {
919 self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
924 Some(if item.is_mod() {
926 self.mod_ids.push(item.def_id.expect_def_id());
929 let ret = self.fold_item_recur(item);
933 self.fold_item_recur(item)
938 enum PreprocessingError<'a> {
939 Anchor(AnchorFailure),
940 Disambiguator(Range<usize>, String),
941 Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
944 impl From<AnchorFailure> for PreprocessingError<'_> {
945 fn from(err: AnchorFailure) -> Self {
950 struct PreprocessingInfo {
952 disambiguator: Option<Disambiguator>,
953 extra_fragment: Option<String>,
958 /// - `None` if the link should be ignored.
959 /// - `Some(Err)` if the link should emit an error
960 /// - `Some(Ok)` if the link is valid
962 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
963 fn preprocess_link<'a>(
964 ori_link: &'a MarkdownLink,
965 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
966 // [] is mostly likely not supposed to be a link
967 if ori_link.link.is_empty() {
971 // Bail early for real links.
972 if ori_link.link.contains('/') {
976 let stripped = ori_link.link.replace("`", "");
977 let mut parts = stripped.split('#');
979 let link = parts.next().unwrap();
980 if link.trim().is_empty() {
981 // This is an anchor to an element of the current page, nothing to do in here!
984 let extra_fragment = parts.next();
985 if parts.next().is_some() {
986 // A valid link can't have multiple #'s
987 return Some(Err(AnchorFailure::MultipleAnchors.into()));
990 // Parse and strip the disambiguator from the link, if present.
991 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(&link) {
992 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
993 Ok(None) => (None, link.trim(), link.trim()),
994 Err((err_msg, relative_range)) => {
995 // Only report error if we would not have ignored this link. See issue #83859.
996 if !should_ignore_link_with_disambiguators(link) {
997 let no_backticks_range = range_between_backticks(&ori_link);
998 let disambiguator_range = (no_backticks_range.start + relative_range.start)
999 ..(no_backticks_range.start + relative_range.end);
1000 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1007 if should_ignore_link(path_str) {
1011 // Strip generics from the path.
1012 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1013 match strip_generics_from_path(&path_str) {
1016 debug!("link has malformed generics: {}", path_str);
1017 return Some(Err(PreprocessingError::Resolution(
1019 path_str.to_owned(),
1028 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1029 assert!(!path_str.contains(['<', '>'].as_slice()));
1031 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1032 if path_str.contains(' ') {
1036 Some(Ok(PreprocessingInfo {
1039 extra_fragment: extra_fragment.map(String::from),
1040 link_text: link_text.to_owned(),
1044 impl LinkCollector<'_, '_> {
1045 /// This is the entry point for resolving an intra-doc link.
1047 /// FIXME(jynelson): this is way too many arguments
1052 self_name: &Option<String>,
1053 parent_node: Option<DefId>,
1055 ori_link: MarkdownLink,
1056 ) -> Option<ItemLink> {
1057 trace!("considering link '{}'", ori_link.link);
1059 let diag_info = DiagnosticInfo {
1062 ori_link: &ori_link.link,
1063 link_range: ori_link.range.clone(),
1066 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1067 match preprocess_link(&ori_link)? {
1071 PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1072 PreprocessingError::Disambiguator(range, msg) => {
1073 disambiguator_error(self.cx, diag_info, range, &msg)
1075 PreprocessingError::Resolution(err, path_str, disambiguator) => {
1088 let mut path_str = &*path_str;
1090 let inner_docs = item.inner_docs(self.cx.tcx);
1092 // In order to correctly resolve intra-doc links we need to
1093 // pick a base AST node to work from. If the documentation for
1094 // this module came from an inner comment (//!) then we anchor
1095 // our name resolution *inside* the module. If, on the other
1096 // hand it was an outer comment (///) then we anchor the name
1097 // resolution in the parent module on the basis that the names
1098 // used are more likely to be intended to be parent names. For
1099 // this, we set base_node to None for inner comments since
1100 // we've already pushed this node onto the resolution stack but
1101 // for outer comments we explicitly try and resolve against the
1102 // parent_node first.
1104 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1106 let mut module_id = if let Some(id) = base_node {
1110 debug!("attempting to resolve item without parent module: {}", path_str);
1116 smallvec![ResolutionFailure::NoParentItem],
1122 // replace `Self` with suitable item's parent name
1123 let is_lone_self = path_str == "Self";
1124 let is_lone_crate = path_str == "crate";
1125 if path_str.starts_with("Self::") || is_lone_self {
1126 if let Some(ref name) = self_name {
1130 resolved_self = format!("{}::{}", name, &path_str[6..]);
1131 path_str = &resolved_self;
1134 } else if path_str.starts_with("crate::") || is_lone_crate {
1135 use rustc_span::def_id::CRATE_DEF_INDEX;
1137 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1138 // But rustdoc wants it to mean the crate this item was originally present in.
1139 // To work around this, remove it and resolve relative to the crate root instead.
1140 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1141 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1142 // FIXME(#78696): This doesn't always work.
1146 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1147 path_str = &resolved_self;
1149 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1152 let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(
1156 path_str: path_str.to_owned(),
1157 extra_fragment: extra_fragment.map(String::from),
1159 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1160 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1163 // Check for a primitive which might conflict with a module
1164 // Report the ambiguity and require that the user specify which one they meant.
1165 // FIXME: could there ever be a primitive not in the type namespace?
1168 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1169 ) && !matches!(res, Res::Primitive(_))
1171 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1173 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1174 if fragment.is_some() {
1178 AnchorFailure::RustdocAnchorConflict(prim),
1183 fragment = Some(prim.name(self.cx.tcx).to_string());
1185 // `[char]` when a `char` module is in scope
1186 let candidates = vec![res, prim];
1187 ambiguity_error(self.cx, diag_info, path_str, candidates);
1193 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1194 // The resolved item did not match the disambiguator; give a better error than 'not found'
1195 let msg = format!("incompatible link kind for `{}`", path_str);
1196 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1198 "this link resolved to {} {}, which is not {} {}",
1201 specified.article(),
1205 suggest_disambiguator(resolved, diag, path_str, dox, sp, &ori_link.range);
1207 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1210 let verify = |kind: DefKind, id: DefId| {
1211 let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id));
1212 debug!("intra-doc link to {} resolved to {:?} (id: {:?})", path_str, res, id);
1214 // Disallow e.g. linking to enums with `struct@`
1215 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1216 match (kind, disambiguator) {
1217 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1218 // NOTE: this allows 'method' to mean both normal functions and associated functions
1219 // This can't cause ambiguity because both are in the same namespace.
1220 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1221 // These are namespaces; allow anything in the namespace to match
1222 | (_, Some(Disambiguator::Namespace(_)))
1223 // If no disambiguator given, allow anything
1225 // All of these are valid, so do nothing
1227 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1228 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1229 report_mismatch(specified, Disambiguator::Kind(kind));
1234 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1235 if let Some((src_id, dst_id)) = id
1237 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1238 // would presumably panic if a fake `DefIndex` were passed.
1239 .and_then(|dst_id| {
1240 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1243 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1244 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1246 if self.cx.tcx.privacy_access_levels(()).is_exported(hir_src)
1247 && !self.cx.tcx.privacy_access_levels(()).is_exported(hir_dst)
1249 privacy_error(self.cx, &diag_info, &path_str);
1257 Res::Primitive(prim) => {
1258 if let Some((kind, id)) = self.kind_side_channel.take() {
1259 // We're actually resolving an associated item of a primitive, so we need to
1260 // verify the disambiguator (if any) matches the type of the associated item.
1261 // This case should really follow the same flow as the `Res::Def` branch below,
1262 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1263 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1264 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1265 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1266 // for discussion on the matter.
1267 verify(kind, id.into())?;
1269 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1270 // However I'm not sure how to check that across crates.
1271 if prim == PrimitiveType::RawPointer
1272 && item.def_id.is_local()
1273 && !self.cx.tcx.features().intra_doc_pointers
1275 let span = super::source_span_for_markdown_range(
1281 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1283 rustc_session::parse::feature_err(
1284 &self.cx.tcx.sess.parse_sess,
1285 sym::intra_doc_pointers,
1287 "linking to associated items of raw pointers is experimental",
1289 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1293 match disambiguator {
1294 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1296 report_mismatch(other, Disambiguator::Primitive);
1302 Some(ItemLink { link: ori_link.link, link_text, did: None, fragment })
1304 Res::Def(kind, id) => {
1305 verify(kind, id.into())?;
1306 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1307 Some(ItemLink { link: ori_link.link, link_text, did: Some(id.into()), fragment })
1312 fn resolve_with_disambiguator_cached(
1314 key: ResolutionInfo,
1315 diag: DiagnosticInfo<'_>,
1316 cache_resolution_failure: bool,
1317 ) -> Option<(Res, Option<String>)> {
1318 // Try to look up both the result and the corresponding side channel value
1319 if let Some(ref cached) = self.visited_links.get(&key) {
1322 self.kind_side_channel.set(cached.side_channel.clone());
1323 return Some(cached.res.clone());
1325 None if cache_resolution_failure => return None,
1327 // Although we hit the cache and found a resolution error, this link isn't
1328 // supposed to cache those. Run link resolution again to emit the expected
1329 // resolution error.
1334 let res = self.resolve_with_disambiguator(&key, diag);
1336 // Cache only if resolved successfully - don't silence duplicate errors
1337 if let Some(res) = res {
1338 // Store result for the actual namespace
1339 self.visited_links.insert(
1343 side_channel: self.kind_side_channel.clone().into_inner(),
1349 if cache_resolution_failure {
1350 // For reference-style links we only want to report one resolution error
1351 // so let's cache them as well.
1352 self.visited_links.insert(key, None);
1359 /// After parsing the disambiguator, resolve the main part of the link.
1360 // FIXME(jynelson): wow this is just so much
1361 fn resolve_with_disambiguator(
1363 key: &ResolutionInfo,
1364 diag: DiagnosticInfo<'_>,
1365 ) -> Option<(Res, Option<String>)> {
1366 let disambiguator = key.dis;
1367 let path_str = &key.path_str;
1368 let base_node = key.module_id;
1369 let extra_fragment = &key.extra_fragment;
1371 match disambiguator.map(Disambiguator::ns) {
1372 Some(expected_ns @ (ValueNS | TypeNS)) => {
1373 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1374 Ok(res) => Some(res),
1375 Err(ErrorKind::Resolve(box mut kind)) => {
1376 // We only looked in one namespace. Try to give a better error if possible.
1377 if kind.full_res().is_none() {
1378 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1379 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1380 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1381 for new_ns in [other_ns, MacroNS] {
1383 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1385 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1390 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1391 // This could just be a normal link or a broken link
1392 // we could potentially check if something is
1393 // "intra-doc-link-like" and warn in that case.
1396 Err(ErrorKind::AnchorFailure(msg)) => {
1397 anchor_failure(self.cx, diag, msg);
1404 let mut candidates = PerNS {
1406 .resolve_macro(path_str, base_node)
1407 .map(|res| (res, extra_fragment.clone())),
1408 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1410 debug!("got res in TypeNS: {:?}", res);
1413 Err(ErrorKind::AnchorFailure(msg)) => {
1414 anchor_failure(self.cx, diag, msg);
1417 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1419 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1421 Err(ErrorKind::AnchorFailure(msg)) => {
1422 anchor_failure(self.cx, diag, msg);
1425 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1427 .and_then(|(res, fragment)| {
1428 // Constructors are picked up in the type namespace.
1430 Res::Def(DefKind::Ctor(..), _) => {
1431 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1434 match (fragment, extra_fragment.clone()) {
1435 (Some(fragment), Some(_)) => {
1436 // Shouldn't happen but who knows?
1437 Ok((res, Some(fragment)))
1439 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1446 let len = candidates.iter().filter(|res| res.is_ok()).count();
1454 candidates.into_iter().filter_map(|res| res.err()).collect(),
1456 // this could just be a normal link
1461 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1462 } else if len == 2 && is_derive_trait_collision(&candidates) {
1463 Some(candidates.type_ns.unwrap())
1465 if is_derive_trait_collision(&candidates) {
1466 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1468 // If we're reporting an ambiguity, don't mention the namespaces that failed
1469 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1470 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1475 match self.resolve_macro(path_str, base_node) {
1476 Ok(res) => Some((res, extra_fragment.clone())),
1478 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1479 for ns in [TypeNS, ValueNS] {
1481 self.check_full_res(ns, path_str, base_node, extra_fragment)
1484 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1488 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1497 /// Get the section of a link between the backticks,
1498 /// or the whole link if there aren't any backticks.
1506 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1507 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1508 let before_second_backtick_group = ori_link
1511 .skip(after_first_backtick_group)
1512 .position(|b| b == b'`')
1513 .unwrap_or(ori_link.link.len());
1514 (ori_link.range.start + after_first_backtick_group)
1515 ..(ori_link.range.start + before_second_backtick_group)
1518 /// Returns true if we should ignore `link` due to it being unlikely
1519 /// that it is an intra-doc link. `link` should still have disambiguators
1520 /// if there were any.
1522 /// The difference between this and [`should_ignore_link()`] is that this
1523 /// check should only be used on links that still have disambiguators.
1524 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1525 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1528 /// Returns true if we should ignore `path_str` due to it being unlikely
1529 /// that it is an intra-doc link.
1530 fn should_ignore_link(path_str: &str) -> bool {
1531 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1534 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1535 /// Disambiguators for a link.
1536 enum Disambiguator {
1539 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1541 /// `struct@` or `f()`
1544 Namespace(Namespace),
1547 impl Disambiguator {
1548 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1550 /// This returns `Ok(Some(...))` if a disambiguator was found,
1551 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1552 /// if there was a problem with the disambiguator.
1553 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1554 use Disambiguator::{Kind, Namespace as NS, Primitive};
1556 if let Some(idx) = link.find('@') {
1557 let (prefix, rest) = link.split_at(idx);
1558 let d = match prefix {
1559 "struct" => Kind(DefKind::Struct),
1560 "enum" => Kind(DefKind::Enum),
1561 "trait" => Kind(DefKind::Trait),
1562 "union" => Kind(DefKind::Union),
1563 "module" | "mod" => Kind(DefKind::Mod),
1564 "const" | "constant" => Kind(DefKind::Const),
1565 "static" => Kind(DefKind::Static),
1566 "function" | "fn" | "method" => Kind(DefKind::Fn),
1567 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1568 "type" => NS(Namespace::TypeNS),
1569 "value" => NS(Namespace::ValueNS),
1570 "macro" => NS(Namespace::MacroNS),
1571 "prim" | "primitive" => Primitive,
1572 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1574 Ok(Some((d, &rest[1..], &rest[1..])))
1577 ("!()", DefKind::Macro(MacroKind::Bang)),
1578 ("!{}", DefKind::Macro(MacroKind::Bang)),
1579 ("![]", DefKind::Macro(MacroKind::Bang)),
1580 ("()", DefKind::Fn),
1581 ("!", DefKind::Macro(MacroKind::Bang)),
1583 for (suffix, kind) in suffixes {
1584 if let Some(path_str) = link.strip_suffix(suffix) {
1585 // Avoid turning `!` or `()` into an empty string
1586 if !path_str.is_empty() {
1587 return Ok(Some((Kind(kind), path_str, link)));
1595 fn from_res(res: Res) -> Self {
1597 Res::Def(kind, _) => Disambiguator::Kind(kind),
1598 Res::Primitive(_) => Disambiguator::Primitive,
1602 /// Used for error reporting.
1603 fn suggestion(self) -> Suggestion {
1604 let kind = match self {
1605 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1606 Disambiguator::Kind(kind) => kind,
1607 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1609 if kind == DefKind::Macro(MacroKind::Bang) {
1610 return Suggestion::Macro;
1611 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1612 return Suggestion::Function;
1615 let prefix = match kind {
1616 DefKind::Struct => "struct",
1617 DefKind::Enum => "enum",
1618 DefKind::Trait => "trait",
1619 DefKind::Union => "union",
1620 DefKind::Mod => "mod",
1621 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1624 DefKind::Static => "static",
1625 DefKind::Macro(MacroKind::Derive) => "derive",
1626 // Now handle things that don't have a specific disambiguator
1629 .expect("tried to calculate a disambiguator for a def without a namespace?")
1631 Namespace::TypeNS => "type",
1632 Namespace::ValueNS => "value",
1633 Namespace::MacroNS => "macro",
1637 Suggestion::Prefix(prefix)
1640 fn ns(self) -> Namespace {
1642 Self::Namespace(n) => n,
1644 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1646 Self::Primitive => TypeNS,
1650 fn article(self) -> &'static str {
1652 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1653 Self::Kind(k) => k.article(),
1654 Self::Primitive => "a",
1658 fn descr(self) -> &'static str {
1660 Self::Namespace(n) => n.descr(),
1661 // HACK(jynelson): by looking at the source I saw the DefId we pass
1662 // for `expected.descr()` doesn't matter, since it's not a crate
1663 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1664 Self::Primitive => "builtin type",
1669 /// A suggestion to show in a diagnostic.
1672 Prefix(&'static str),
1680 fn descr(&self) -> Cow<'static, str> {
1682 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1683 Self::Function => "add parentheses".into(),
1684 Self::Macro => "add an exclamation mark".into(),
1688 fn as_help(&self, path_str: &str) -> String {
1689 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1691 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1692 Self::Function => format!("{}()", path_str),
1693 Self::Macro => format!("{}!", path_str),
1698 /// Reports a diagnostic for an intra-doc link.
1700 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1701 /// the entire documentation block is used for the lint. If a range is provided but the span
1702 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1704 /// The `decorate` callback is invoked in all cases to allow further customization of the
1705 /// diagnostic before emission. If the span of the link was able to be determined, the second
1706 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1708 fn report_diagnostic(
1710 lint: &'static Lint,
1712 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1713 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1715 let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1716 Some(hir_id) => hir_id,
1718 // If non-local, no need to check anything.
1719 info!("ignoring warning from parent crate: {}", msg);
1724 let sp = item.attr_span(tcx);
1726 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1727 let mut diag = lint.build(msg);
1729 let span = super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs);
1731 if let Some(sp) = span {
1734 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1737 // last_new_line_offset
1738 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1739 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1741 // Print the line containing the `link_range` and manually mark it with '^'s.
1743 "the link appears in this line:\n\n{line}\n\
1744 {indicator: <before$}{indicator:^<found$}",
1747 before = link_range.start - last_new_line_offset,
1748 found = link_range.len(),
1752 decorate(&mut diag, span);
1758 /// Reports a link that failed to resolve.
1760 /// This also tries to resolve any intermediate path segments that weren't
1761 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1762 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1763 fn resolution_failure(
1764 collector: &mut LinkCollector<'_, '_>,
1765 diag_info: DiagnosticInfo<'_>,
1767 disambiguator: Option<Disambiguator>,
1768 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1770 let tcx = collector.cx.tcx;
1773 BROKEN_INTRA_DOC_LINKS,
1774 &format!("unresolved link to `{}`", path_str),
1777 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1778 let assoc_item_not_allowed = |res: Res| {
1779 let name = res.name(tcx);
1781 "`{}` is {} {}, not a module or type, and cannot have associated items",
1787 // ignore duplicates
1788 let mut variants_seen = SmallVec::<[_; 3]>::new();
1789 for mut failure in kinds {
1790 let variant = std::mem::discriminant(&failure);
1791 if variants_seen.contains(&variant) {
1794 variants_seen.push(variant);
1796 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1801 let module_id = *module_id;
1802 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1803 // FIXME: maybe use itertools `collect_tuple` instead?
1804 fn split(path: &str) -> Option<(&str, &str)> {
1805 let mut splitter = path.rsplitn(2, "::");
1806 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1809 // Check if _any_ parent of the path gets resolved.
1810 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1811 let mut name = path_str;
1813 let (start, end) = if let Some(x) = split(name) {
1816 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1817 if partial_res.is_none() {
1818 *unresolved = name.into();
1823 for ns in [TypeNS, ValueNS, MacroNS] {
1825 collector.check_full_res(ns, &start, module_id.into(), &None)
1827 debug!("found partial_res={:?}", res);
1828 *partial_res = Some(res);
1829 *unresolved = end.into();
1833 *unresolved = end.into();
1836 let last_found_module = match *partial_res {
1837 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1838 None => Some(module_id),
1841 // See if this was a module: `[path]` or `[std::io::nope]`
1842 if let Some(module) = last_found_module {
1843 let note = if partial_res.is_some() {
1844 // Part of the link resolved; e.g. `std::io::nonexistent`
1845 let module_name = tcx.item_name(module);
1846 format!("no item named `{}` in module `{}`", unresolved, module_name)
1848 // None of the link resolved; e.g. `Notimported`
1849 format!("no item named `{}` in scope", unresolved)
1851 if let Some(span) = sp {
1852 diag.span_label(span, ¬e);
1857 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1858 // Otherwise, the `[]` might be unrelated.
1859 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1860 if !path_str.contains("::") {
1861 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1867 // Otherwise, it must be an associated item or variant
1868 let res = partial_res.expect("None case was handled by `last_found_module`");
1869 let name = res.name(tcx);
1870 let kind = match res {
1871 Res::Def(kind, _) => Some(kind),
1872 Res::Primitive(_) => None,
1874 let path_description = if let Some(kind) = kind {
1876 Mod | ForeignMod => "inner item",
1877 Struct => "field or associated item",
1878 Enum | Union => "variant or associated item",
1895 let note = assoc_item_not_allowed(res);
1896 if let Some(span) = sp {
1897 diag.span_label(span, ¬e);
1903 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1904 | Static => "associated item",
1905 Impl | GlobalAsm => unreachable!("not a path"),
1911 "the {} `{}` has no {} named `{}`",
1914 disambiguator.map_or(path_description, |d| d.descr()),
1917 if let Some(span) = sp {
1918 diag.span_label(span, ¬e);
1925 let note = match failure {
1926 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1927 ResolutionFailure::Dummy => continue,
1928 ResolutionFailure::WrongNamespace { res, expected_ns } => {
1929 if let Res::Def(kind, _) = res {
1930 let disambiguator = Disambiguator::Kind(kind);
1931 suggest_disambiguator(
1937 &diag_info.link_range,
1942 "this link resolves to {}, which is not in the {} namespace",
1947 ResolutionFailure::NoParentItem => {
1948 diag.level = rustc_errors::Level::Bug;
1949 "all intra-doc links should have a parent item".to_owned()
1951 ResolutionFailure::MalformedGenerics(variant) => match variant {
1952 MalformedGenerics::UnbalancedAngleBrackets => {
1953 String::from("unbalanced angle brackets")
1955 MalformedGenerics::MissingType => {
1956 String::from("missing type for generic parameters")
1958 MalformedGenerics::HasFullyQualifiedSyntax => {
1959 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1960 String::from("fully-qualified syntax is unsupported")
1962 MalformedGenerics::InvalidPathSeparator => {
1963 String::from("has invalid path separator")
1965 MalformedGenerics::TooManyAngleBrackets => {
1966 String::from("too many angle brackets")
1968 MalformedGenerics::EmptyAngleBrackets => {
1969 String::from("empty angle brackets")
1973 if let Some(span) = sp {
1974 diag.span_label(span, ¬e);
1983 /// Report an anchor failure.
1984 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
1985 let (msg, anchor_idx) = match failure {
1986 AnchorFailure::MultipleAnchors => {
1987 (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
1989 AnchorFailure::RustdocAnchorConflict(res) => (
1991 "`{}` contains an anchor, but links to {kind}s are already anchored",
1999 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2000 if let Some(mut sp) = sp {
2001 if let Some((fragment_offset, _)) =
2002 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2004 sp = sp.with_lo(sp.lo() + rustc_span::BytePos(fragment_offset as _));
2006 diag.span_label(sp, "invalid anchor");
2008 if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2009 diag.note("this restriction may be lifted in a future release");
2010 diag.note("see https://github.com/rust-lang/rust/issues/83083 for more information");
2015 /// Report an error in the link disambiguator.
2016 fn disambiguator_error(
2017 cx: &DocContext<'_>,
2018 mut diag_info: DiagnosticInfo<'_>,
2019 disambiguator_range: Range<usize>,
2022 diag_info.link_range = disambiguator_range;
2023 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2025 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2026 crate::DOC_RUST_LANG_ORG_CHANNEL
2032 /// Report an ambiguity error, where there were multiple possible resolutions.
2034 cx: &DocContext<'_>,
2035 diag_info: DiagnosticInfo<'_>,
2037 candidates: Vec<Res>,
2039 let mut msg = format!("`{}` is ", path_str);
2041 match candidates.as_slice() {
2042 [first_def, second_def] => {
2044 "both {} {} and {} {}",
2045 first_def.article(),
2047 second_def.article(),
2052 let mut candidates = candidates.iter().peekable();
2053 while let Some(res) = candidates.next() {
2054 if candidates.peek().is_some() {
2055 msg += &format!("{} {}, ", res.article(), res.descr());
2057 msg += &format!("and {} {}", res.article(), res.descr());
2063 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2064 if let Some(sp) = sp {
2065 diag.span_label(sp, "ambiguous link");
2067 diag.note("ambiguous link");
2070 for res in candidates {
2071 let disambiguator = Disambiguator::from_res(res);
2072 suggest_disambiguator(
2078 &diag_info.link_range,
2084 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2086 fn suggest_disambiguator(
2087 disambiguator: Disambiguator,
2088 diag: &mut DiagnosticBuilder<'_>,
2091 sp: Option<rustc_span::Span>,
2092 link_range: &Range<usize>,
2094 let suggestion = disambiguator.suggestion();
2095 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
2097 if let Some(sp) = sp {
2098 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
2099 format!("`{}`", suggestion.as_help(path_str))
2101 suggestion.as_help(path_str)
2104 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
2106 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2110 /// Report a link from a public item to a private one.
2111 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2113 let item_name = match diag_info.item.name {
2115 sym = name.as_str();
2118 None => "<unknown>",
2121 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2123 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2124 if let Some(sp) = sp {
2125 diag.span_label(sp, "this item is private");
2128 let note_msg = if cx.render_options.document_private {
2129 "this link resolves only because you passed `--document-private-items`, but will break without"
2131 "this link will resolve properly if you pass `--document-private-items`"
2133 diag.note(note_msg);
2137 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2139 cx: &DocContext<'_>,
2141 extra_fragment: &Option<String>,
2142 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
2143 use rustc_middle::ty::DefIdTree;
2145 if extra_fragment.is_some() {
2146 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2149 .parent(res.def_id())
2151 let parent_def = Res::Def(DefKind::Enum, parent);
2152 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2153 (parent_def, Some(format!("variant.{}", variant.ident.name)))
2155 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2158 /// Resolve a primitive type or value.
2159 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2163 use PrimitiveType::*;
2164 let prim = match path_str {
2180 "bool" | "true" | "false" => Bool,
2181 "str" | "&str" => Str,
2182 // See #80181 for why these don't have symbols associated.
2187 "pointer" | "*const" | "*mut" => RawPointer,
2188 "reference" | "&" | "&mut" => Reference,
2190 "never" | "!" => Never,
2193 debug!("resolved primitives {:?}", prim);
2194 Some(Res::Primitive(prim))
2197 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2198 let mut stripped_segments = vec![];
2199 let mut path = path_str.chars().peekable();
2200 let mut segment = Vec::new();
2202 while let Some(chr) = path.next() {
2205 if path.next_if_eq(&':').is_some() {
2206 let stripped_segment =
2207 strip_generics_from_path_segment(mem::take(&mut segment))?;
2208 if !stripped_segment.is_empty() {
2209 stripped_segments.push(stripped_segment);
2212 return Err(ResolutionFailure::MalformedGenerics(
2213 MalformedGenerics::InvalidPathSeparator,
2222 return Err(ResolutionFailure::MalformedGenerics(
2223 MalformedGenerics::TooManyAngleBrackets,
2227 return Err(ResolutionFailure::MalformedGenerics(
2228 MalformedGenerics::EmptyAngleBrackets,
2234 while let Some(chr) = path.next_if(|c| *c != '>') {
2241 _ => segment.push(chr),
2243 trace!("raw segment: {:?}", segment);
2246 if !segment.is_empty() {
2247 let stripped_segment = strip_generics_from_path_segment(segment)?;
2248 if !stripped_segment.is_empty() {
2249 stripped_segments.push(stripped_segment);
2253 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2255 let stripped_path = stripped_segments.join("::");
2257 if !stripped_path.is_empty() {
2260 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2264 fn strip_generics_from_path_segment(
2266 ) -> Result<String, ResolutionFailure<'static>> {
2267 let mut stripped_segment = String::new();
2268 let mut param_depth = 0;
2270 let mut latest_generics_chunk = String::new();
2275 latest_generics_chunk.clear();
2276 } else if c == '>' {
2278 if latest_generics_chunk.contains(" as ") {
2279 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2280 // Give a helpful error message instead of completely ignoring the angle brackets.
2281 return Err(ResolutionFailure::MalformedGenerics(
2282 MalformedGenerics::HasFullyQualifiedSyntax,
2286 if param_depth == 0 {
2287 stripped_segment.push(c);
2289 latest_generics_chunk.push(c);
2294 if param_depth == 0 {
2295 Ok(stripped_segment)
2297 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2298 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))