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;
833 let parent_node = if item.is_fake() {
836 find_nearest_parent_module(self.cx.tcx, item.def_id.expect_real())
839 if parent_node.is_some() {
840 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
843 // find item's parent to resolve `Self` in item's docs below
844 debug!("looking for the `Self` type");
845 let self_id = if item.is_fake() {
847 // Checking if the item is a field in an enum variant
848 } else if (matches!(self.cx.tcx.def_kind(item.def_id.expect_real()), DefKind::Field)
850 self.cx.tcx.def_kind(self.cx.tcx.parent(item.def_id.expect_real()).unwrap()),
856 .parent(item.def_id.expect_real())
857 .and_then(|item_id| self.cx.tcx.parent(item_id))
859 self.cx.tcx.def_kind(item.def_id.expect_real()),
866 self.cx.tcx.parent(item.def_id.expect_real())
867 // HACK(jynelson): `clean` marks associated types as `TypedefItem`, not as `AssocTypeItem`.
868 // Fixing this breaks `fn render_deref_methods`.
869 // As a workaround, see if the parent of the item is an `impl`; if so this must be an associated item,
870 // regardless of what rustdoc wants to call it.
871 } else if let Some(parent) = self.cx.tcx.parent(item.def_id.expect_real()) {
872 let parent_kind = self.cx.tcx.def_kind(parent);
873 Some(if parent_kind == DefKind::Impl { parent } else { item.def_id.expect_real() })
875 Some(item.def_id.expect_real())
878 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
879 let self_name = self_id.and_then(|self_id| {
880 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
881 // using `ty.to_string()` (or any variant) has issues with raw idents
882 let ty = self.cx.tcx.type_of(self_id);
883 let name = match ty.kind() {
884 ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
885 other if other.is_primitive() => Some(ty.to_string()),
888 debug!("using type_of(): {:?}", name);
891 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
892 debug!("using item_name(): {:?}", name);
897 let inner_docs = item.inner_docs(self.cx.tcx);
899 if item.is_mod() && inner_docs {
900 self.mod_ids.push(item.def_id.expect_real());
903 // We want to resolve in the lexical scope of the documentation.
904 // In the presence of re-exports, this is not the same as the module of the item.
905 // Rather than merging all documentation into one, resolve it one attribute at a time
906 // so we know which module it came from.
907 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
908 debug!("combined_docs={}", doc);
910 let (krate, parent_node) = if let Some(id) = parent_module {
913 (item.def_id.krate(), parent_node)
915 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
916 // This is a degenerate case and it's not supported by rustdoc.
917 for md_link in markdown_links(&doc) {
918 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
919 if let Some(link) = link {
920 self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
925 Some(if item.is_mod() {
927 self.mod_ids.push(item.def_id.expect_real());
930 let ret = self.fold_item_recur(item);
934 self.fold_item_recur(item)
939 enum PreprocessingError<'a> {
940 Anchor(AnchorFailure),
941 Disambiguator(Range<usize>, String),
942 Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
945 impl From<AnchorFailure> for PreprocessingError<'_> {
946 fn from(err: AnchorFailure) -> Self {
951 struct PreprocessingInfo {
953 disambiguator: Option<Disambiguator>,
954 extra_fragment: Option<String>,
959 /// - `None` if the link should be ignored.
960 /// - `Some(Err)` if the link should emit an error
961 /// - `Some(Ok)` if the link is valid
963 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
964 fn preprocess_link<'a>(
965 ori_link: &'a MarkdownLink,
966 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
967 // [] is mostly likely not supposed to be a link
968 if ori_link.link.is_empty() {
972 // Bail early for real links.
973 if ori_link.link.contains('/') {
977 let stripped = ori_link.link.replace("`", "");
978 let mut parts = stripped.split('#');
980 let link = parts.next().unwrap();
981 if link.trim().is_empty() {
982 // This is an anchor to an element of the current page, nothing to do in here!
985 let extra_fragment = parts.next();
986 if parts.next().is_some() {
987 // A valid link can't have multiple #'s
988 return Some(Err(AnchorFailure::MultipleAnchors.into()));
991 // Parse and strip the disambiguator from the link, if present.
992 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(&link) {
993 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
994 Ok(None) => (None, link.trim(), link.trim()),
995 Err((err_msg, relative_range)) => {
996 // Only report error if we would not have ignored this link. See issue #83859.
997 if !should_ignore_link_with_disambiguators(link) {
998 let no_backticks_range = range_between_backticks(&ori_link);
999 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1000 ..(no_backticks_range.start + relative_range.end);
1001 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1008 if should_ignore_link(path_str) {
1012 // Strip generics from the path.
1013 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1014 match strip_generics_from_path(&path_str) {
1017 debug!("link has malformed generics: {}", path_str);
1018 return Some(Err(PreprocessingError::Resolution(
1020 path_str.to_owned(),
1029 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1030 assert!(!path_str.contains(['<', '>'].as_slice()));
1032 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1033 if path_str.contains(' ') {
1037 Some(Ok(PreprocessingInfo {
1040 extra_fragment: extra_fragment.map(String::from),
1041 link_text: link_text.to_owned(),
1045 impl LinkCollector<'_, '_> {
1046 /// This is the entry point for resolving an intra-doc link.
1048 /// FIXME(jynelson): this is way too many arguments
1053 self_name: &Option<String>,
1054 parent_node: Option<DefId>,
1056 ori_link: MarkdownLink,
1057 ) -> Option<ItemLink> {
1058 trace!("considering link '{}'", ori_link.link);
1060 let diag_info = DiagnosticInfo {
1063 ori_link: &ori_link.link,
1064 link_range: ori_link.range.clone(),
1067 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1068 match preprocess_link(&ori_link)? {
1072 PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1073 PreprocessingError::Disambiguator(range, msg) => {
1074 disambiguator_error(self.cx, diag_info, range, &msg)
1076 PreprocessingError::Resolution(err, path_str, disambiguator) => {
1089 let mut path_str = &*path_str;
1091 let inner_docs = item.inner_docs(self.cx.tcx);
1093 // In order to correctly resolve intra-doc links we need to
1094 // pick a base AST node to work from. If the documentation for
1095 // this module came from an inner comment (//!) then we anchor
1096 // our name resolution *inside* the module. If, on the other
1097 // hand it was an outer comment (///) then we anchor the name
1098 // resolution in the parent module on the basis that the names
1099 // used are more likely to be intended to be parent names. For
1100 // this, we set base_node to None for inner comments since
1101 // we've already pushed this node onto the resolution stack but
1102 // for outer comments we explicitly try and resolve against the
1103 // parent_node first.
1105 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1107 let mut module_id = if let Some(id) = base_node {
1111 debug!("attempting to resolve item without parent module: {}", path_str);
1117 smallvec![ResolutionFailure::NoParentItem],
1123 // replace `Self` with suitable item's parent name
1124 let is_lone_self = path_str == "Self";
1125 let is_lone_crate = path_str == "crate";
1126 if path_str.starts_with("Self::") || is_lone_self {
1127 if let Some(ref name) = self_name {
1131 resolved_self = format!("{}::{}", name, &path_str[6..]);
1132 path_str = &resolved_self;
1135 } else if path_str.starts_with("crate::") || is_lone_crate {
1136 use rustc_span::def_id::CRATE_DEF_INDEX;
1138 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1139 // But rustdoc wants it to mean the crate this item was originally present in.
1140 // To work around this, remove it and resolve relative to the crate root instead.
1141 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1142 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1143 // FIXME(#78696): This doesn't always work.
1147 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1148 path_str = &resolved_self;
1150 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1153 let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(
1157 path_str: path_str.to_owned(),
1158 extra_fragment: extra_fragment.map(String::from),
1160 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1161 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1164 // Check for a primitive which might conflict with a module
1165 // Report the ambiguity and require that the user specify which one they meant.
1166 // FIXME: could there ever be a primitive not in the type namespace?
1169 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1170 ) && !matches!(res, Res::Primitive(_))
1172 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1174 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1175 if fragment.is_some() {
1179 AnchorFailure::RustdocAnchorConflict(prim),
1184 fragment = Some(prim.name(self.cx.tcx).to_string());
1186 // `[char]` when a `char` module is in scope
1187 let candidates = vec![res, prim];
1188 ambiguity_error(self.cx, diag_info, path_str, candidates);
1194 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1195 // The resolved item did not match the disambiguator; give a better error than 'not found'
1196 let msg = format!("incompatible link kind for `{}`", path_str);
1197 let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1199 "this link resolved to {} {}, which is not {} {}",
1202 specified.article(),
1206 suggest_disambiguator(resolved, diag, path_str, dox, sp, &ori_link.range);
1208 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1211 let verify = |kind: DefKind, id: DefId| {
1212 let (kind, id) = self.kind_side_channel.take().unwrap_or((kind, id));
1213 debug!("intra-doc link to {} resolved to {:?} (id: {:?})", path_str, res, id);
1215 // Disallow e.g. linking to enums with `struct@`
1216 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1217 match (kind, disambiguator) {
1218 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1219 // NOTE: this allows 'method' to mean both normal functions and associated functions
1220 // This can't cause ambiguity because both are in the same namespace.
1221 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1222 // These are namespaces; allow anything in the namespace to match
1223 | (_, Some(Disambiguator::Namespace(_)))
1224 // If no disambiguator given, allow anything
1226 // All of these are valid, so do nothing
1228 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1229 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1230 report_mismatch(specified, Disambiguator::Kind(kind));
1235 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1236 if let Some((src_id, dst_id)) = id
1238 // The `expect_real()` should be okay because `local_def_id_to_hir_id`
1239 // would presumably panic if a fake `DefIndex` were passed.
1240 .and_then(|dst_id| {
1241 item.def_id.expect_real().as_local().map(|src_id| (src_id, dst_id))
1244 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1245 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1247 if self.cx.tcx.privacy_access_levels(()).is_exported(hir_src)
1248 && !self.cx.tcx.privacy_access_levels(()).is_exported(hir_dst)
1250 privacy_error(self.cx, &diag_info, &path_str);
1258 Res::Primitive(prim) => {
1259 if let Some((kind, id)) = self.kind_side_channel.take() {
1260 // We're actually resolving an associated item of a primitive, so we need to
1261 // verify the disambiguator (if any) matches the type of the associated item.
1262 // This case should really follow the same flow as the `Res::Def` branch below,
1263 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1264 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1265 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1266 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1267 // for discussion on the matter.
1268 verify(kind, id.into())?;
1270 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1271 // However I'm not sure how to check that across crates.
1272 if prim == PrimitiveType::RawPointer
1273 && item.def_id.is_local()
1274 && !self.cx.tcx.features().intra_doc_pointers
1276 let span = super::source_span_for_markdown_range(
1282 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1284 rustc_session::parse::feature_err(
1285 &self.cx.tcx.sess.parse_sess,
1286 sym::intra_doc_pointers,
1288 "linking to associated items of raw pointers is experimental",
1290 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1294 match disambiguator {
1295 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1297 report_mismatch(other, Disambiguator::Primitive);
1303 Some(ItemLink { link: ori_link.link, link_text, did: None, fragment })
1305 Res::Def(kind, id) => {
1306 verify(kind, id.into())?;
1307 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1308 Some(ItemLink { link: ori_link.link, link_text, did: Some(id.into()), fragment })
1313 fn resolve_with_disambiguator_cached(
1315 key: ResolutionInfo,
1316 diag: DiagnosticInfo<'_>,
1317 cache_resolution_failure: bool,
1318 ) -> Option<(Res, Option<String>)> {
1319 // Try to look up both the result and the corresponding side channel value
1320 if let Some(ref cached) = self.visited_links.get(&key) {
1323 self.kind_side_channel.set(cached.side_channel.clone());
1324 return Some(cached.res.clone());
1326 None if cache_resolution_failure => return None,
1328 // Although we hit the cache and found a resolution error, this link isn't
1329 // supposed to cache those. Run link resolution again to emit the expected
1330 // resolution error.
1335 let res = self.resolve_with_disambiguator(&key, diag);
1337 // Cache only if resolved successfully - don't silence duplicate errors
1338 if let Some(res) = res {
1339 // Store result for the actual namespace
1340 self.visited_links.insert(
1344 side_channel: self.kind_side_channel.clone().into_inner(),
1350 if cache_resolution_failure {
1351 // For reference-style links we only want to report one resolution error
1352 // so let's cache them as well.
1353 self.visited_links.insert(key, None);
1360 /// After parsing the disambiguator, resolve the main part of the link.
1361 // FIXME(jynelson): wow this is just so much
1362 fn resolve_with_disambiguator(
1364 key: &ResolutionInfo,
1365 diag: DiagnosticInfo<'_>,
1366 ) -> Option<(Res, Option<String>)> {
1367 let disambiguator = key.dis;
1368 let path_str = &key.path_str;
1369 let base_node = key.module_id;
1370 let extra_fragment = &key.extra_fragment;
1372 match disambiguator.map(Disambiguator::ns) {
1373 Some(expected_ns @ (ValueNS | TypeNS)) => {
1374 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1375 Ok(res) => Some(res),
1376 Err(ErrorKind::Resolve(box mut kind)) => {
1377 // We only looked in one namespace. Try to give a better error if possible.
1378 if kind.full_res().is_none() {
1379 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1380 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1381 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1382 for new_ns in [other_ns, MacroNS] {
1384 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1386 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1391 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1392 // This could just be a normal link or a broken link
1393 // we could potentially check if something is
1394 // "intra-doc-link-like" and warn in that case.
1397 Err(ErrorKind::AnchorFailure(msg)) => {
1398 anchor_failure(self.cx, diag, msg);
1405 let mut candidates = PerNS {
1407 .resolve_macro(path_str, base_node)
1408 .map(|res| (res, extra_fragment.clone())),
1409 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1411 debug!("got res in TypeNS: {:?}", res);
1414 Err(ErrorKind::AnchorFailure(msg)) => {
1415 anchor_failure(self.cx, diag, msg);
1418 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1420 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1422 Err(ErrorKind::AnchorFailure(msg)) => {
1423 anchor_failure(self.cx, diag, msg);
1426 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1428 .and_then(|(res, fragment)| {
1429 // Constructors are picked up in the type namespace.
1431 Res::Def(DefKind::Ctor(..), _) => {
1432 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1435 match (fragment, extra_fragment.clone()) {
1436 (Some(fragment), Some(_)) => {
1437 // Shouldn't happen but who knows?
1438 Ok((res, Some(fragment)))
1440 (fragment, None) | (None, fragment) => Ok((res, fragment)),
1447 let len = candidates.iter().filter(|res| res.is_ok()).count();
1455 candidates.into_iter().filter_map(|res| res.err()).collect(),
1457 // this could just be a normal link
1462 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1463 } else if len == 2 && is_derive_trait_collision(&candidates) {
1464 Some(candidates.type_ns.unwrap())
1466 if is_derive_trait_collision(&candidates) {
1467 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1469 // If we're reporting an ambiguity, don't mention the namespaces that failed
1470 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1471 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1476 match self.resolve_macro(path_str, base_node) {
1477 Ok(res) => Some((res, extra_fragment.clone())),
1479 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1480 for ns in [TypeNS, ValueNS] {
1482 self.check_full_res(ns, path_str, base_node, extra_fragment)
1485 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1489 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1498 /// Get the section of a link between the backticks,
1499 /// or the whole link if there aren't any backticks.
1507 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1508 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1509 let before_second_backtick_group = ori_link
1512 .skip(after_first_backtick_group)
1513 .position(|b| b == b'`')
1514 .unwrap_or(ori_link.link.len());
1515 (ori_link.range.start + after_first_backtick_group)
1516 ..(ori_link.range.start + before_second_backtick_group)
1519 /// Returns true if we should ignore `link` due to it being unlikely
1520 /// that it is an intra-doc link. `link` should still have disambiguators
1521 /// if there were any.
1523 /// The difference between this and [`should_ignore_link()`] is that this
1524 /// check should only be used on links that still have disambiguators.
1525 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1526 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1529 /// Returns true if we should ignore `path_str` due to it being unlikely
1530 /// that it is an intra-doc link.
1531 fn should_ignore_link(path_str: &str) -> bool {
1532 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1535 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1536 /// Disambiguators for a link.
1537 enum Disambiguator {
1540 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1542 /// `struct@` or `f()`
1545 Namespace(Namespace),
1548 impl Disambiguator {
1549 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1551 /// This returns `Ok(Some(...))` if a disambiguator was found,
1552 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1553 /// if there was a problem with the disambiguator.
1554 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1555 use Disambiguator::{Kind, Namespace as NS, Primitive};
1557 if let Some(idx) = link.find('@') {
1558 let (prefix, rest) = link.split_at(idx);
1559 let d = match prefix {
1560 "struct" => Kind(DefKind::Struct),
1561 "enum" => Kind(DefKind::Enum),
1562 "trait" => Kind(DefKind::Trait),
1563 "union" => Kind(DefKind::Union),
1564 "module" | "mod" => Kind(DefKind::Mod),
1565 "const" | "constant" => Kind(DefKind::Const),
1566 "static" => Kind(DefKind::Static),
1567 "function" | "fn" | "method" => Kind(DefKind::Fn),
1568 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1569 "type" => NS(Namespace::TypeNS),
1570 "value" => NS(Namespace::ValueNS),
1571 "macro" => NS(Namespace::MacroNS),
1572 "prim" | "primitive" => Primitive,
1573 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1575 Ok(Some((d, &rest[1..], &rest[1..])))
1578 ("!()", DefKind::Macro(MacroKind::Bang)),
1579 ("!{}", DefKind::Macro(MacroKind::Bang)),
1580 ("![]", DefKind::Macro(MacroKind::Bang)),
1581 ("()", DefKind::Fn),
1582 ("!", DefKind::Macro(MacroKind::Bang)),
1584 for (suffix, kind) in suffixes {
1585 if let Some(path_str) = link.strip_suffix(suffix) {
1586 // Avoid turning `!` or `()` into an empty string
1587 if !path_str.is_empty() {
1588 return Ok(Some((Kind(kind), path_str, link)));
1596 fn from_res(res: Res) -> Self {
1598 Res::Def(kind, _) => Disambiguator::Kind(kind),
1599 Res::Primitive(_) => Disambiguator::Primitive,
1603 /// Used for error reporting.
1604 fn suggestion(self) -> Suggestion {
1605 let kind = match self {
1606 Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1607 Disambiguator::Kind(kind) => kind,
1608 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1610 if kind == DefKind::Macro(MacroKind::Bang) {
1611 return Suggestion::Macro;
1612 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1613 return Suggestion::Function;
1616 let prefix = match kind {
1617 DefKind::Struct => "struct",
1618 DefKind::Enum => "enum",
1619 DefKind::Trait => "trait",
1620 DefKind::Union => "union",
1621 DefKind::Mod => "mod",
1622 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1625 DefKind::Static => "static",
1626 DefKind::Macro(MacroKind::Derive) => "derive",
1627 // Now handle things that don't have a specific disambiguator
1630 .expect("tried to calculate a disambiguator for a def without a namespace?")
1632 Namespace::TypeNS => "type",
1633 Namespace::ValueNS => "value",
1634 Namespace::MacroNS => "macro",
1638 Suggestion::Prefix(prefix)
1641 fn ns(self) -> Namespace {
1643 Self::Namespace(n) => n,
1645 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1647 Self::Primitive => TypeNS,
1651 fn article(self) -> &'static str {
1653 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1654 Self::Kind(k) => k.article(),
1655 Self::Primitive => "a",
1659 fn descr(self) -> &'static str {
1661 Self::Namespace(n) => n.descr(),
1662 // HACK(jynelson): by looking at the source I saw the DefId we pass
1663 // for `expected.descr()` doesn't matter, since it's not a crate
1664 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1665 Self::Primitive => "builtin type",
1670 /// A suggestion to show in a diagnostic.
1673 Prefix(&'static str),
1681 fn descr(&self) -> Cow<'static, str> {
1683 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1684 Self::Function => "add parentheses".into(),
1685 Self::Macro => "add an exclamation mark".into(),
1689 fn as_help(&self, path_str: &str) -> String {
1690 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1692 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1693 Self::Function => format!("{}()", path_str),
1694 Self::Macro => format!("{}!", path_str),
1699 /// Reports a diagnostic for an intra-doc link.
1701 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1702 /// the entire documentation block is used for the lint. If a range is provided but the span
1703 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1705 /// The `decorate` callback is invoked in all cases to allow further customization of the
1706 /// diagnostic before emission. If the span of the link was able to be determined, the second
1707 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1709 fn report_diagnostic(
1711 lint: &'static Lint,
1713 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1714 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1716 let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1717 Some(hir_id) => hir_id,
1719 // If non-local, no need to check anything.
1720 info!("ignoring warning from parent crate: {}", msg);
1725 let sp = item.attr_span(tcx);
1727 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1728 let mut diag = lint.build(msg);
1730 let span = super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs);
1732 if let Some(sp) = span {
1735 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1738 // last_new_line_offset
1739 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1740 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1742 // Print the line containing the `link_range` and manually mark it with '^'s.
1744 "the link appears in this line:\n\n{line}\n\
1745 {indicator: <before$}{indicator:^<found$}",
1748 before = link_range.start - last_new_line_offset,
1749 found = link_range.len(),
1753 decorate(&mut diag, span);
1759 /// Reports a link that failed to resolve.
1761 /// This also tries to resolve any intermediate path segments that weren't
1762 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1763 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1764 fn resolution_failure(
1765 collector: &mut LinkCollector<'_, '_>,
1766 diag_info: DiagnosticInfo<'_>,
1768 disambiguator: Option<Disambiguator>,
1769 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1771 let tcx = collector.cx.tcx;
1774 BROKEN_INTRA_DOC_LINKS,
1775 &format!("unresolved link to `{}`", path_str),
1778 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1779 let assoc_item_not_allowed = |res: Res| {
1780 let name = res.name(tcx);
1782 "`{}` is {} {}, not a module or type, and cannot have associated items",
1788 // ignore duplicates
1789 let mut variants_seen = SmallVec::<[_; 3]>::new();
1790 for mut failure in kinds {
1791 let variant = std::mem::discriminant(&failure);
1792 if variants_seen.contains(&variant) {
1795 variants_seen.push(variant);
1797 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1802 let module_id = *module_id;
1803 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1804 // FIXME: maybe use itertools `collect_tuple` instead?
1805 fn split(path: &str) -> Option<(&str, &str)> {
1806 let mut splitter = path.rsplitn(2, "::");
1807 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1810 // Check if _any_ parent of the path gets resolved.
1811 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1812 let mut name = path_str;
1814 let (start, end) = if let Some(x) = split(name) {
1817 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1818 if partial_res.is_none() {
1819 *unresolved = name.into();
1824 for ns in [TypeNS, ValueNS, MacroNS] {
1826 collector.check_full_res(ns, &start, module_id.into(), &None)
1828 debug!("found partial_res={:?}", res);
1829 *partial_res = Some(res);
1830 *unresolved = end.into();
1834 *unresolved = end.into();
1837 let last_found_module = match *partial_res {
1838 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1839 None => Some(module_id),
1842 // See if this was a module: `[path]` or `[std::io::nope]`
1843 if let Some(module) = last_found_module {
1844 let note = if partial_res.is_some() {
1845 // Part of the link resolved; e.g. `std::io::nonexistent`
1846 let module_name = tcx.item_name(module);
1847 format!("no item named `{}` in module `{}`", unresolved, module_name)
1849 // None of the link resolved; e.g. `Notimported`
1850 format!("no item named `{}` in scope", unresolved)
1852 if let Some(span) = sp {
1853 diag.span_label(span, ¬e);
1858 // If the link has `::` in it, assume it was meant to be an intra-doc link.
1859 // Otherwise, the `[]` might be unrelated.
1860 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1861 if !path_str.contains("::") {
1862 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1868 // Otherwise, it must be an associated item or variant
1869 let res = partial_res.expect("None case was handled by `last_found_module`");
1870 let name = res.name(tcx);
1871 let kind = match res {
1872 Res::Def(kind, _) => Some(kind),
1873 Res::Primitive(_) => None,
1875 let path_description = if let Some(kind) = kind {
1877 Mod | ForeignMod => "inner item",
1878 Struct => "field or associated item",
1879 Enum | Union => "variant or associated item",
1896 let note = assoc_item_not_allowed(res);
1897 if let Some(span) = sp {
1898 diag.span_label(span, ¬e);
1904 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1905 | Static => "associated item",
1906 Impl | GlobalAsm => unreachable!("not a path"),
1912 "the {} `{}` has no {} named `{}`",
1915 disambiguator.map_or(path_description, |d| d.descr()),
1918 if let Some(span) = sp {
1919 diag.span_label(span, ¬e);
1926 let note = match failure {
1927 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1928 ResolutionFailure::Dummy => continue,
1929 ResolutionFailure::WrongNamespace { res, expected_ns } => {
1930 if let Res::Def(kind, _) = res {
1931 let disambiguator = Disambiguator::Kind(kind);
1932 suggest_disambiguator(
1938 &diag_info.link_range,
1943 "this link resolves to {}, which is not in the {} namespace",
1948 ResolutionFailure::NoParentItem => {
1949 diag.level = rustc_errors::Level::Bug;
1950 "all intra-doc links should have a parent item".to_owned()
1952 ResolutionFailure::MalformedGenerics(variant) => match variant {
1953 MalformedGenerics::UnbalancedAngleBrackets => {
1954 String::from("unbalanced angle brackets")
1956 MalformedGenerics::MissingType => {
1957 String::from("missing type for generic parameters")
1959 MalformedGenerics::HasFullyQualifiedSyntax => {
1960 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1961 String::from("fully-qualified syntax is unsupported")
1963 MalformedGenerics::InvalidPathSeparator => {
1964 String::from("has invalid path separator")
1966 MalformedGenerics::TooManyAngleBrackets => {
1967 String::from("too many angle brackets")
1969 MalformedGenerics::EmptyAngleBrackets => {
1970 String::from("empty angle brackets")
1974 if let Some(span) = sp {
1975 diag.span_label(span, ¬e);
1984 /// Report an anchor failure.
1985 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
1986 let (msg, anchor_idx) = match failure {
1987 AnchorFailure::MultipleAnchors => {
1988 (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
1990 AnchorFailure::RustdocAnchorConflict(res) => (
1992 "`{}` contains an anchor, but links to {kind}s are already anchored",
2000 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2001 if let Some(mut sp) = sp {
2002 if let Some((fragment_offset, _)) =
2003 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2005 sp = sp.with_lo(sp.lo() + rustc_span::BytePos(fragment_offset as _));
2007 diag.span_label(sp, "invalid anchor");
2009 if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2010 diag.note("this restriction may be lifted in a future release");
2011 diag.note("see https://github.com/rust-lang/rust/issues/83083 for more information");
2016 /// Report an error in the link disambiguator.
2017 fn disambiguator_error(
2018 cx: &DocContext<'_>,
2019 mut diag_info: DiagnosticInfo<'_>,
2020 disambiguator_range: Range<usize>,
2023 diag_info.link_range = disambiguator_range;
2024 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2026 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2027 crate::DOC_RUST_LANG_ORG_CHANNEL
2033 /// Report an ambiguity error, where there were multiple possible resolutions.
2035 cx: &DocContext<'_>,
2036 diag_info: DiagnosticInfo<'_>,
2038 candidates: Vec<Res>,
2040 let mut msg = format!("`{}` is ", path_str);
2042 match candidates.as_slice() {
2043 [first_def, second_def] => {
2045 "both {} {} and {} {}",
2046 first_def.article(),
2048 second_def.article(),
2053 let mut candidates = candidates.iter().peekable();
2054 while let Some(res) = candidates.next() {
2055 if candidates.peek().is_some() {
2056 msg += &format!("{} {}, ", res.article(), res.descr());
2058 msg += &format!("and {} {}", res.article(), res.descr());
2064 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2065 if let Some(sp) = sp {
2066 diag.span_label(sp, "ambiguous link");
2068 diag.note("ambiguous link");
2071 for res in candidates {
2072 let disambiguator = Disambiguator::from_res(res);
2073 suggest_disambiguator(
2079 &diag_info.link_range,
2085 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2087 fn suggest_disambiguator(
2088 disambiguator: Disambiguator,
2089 diag: &mut DiagnosticBuilder<'_>,
2092 sp: Option<rustc_span::Span>,
2093 link_range: &Range<usize>,
2095 let suggestion = disambiguator.suggestion();
2096 let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
2098 if let Some(sp) = sp {
2099 let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
2100 format!("`{}`", suggestion.as_help(path_str))
2102 suggestion.as_help(path_str)
2105 diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
2107 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2111 /// Report a link from a public item to a private one.
2112 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2114 let item_name = match diag_info.item.name {
2116 sym = name.as_str();
2119 None => "<unknown>",
2122 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2124 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2125 if let Some(sp) = sp {
2126 diag.span_label(sp, "this item is private");
2129 let note_msg = if cx.render_options.document_private {
2130 "this link resolves only because you passed `--document-private-items`, but will break without"
2132 "this link will resolve properly if you pass `--document-private-items`"
2134 diag.note(note_msg);
2138 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2140 cx: &DocContext<'_>,
2142 extra_fragment: &Option<String>,
2143 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
2144 use rustc_middle::ty::DefIdTree;
2146 if extra_fragment.is_some() {
2147 return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2150 .parent(res.def_id())
2152 let parent_def = Res::Def(DefKind::Enum, parent);
2153 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2154 (parent_def, Some(format!("variant.{}", variant.ident.name)))
2156 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2159 /// Resolve a primitive type or value.
2160 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2164 use PrimitiveType::*;
2165 let prim = match path_str {
2181 "bool" | "true" | "false" => Bool,
2182 "str" | "&str" => Str,
2183 // See #80181 for why these don't have symbols associated.
2188 "pointer" | "*const" | "*mut" => RawPointer,
2189 "reference" | "&" | "&mut" => Reference,
2191 "never" | "!" => Never,
2194 debug!("resolved primitives {:?}", prim);
2195 Some(Res::Primitive(prim))
2198 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2199 let mut stripped_segments = vec![];
2200 let mut path = path_str.chars().peekable();
2201 let mut segment = Vec::new();
2203 while let Some(chr) = path.next() {
2206 if path.next_if_eq(&':').is_some() {
2207 let stripped_segment =
2208 strip_generics_from_path_segment(mem::take(&mut segment))?;
2209 if !stripped_segment.is_empty() {
2210 stripped_segments.push(stripped_segment);
2213 return Err(ResolutionFailure::MalformedGenerics(
2214 MalformedGenerics::InvalidPathSeparator,
2223 return Err(ResolutionFailure::MalformedGenerics(
2224 MalformedGenerics::TooManyAngleBrackets,
2228 return Err(ResolutionFailure::MalformedGenerics(
2229 MalformedGenerics::EmptyAngleBrackets,
2235 while let Some(chr) = path.next_if(|c| *c != '>') {
2242 _ => segment.push(chr),
2244 trace!("raw segment: {:?}", segment);
2247 if !segment.is_empty() {
2248 let stripped_segment = strip_generics_from_path_segment(segment)?;
2249 if !stripped_segment.is_empty() {
2250 stripped_segments.push(stripped_segment);
2254 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2256 let stripped_path = stripped_segments.join("::");
2258 if !stripped_path.is_empty() {
2261 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2265 fn strip_generics_from_path_segment(
2267 ) -> Result<String, ResolutionFailure<'static>> {
2268 let mut stripped_segment = String::new();
2269 let mut param_depth = 0;
2271 let mut latest_generics_chunk = String::new();
2276 latest_generics_chunk.clear();
2277 } else if c == '>' {
2279 if latest_generics_chunk.contains(" as ") {
2280 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2281 // Give a helpful error message instead of completely ignoring the angle brackets.
2282 return Err(ResolutionFailure::MalformedGenerics(
2283 MalformedGenerics::HasFullyQualifiedSyntax,
2287 if param_depth == 0 {
2288 stripped_segment.push(c);
2290 latest_generics_chunk.push(c);
2295 if param_depth == 0 {
2296 Ok(stripped_segment)
2298 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2299 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))