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
5 use rustc_data_structures::{fx::FxHashMap, intern::Interned, stable_set::FxHashSet};
6 use rustc_errors::{Applicability, Diagnostic};
12 use rustc_hir::def_id::{DefId, CRATE_DEF_ID};
13 use rustc_hir::Mutability;
14 use rustc_middle::ty::{DefIdTree, Ty, TyCtxt};
15 use rustc_middle::{bug, span_bug, ty};
16 use rustc_session::lint::Lint;
17 use rustc_span::hygiene::MacroKind;
18 use rustc_span::symbol::{sym, Ident, Symbol};
19 use rustc_span::{BytePos, DUMMY_SP};
20 use smallvec::{smallvec, SmallVec};
22 use pulldown_cmark::LinkType;
25 use std::convert::{TryFrom, TryInto};
30 use crate::clean::{self, utils::find_nearest_parent_module};
31 use crate::clean::{Crate, Item, ItemId, ItemLink, PrimitiveType};
32 use crate::core::DocContext;
33 use crate::html::markdown::{markdown_links, MarkdownLink};
34 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
35 use crate::passes::Pass;
36 use crate::visit::DocVisitor;
39 crate use early::early_resolve_intra_doc_links;
41 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
42 name: "collect-intra-doc-links",
43 run: collect_intra_doc_links,
44 description: "resolves intra-doc links",
47 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
49 LinkCollector { cx, mod_ids: Vec::new(), visited_links: FxHashMap::default() };
50 collector.visit_crate(&krate);
54 /// Top-level errors emitted by this pass.
56 Resolve(Box<ResolutionFailure<'a>>),
57 AnchorFailure(AnchorFailure),
60 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
61 fn from(err: ResolutionFailure<'a>) -> Self {
62 ErrorKind::Resolve(box err)
66 #[derive(Copy, Clone, Debug, Hash)]
69 Primitive(PrimitiveType),
72 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
75 fn descr(self) -> &'static str {
77 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
78 Res::Primitive(_) => "builtin type",
82 fn article(self) -> &'static str {
84 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
85 Res::Primitive(_) => "a",
89 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
91 Res::Def(_, id) => tcx.item_name(id),
92 Res::Primitive(prim) => prim.as_sym(),
96 fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
98 Res::Def(_, id) => id,
99 Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
103 fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
105 Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
106 // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
107 Res::Primitive(_) => None,
111 /// Used for error reporting.
112 fn disambiguator_suggestion(self) -> Suggestion {
113 let kind = match self {
114 Res::Primitive(_) => return Suggestion::Prefix("prim"),
115 Res::Def(kind, _) => kind,
117 if kind == DefKind::Macro(MacroKind::Bang) {
118 return Suggestion::Macro;
119 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
120 return Suggestion::Function;
121 } else if kind == DefKind::Field {
122 return Suggestion::RemoveDisambiguator;
125 let prefix = match kind {
126 DefKind::Struct => "struct",
127 DefKind::Enum => "enum",
128 DefKind::Trait => "trait",
129 DefKind::Union => "union",
130 DefKind::Mod => "mod",
131 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
134 DefKind::Static(_) => "static",
135 DefKind::Macro(MacroKind::Derive) => "derive",
136 // Now handle things that don't have a specific disambiguator
139 .expect("tried to calculate a disambiguator for a def without a namespace?")
141 Namespace::TypeNS => "type",
142 Namespace::ValueNS => "value",
143 Namespace::MacroNS => "macro",
147 Suggestion::Prefix(prefix)
151 impl TryFrom<ResolveRes> for Res {
154 fn try_from(res: ResolveRes) -> Result<Self, ()> {
155 use rustc_hir::def::Res::*;
157 Def(kind, id) => Ok(Res::Def(kind, id)),
158 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
160 NonMacroAttr(..) | Err => Result::Err(()),
161 other => bug!("unrecognized res {:?}", other),
166 /// A link failed to resolve.
168 enum ResolutionFailure<'a> {
169 /// This resolved, but with the wrong namespace.
171 /// What the link resolved to.
173 /// The expected namespace for the resolution, determined from the link's disambiguator.
175 /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
176 /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
177 expected_ns: Namespace,
179 /// The link failed to resolve. [`resolution_failure`] should look to see if there's
180 /// a more helpful error that can be given.
182 /// Item on which the link is resolved, used for resolving `Self`.
184 /// The scope the link was resolved in.
186 /// If part of the link resolved, this has the `Res`.
188 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
189 partial_res: Option<Res>,
190 /// The remaining unresolved path segments.
192 /// In `[std::io::Error::x]`, `x` would be unresolved.
193 unresolved: Cow<'a, str>,
195 /// This happens when rustdoc can't determine the parent scope for an item.
196 /// It is always a bug in rustdoc.
198 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
199 MalformedGenerics(MalformedGenerics),
200 /// Used to communicate that this should be ignored, but shouldn't be reported to the user.
202 /// This happens when there is no disambiguator and one of the namespaces
203 /// failed to resolve.
208 enum MalformedGenerics {
209 /// This link has unbalanced angle brackets.
211 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
212 UnbalancedAngleBrackets,
213 /// The generics are not attached to a type.
215 /// For example, `<T>` should trigger this.
217 /// This is detected by checking if the path is empty after the generics are stripped.
219 /// The link uses fully-qualified syntax, which is currently unsupported.
221 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
223 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
225 HasFullyQualifiedSyntax,
226 /// The link has an invalid path separator.
228 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
229 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
232 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
233 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
234 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
236 /// This is detected by checking if there is a colon followed by a non-colon in the link.
237 InvalidPathSeparator,
238 /// The link has too many angle brackets.
240 /// For example, `Vec<<T>>` should trigger this.
241 TooManyAngleBrackets,
242 /// The link has empty angle brackets.
244 /// For example, `Vec<>` should trigger this.
248 impl ResolutionFailure<'_> {
249 /// This resolved fully (not just partially) but is erroneous for some other reason
251 /// Returns the full resolution of the link, if present.
252 fn full_res(&self) -> Option<Res> {
254 Self::WrongNamespace { res, expected_ns: _ } => Some(*res),
261 /// User error: `[std#x#y]` is not valid
263 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
265 /// This is an unfortunate state of affairs. Not every item that can be
266 /// linked to has its own page; sometimes it is a subheading within a page,
267 /// like for associated items. In those cases, rustdoc uses an anchor to
268 /// link to the subheading. Since you can't have two anchors for the same
269 /// link, Rustdoc disallows having a user-specified anchor.
271 /// Most of the time this is fine, because you can just link to the page of
272 /// the item if you want to provide your own anchor.
273 RustdocAnchorConflict(Res),
276 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
277 crate enum UrlFragment {
283 /// Render the fragment, including the leading `#`.
284 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
286 UrlFragment::Item(frag) => frag.render(s, tcx),
287 UrlFragment::UserWritten(raw) => write!(s, "#{}", raw),
292 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
293 crate struct ItemFragment(FragmentKind, DefId);
295 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
296 crate enum FragmentKind {
308 /// Create a fragment for an associated item.
309 #[instrument(level = "debug")]
310 fn from_assoc_item(item: &ty::AssocItem) -> Self {
311 let def_id = item.def_id;
313 ty::AssocKind::Fn => {
314 if item.defaultness.has_value() {
315 ItemFragment(FragmentKind::Method, def_id)
317 ItemFragment(FragmentKind::TyMethod, def_id)
320 ty::AssocKind::Const => ItemFragment(FragmentKind::AssociatedConstant, def_id),
321 ty::AssocKind::Type => ItemFragment(FragmentKind::AssociatedType, def_id),
325 /// Render the fragment, including the leading `#`.
326 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
329 ItemFragment(kind, def_id) => {
330 let name = tcx.item_name(def_id);
332 FragmentKind::Method => write!(s, "method.{}", name),
333 FragmentKind::TyMethod => write!(s, "tymethod.{}", name),
334 FragmentKind::AssociatedConstant => write!(s, "associatedconstant.{}", name),
335 FragmentKind::AssociatedType => write!(s, "associatedtype.{}", name),
336 FragmentKind::StructField => write!(s, "structfield.{}", name),
337 FragmentKind::Variant => write!(s, "variant.{}", name),
338 FragmentKind::VariantField => {
339 let variant = tcx.item_name(tcx.parent(def_id).unwrap());
340 write!(s, "variant.{}.field.{}", variant, name)
348 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
349 struct ResolutionInfo {
352 dis: Option<Disambiguator>,
354 extra_fragment: Option<String>,
358 struct DiagnosticInfo<'a> {
362 link_range: Range<usize>,
365 #[derive(Clone, Debug, Hash)]
367 res: (Res, Option<UrlFragment>),
370 struct LinkCollector<'a, 'tcx> {
371 cx: &'a mut DocContext<'tcx>,
372 /// A stack of modules used to decide what scope to resolve in.
374 /// The last module will be used if the parent scope of the current item is
377 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
378 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
379 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
382 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
383 /// Given a full link, parse it as an [enum struct variant].
385 /// In particular, this will return an error whenever there aren't three
386 /// full path segments left in the link.
388 /// [enum struct variant]: rustc_hir::VariantData::Struct
389 fn variant_field<'path>(
391 path_str: &'path str,
394 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
395 let tcx = self.cx.tcx;
396 let no_res = || ResolutionFailure::NotResolved {
400 unresolved: path_str.into(),
403 debug!("looking for enum variant {}", path_str);
404 let mut split = path_str.rsplitn(3, "::");
405 let variant_field_name = split
407 .map(|f| Symbol::intern(f))
408 .expect("fold_item should ensure link is non-empty");
410 // we're not sure this is a variant at all, so use the full string
411 // If there's no second component, the link looks like `[path]`.
412 // So there's no partial res and we should say the whole link failed to resolve.
413 split.next().map(|f| Symbol::intern(f)).ok_or_else(no_res)?;
416 .map(|f| f.to_owned())
417 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
418 // So there's no partial res.
419 .ok_or_else(no_res)?;
420 let ty_res = self.resolve_path(&path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
423 Res::Def(DefKind::Enum, did) => {
427 .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
428 .any(|item| item.name == variant_name)
430 // This is just to let `fold_item` know that this shouldn't be considered;
431 // it's a bug for the error to make it to the user
432 return Err(ResolutionFailure::Dummy.into());
434 match tcx.type_of(did).kind() {
435 ty::Adt(def, _) if def.is_enum() => {
436 if let Some(field) = def.all_fields().find(|f| f.name == variant_field_name)
438 Ok((ty_res, Some(ItemFragment(FragmentKind::VariantField, field.did))))
440 Err(ResolutionFailure::NotResolved {
443 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
444 unresolved: variant_field_name.to_string().into(),
452 _ => Err(ResolutionFailure::NotResolved {
455 partial_res: Some(ty_res),
456 unresolved: variant_name.to_string().into(),
462 /// Given a primitive type, try to resolve an associated item.
463 fn resolve_primitive_associated_item(
465 prim_ty: PrimitiveType,
468 ) -> Option<(Res, ItemFragment)> {
469 let tcx = self.cx.tcx;
471 prim_ty.impls(tcx).find_map(|impl_| {
472 tcx.associated_items(impl_)
473 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
475 let fragment = ItemFragment::from_assoc_item(item);
476 (Res::Primitive(prim_ty), fragment)
481 /// Resolves a string as a macro.
483 /// FIXME(jynelson): Can this be unified with `resolve()`?
489 ) -> Result<Res, ResolutionFailure<'a>> {
490 self.cx.enter_resolver(|resolver| {
491 // NOTE: this needs 2 separate lookups because `resolve_rustdoc_path` doesn't take
492 // lexical scope into account (it ignores all macros not defined at the mod-level)
493 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
494 if let Some(res) = resolver.resolve_rustdoc_path(path_str, MacroNS, module_id) {
495 // don't resolve builtins like `#[derive]`
496 if let Ok(res) = res.try_into() {
500 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
501 return Ok(res.try_into().unwrap());
503 Err(ResolutionFailure::NotResolved {
507 unresolved: path_str.into(),
512 fn resolve_self_ty(&self, path_str: &str, ns: Namespace, item_id: ItemId) -> Option<Res> {
513 if ns != TypeNS || path_str != "Self" {
517 let tcx = self.cx.tcx;
520 .map(|def_id| match tcx.def_kind(def_id) {
521 def_kind @ (DefKind::AssocFn
522 | DefKind::AssocConst
525 | DefKind::Field) => {
526 let parent_def_id = tcx.parent(def_id).expect("nested item has no parent");
527 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant
529 tcx.parent(parent_def_id).expect("variant has no parent")
536 .and_then(|self_id| match tcx.def_kind(self_id) {
537 DefKind::Impl => self.def_id_to_res(self_id),
538 def_kind => Some(Res::Def(def_kind, self_id)),
542 /// Convenience wrapper around `resolve_rustdoc_path`.
544 /// This also handles resolving `true` and `false` as booleans.
545 /// NOTE: `resolve_rustdoc_path` knows only about paths, not about types.
546 /// Associated items will never be resolved by this function.
554 if let res @ Some(..) = self.resolve_self_ty(path_str, ns, item_id) {
558 // Resolver doesn't know about true, false, and types that aren't paths (e.g. `()`).
561 .enter_resolver(|resolver| resolver.resolve_rustdoc_path(path_str, ns, module_id))
562 .and_then(|res| res.try_into().ok())
563 .or_else(|| resolve_primitive(path_str, ns));
564 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
568 /// Resolves a string as a path within a particular namespace. Returns an
569 /// optional URL fragment in the case of variants and methods.
572 path_str: &'path str,
576 user_fragment: &Option<String>,
577 ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'path>> {
578 let (res, rustdoc_fragment) = self.resolve_inner(path_str, ns, item_id, module_id)?;
579 let chosen_fragment = match (user_fragment, rustdoc_fragment) {
580 (Some(_), Some(r_frag)) => {
581 let diag_res = match r_frag {
582 ItemFragment(_, did) => Res::Def(self.cx.tcx.def_kind(did), did),
584 let failure = AnchorFailure::RustdocAnchorConflict(diag_res);
585 return Err(ErrorKind::AnchorFailure(failure));
587 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
588 (None, Some(r_frag)) => Some(UrlFragment::Item(r_frag)),
589 (None, None) => None,
591 Ok((res, chosen_fragment))
594 fn resolve_inner<'path>(
596 path_str: &'path str,
600 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
601 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
603 // FIXME(#76467): make this fallthrough to lookup the associated
604 // item a separate function.
605 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
606 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
607 Res::Def(DefKind::Variant, _) => {
608 return handle_variant(self.cx, res);
610 // Not a trait item; just return what we found.
611 _ => return Ok((res, None)),
615 // Try looking for methods and associated items.
616 let mut split = path_str.rsplitn(2, "::");
617 // NB: `split`'s first element is always defined, even if the delimiter was not present.
618 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
619 let item_str = split.next().unwrap();
620 let item_name = Symbol::intern(item_str);
621 let path_root = split
623 .map(|f| f.to_owned())
624 // If there's no `::`, it's not an associated item.
625 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
627 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
628 ResolutionFailure::NotResolved {
632 unresolved: item_str.into(),
636 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
637 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
638 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
640 resolve_primitive(&path_root, TypeNS)
641 .or_else(|| self.resolve_path(&path_root, TypeNS, item_id, module_id))
643 let (res, fragment) =
644 self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
646 Some(Ok((res, Some(fragment))))
649 if ns == Namespace::ValueNS {
650 self.variant_field(path_str, item_id, module_id)
652 Err(ResolutionFailure::NotResolved {
656 unresolved: path_root.into(),
663 /// Convert a DefId to a Res, where possible.
665 /// This is used for resolving type aliases.
666 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
667 use PrimitiveType::*;
668 Some(match *self.cx.tcx.type_of(ty_id).kind() {
669 ty::Bool => Res::Primitive(Bool),
670 ty::Char => Res::Primitive(Char),
671 ty::Int(ity) => Res::Primitive(ity.into()),
672 ty::Uint(uty) => Res::Primitive(uty.into()),
673 ty::Float(fty) => Res::Primitive(fty.into()),
674 ty::Str => Res::Primitive(Str),
675 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
676 ty::Tuple(_) => Res::Primitive(Tuple),
677 ty::Array(..) => Res::Primitive(Array),
678 ty::Slice(_) => Res::Primitive(Slice),
679 ty::RawPtr(_) => Res::Primitive(RawPointer),
680 ty::Ref(..) => Res::Primitive(Reference),
681 ty::FnDef(..) => panic!("type alias to a function definition"),
682 ty::FnPtr(_) => Res::Primitive(Fn),
683 ty::Never => Res::Primitive(Never),
684 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
685 Res::Def(self.cx.tcx.def_kind(did), did)
690 | ty::GeneratorWitness(_)
697 | ty::Error(_) => return None,
701 /// Convert a PrimitiveType to a Ty, where possible.
703 /// This is used for resolving trait impls for primitives
704 fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
705 use PrimitiveType::*;
706 let tcx = self.cx.tcx;
708 // FIXME: Only simple types are supported here, see if we can support
709 // other types such as Tuple, Array, Slice, etc.
710 // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
711 Some(tcx.mk_ty(match prim {
716 I8 => ty::Int(ty::IntTy::I8),
717 I16 => ty::Int(ty::IntTy::I16),
718 I32 => ty::Int(ty::IntTy::I32),
719 I64 => ty::Int(ty::IntTy::I64),
720 I128 => ty::Int(ty::IntTy::I128),
721 Isize => ty::Int(ty::IntTy::Isize),
722 F32 => ty::Float(ty::FloatTy::F32),
723 F64 => ty::Float(ty::FloatTy::F64),
724 U8 => ty::Uint(ty::UintTy::U8),
725 U16 => ty::Uint(ty::UintTy::U16),
726 U32 => ty::Uint(ty::UintTy::U32),
727 U64 => ty::Uint(ty::UintTy::U64),
728 U128 => ty::Uint(ty::UintTy::U128),
729 Usize => ty::Uint(ty::UintTy::Usize),
734 /// Resolve an associated item, returning its containing page's `Res`
735 /// and the fragment targeting the associated item on its page.
736 fn resolve_associated_item(
742 ) -> Option<(Res, ItemFragment)> {
743 let tcx = self.cx.tcx;
746 Res::Primitive(prim) => {
747 self.resolve_primitive_associated_item(prim, ns, item_name).or_else(|| {
748 let assoc_item = self
749 .primitive_type_to_ty(prim)
751 resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
755 assoc_item.map(|item| {
756 let fragment = ItemFragment::from_assoc_item(&item);
761 Res::Def(DefKind::TyAlias, did) => {
762 // Resolve the link on the type the alias points to.
763 // FIXME: if the associated item is defined directly on the type alias,
764 // it will show up on its documentation page, we should link there instead.
765 let res = self.def_id_to_res(did)?;
766 self.resolve_associated_item(res, item_name, ns, module_id)
769 def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
772 debug!("looking for associated item named {} for item {:?}", item_name, did);
773 // Checks if item_name is a variant of the `SomeItem` enum
774 if ns == TypeNS && def_kind == DefKind::Enum {
775 match tcx.type_of(did).kind() {
776 ty::Adt(adt_def, _) => {
777 for variant in adt_def.variants() {
778 if variant.name == item_name {
781 ItemFragment(FragmentKind::Variant, variant.def_id),
790 // Checks if item_name belongs to `impl SomeItem`
795 tcx.associated_items(imp).find_by_name_and_namespace(
797 Ident::with_dummy_span(item_name),
803 // There should only ever be one associated item that matches from any inherent impl
805 // Check if item_name belongs to `impl SomeTrait for SomeItem`
806 // FIXME(#74563): This gives precedence to `impl SomeItem`:
807 // Although having both would be ambiguous, use impl version for compatibility's sake.
808 // To handle that properly resolve() would have to support
809 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
811 resolve_associated_trait_item(
820 debug!("got associated item {:?}", assoc_item);
822 if let Some(item) = assoc_item {
823 let fragment = ItemFragment::from_assoc_item(&item);
824 return Some((root_res, fragment));
827 if ns != Namespace::ValueNS {
830 debug!("looking for fields named {} for {:?}", item_name, did);
831 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
832 // NOTE: it's different from variant_field because it only resolves struct fields,
833 // not variant fields (2 path segments, not 3).
835 // We need to handle struct (and union) fields in this code because
836 // syntactically their paths are identical to associated item paths:
837 // `module::Type::field` and `module::Type::Assoc`.
839 // On the other hand, variant fields can't be mistaken for associated
840 // items because they look like this: `module::Type::Variant::field`.
842 // Variants themselves don't need to be handled here, even though
843 // they also look like associated items (`module::Type::Variant`),
844 // because they are real Rust syntax (unlike the intra-doc links
845 // field syntax) and are handled by the compiler's resolver.
846 let def = match tcx.type_of(did).kind() {
847 ty::Adt(def, _) if !def.is_enum() => def,
851 def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?;
852 Some((root_res, ItemFragment(FragmentKind::StructField, field.did)))
854 Res::Def(DefKind::Trait, did) => tcx
855 .associated_items(did)
856 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
858 let fragment = ItemFragment::from_assoc_item(item);
859 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
866 /// Used for reporting better errors.
868 /// Returns whether the link resolved 'fully' in another namespace.
869 /// 'fully' here means that all parts of the link resolved, not just some path segments.
870 /// This returns the `Res` even if it was erroneous for some reason
871 /// (such as having invalid URL fragments or being in the wrong namespace).
878 extra_fragment: &Option<String>,
880 // resolve() can't be used for macro namespace
881 let result = match ns {
882 Namespace::MacroNS => self
883 .resolve_macro(path_str, item_id, module_id)
884 .map(|res| (res, None))
885 .map_err(ErrorKind::from),
886 Namespace::TypeNS | Namespace::ValueNS => {
887 self.resolve(path_str, ns, item_id, module_id, extra_fragment)
891 let res = match result {
893 if let Some(UrlFragment::Item(ItemFragment(_, id))) = frag {
894 Some(Res::Def(self.cx.tcx.def_kind(id), id))
899 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
900 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
901 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
907 /// Look to see if a resolved item has an associated item named `item_name`.
909 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
910 /// find `std::error::Error::source` and return
911 /// `<io::Error as error::Error>::source`.
912 fn resolve_associated_trait_item<'a>(
917 cx: &mut DocContext<'a>,
918 ) -> Option<ty::AssocItem> {
919 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
920 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
921 // meantime, just don't look for these blanket impls.
923 // Next consider explicit impls: `impl MyTrait for MyType`
924 // Give precedence to inherent impls.
925 let traits = trait_impls_for(cx, ty, module);
926 debug!("considering traits {:?}", traits);
927 let mut candidates = traits.iter().filter_map(|&(impl_, trait_)| {
929 .associated_items(trait_)
930 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
932 trait_assoc_to_impl_assoc_item(cx.tcx, impl_, trait_assoc.def_id)
933 .unwrap_or(trait_assoc)
936 // FIXME(#74563): warn about ambiguity
937 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
938 candidates.next().copied()
941 /// Find the associated item in the impl `impl_id` that corresponds to the
942 /// trait associated item `trait_assoc_id`.
944 /// This function returns `None` if no associated item was found in the impl.
945 /// This can occur when the trait associated item has a default value that is
946 /// not overridden in the impl.
948 /// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
949 /// [`TyCtxt::associated_item()`] (with some helpful logging added).
950 #[instrument(level = "debug", skip(tcx))]
951 fn trait_assoc_to_impl_assoc_item<'tcx>(
954 trait_assoc_id: DefId,
955 ) -> Option<&'tcx ty::AssocItem> {
956 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
957 debug!(?trait_to_impl_assoc_map);
958 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
959 debug!(?impl_assoc_id);
960 let impl_assoc = tcx.associated_item(impl_assoc_id);
965 /// Given a type, return all trait impls in scope in `module` for that type.
966 /// Returns a set of pairs of `(impl_id, trait_id)`.
968 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
969 /// So it is not stable to serialize cross-crate.
970 #[instrument(level = "debug", skip(cx))]
971 fn trait_impls_for<'a>(
972 cx: &mut DocContext<'a>,
975 ) -> FxHashSet<(DefId, DefId)> {
977 let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
978 let trait_ = trait_candidate.def_id;
979 trace!("considering explicit impl for trait {:?}", trait_);
981 // Look at each trait implementation to see if it's an impl for `did`
982 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
983 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
984 // Check if these are the same type.
985 let impl_type = trait_ref.self_ty();
987 "comparing type {} with kind {:?} against type {:?}",
992 // Fast path: if this is a primitive simple `==` will work
993 // NOTE: the `match` is necessary; see #92662.
994 // this allows us to ignore generics because the user input
995 // may not include the generic placeholders
996 // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
997 let saw_impl = impl_type == ty
998 || match (impl_type.kind(), ty.kind()) {
999 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
1000 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
1001 impl_def.did() == ty_def.did()
1006 if saw_impl { Some((impl_, trait_)) } else { None }
1012 /// Check for resolve collisions between a trait and its derive.
1014 /// These are common and we should just resolve to the trait in that case.
1015 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
1019 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
1020 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
1026 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
1027 fn visit_item(&mut self, item: &Item) {
1029 item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
1030 if parent_node.is_some() {
1031 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
1034 let inner_docs = item.inner_docs(self.cx.tcx);
1036 if item.is_mod() && inner_docs {
1037 self.mod_ids.push(item.def_id.expect_def_id());
1040 // We want to resolve in the lexical scope of the documentation.
1041 // In the presence of re-exports, this is not the same as the module of the item.
1042 // Rather than merging all documentation into one, resolve it one attribute at a time
1043 // so we know which module it came from.
1044 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
1045 debug!("combined_docs={}", doc);
1046 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1047 // This is a degenerate case and it's not supported by rustdoc.
1048 let parent_node = parent_module.or(parent_node);
1049 for md_link in markdown_links(&doc) {
1050 let link = self.resolve_link(&item, &doc, parent_node, md_link);
1051 if let Some(link) = link {
1052 self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
1059 self.mod_ids.push(item.def_id.expect_def_id());
1062 self.visit_item_recur(item);
1065 self.visit_item_recur(item)
1070 enum PreprocessingError<'a> {
1071 Anchor(AnchorFailure),
1072 Disambiguator(Range<usize>, String),
1073 Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
1076 impl From<AnchorFailure> for PreprocessingError<'_> {
1077 fn from(err: AnchorFailure) -> Self {
1082 struct PreprocessingInfo {
1084 disambiguator: Option<Disambiguator>,
1085 extra_fragment: Option<String>,
1090 /// - `None` if the link should be ignored.
1091 /// - `Some(Err)` if the link should emit an error
1092 /// - `Some(Ok)` if the link is valid
1094 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
1095 fn preprocess_link<'a>(
1096 ori_link: &'a MarkdownLink,
1097 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
1098 // [] is mostly likely not supposed to be a link
1099 if ori_link.link.is_empty() {
1103 // Bail early for real links.
1104 if ori_link.link.contains('/') {
1108 let stripped = ori_link.link.replace('`', "");
1109 let mut parts = stripped.split('#');
1111 let link = parts.next().unwrap();
1112 if link.trim().is_empty() {
1113 // This is an anchor to an element of the current page, nothing to do in here!
1116 let extra_fragment = parts.next();
1117 if parts.next().is_some() {
1118 // A valid link can't have multiple #'s
1119 return Some(Err(AnchorFailure::MultipleAnchors.into()));
1122 // Parse and strip the disambiguator from the link, if present.
1123 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1124 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1125 Ok(None) => (None, link.trim(), link.trim()),
1126 Err((err_msg, relative_range)) => {
1127 // Only report error if we would not have ignored this link. See issue #83859.
1128 if !should_ignore_link_with_disambiguators(link) {
1129 let no_backticks_range = range_between_backticks(ori_link);
1130 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1131 ..(no_backticks_range.start + relative_range.end);
1132 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1139 if should_ignore_link(path_str) {
1143 // Strip generics from the path.
1144 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1145 match strip_generics_from_path(path_str) {
1148 debug!("link has malformed generics: {}", path_str);
1149 return Some(Err(PreprocessingError::Resolution(
1151 path_str.to_owned(),
1160 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1161 assert!(!path_str.contains(['<', '>'].as_slice()));
1163 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1164 if path_str.contains(' ') {
1168 Some(Ok(PreprocessingInfo {
1171 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1172 link_text: link_text.to_owned(),
1176 impl LinkCollector<'_, '_> {
1177 /// This is the entry point for resolving an intra-doc link.
1179 /// FIXME(jynelson): this is way too many arguments
1184 parent_node: Option<DefId>,
1185 ori_link: MarkdownLink,
1186 ) -> Option<ItemLink> {
1187 trace!("considering link '{}'", ori_link.link);
1189 let diag_info = DiagnosticInfo {
1192 ori_link: &ori_link.link,
1193 link_range: ori_link.range.clone(),
1196 let PreprocessingInfo { ref path_str, disambiguator, extra_fragment, link_text } =
1197 match preprocess_link(&ori_link)? {
1201 PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1202 PreprocessingError::Disambiguator(range, msg) => {
1203 disambiguator_error(self.cx, diag_info, range, &msg)
1205 PreprocessingError::Resolution(err, path_str, disambiguator) => {
1219 let inner_docs = item.inner_docs(self.cx.tcx);
1221 // In order to correctly resolve intra-doc links we need to
1222 // pick a base AST node to work from. If the documentation for
1223 // this module came from an inner comment (//!) then we anchor
1224 // our name resolution *inside* the module. If, on the other
1225 // hand it was an outer comment (///) then we anchor the name
1226 // resolution in the parent module on the basis that the names
1227 // used are more likely to be intended to be parent names. For
1228 // this, we set base_node to None for inner comments since
1229 // we've already pushed this node onto the resolution stack but
1230 // for outer comments we explicitly try and resolve against the
1231 // parent_node first.
1233 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1235 let Some(module_id) = base_node else {
1237 debug!("attempting to resolve item without parent module: {}", path_str);
1243 smallvec![ResolutionFailure::NoParentItem],
1248 let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1250 item_id: item.def_id,
1253 path_str: path_str.to_owned(),
1256 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1257 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1260 // Check for a primitive which might conflict with a module
1261 // Report the ambiguity and require that the user specify which one they meant.
1262 // FIXME: could there ever be a primitive not in the type namespace?
1265 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1266 ) && !matches!(res, Res::Primitive(_))
1268 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1270 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1273 // `[char]` when a `char` module is in scope
1274 let candidates = vec![res, prim];
1275 ambiguity_error(self.cx, diag_info, path_str, candidates);
1282 Res::Primitive(prim) => {
1283 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1284 // We're actually resolving an associated item of a primitive, so we need to
1285 // verify the disambiguator (if any) matches the type of the associated item.
1286 // This case should really follow the same flow as the `Res::Def` branch below,
1287 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1288 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1289 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1290 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1291 // for discussion on the matter.
1292 let kind = self.cx.tcx.def_kind(id);
1293 self.verify_disambiguator(
1303 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1304 // However I'm not sure how to check that across crates.
1305 if prim == PrimitiveType::RawPointer
1306 && item.def_id.is_local()
1307 && !self.cx.tcx.features().intra_doc_pointers
1309 self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1312 match disambiguator {
1313 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1315 self.report_disambiguator_mismatch(
1316 path_str, &ori_link, other, res, &diag_info,
1324 link: ori_link.link,
1326 did: res.def_id(self.cx.tcx),
1330 Res::Def(kind, id) => {
1331 let (kind_for_dis, id_for_dis) =
1332 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1333 (self.cx.tcx.def_kind(id), id)
1337 self.verify_disambiguator(
1346 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1347 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1352 fn verify_disambiguator(
1355 ori_link: &MarkdownLink,
1358 disambiguator: Option<Disambiguator>,
1360 diag_info: &DiagnosticInfo<'_>,
1362 debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1364 // Disallow e.g. linking to enums with `struct@`
1365 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1366 match (kind, disambiguator) {
1367 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1368 // NOTE: this allows 'method' to mean both normal functions and associated functions
1369 // This can't cause ambiguity because both are in the same namespace.
1370 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1371 // These are namespaces; allow anything in the namespace to match
1372 | (_, Some(Disambiguator::Namespace(_)))
1373 // If no disambiguator given, allow anything
1375 // All of these are valid, so do nothing
1377 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1378 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1379 self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1384 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1385 if let Some((src_id, dst_id)) = id
1387 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1388 // would presumably panic if a fake `DefIndex` were passed.
1389 .and_then(|dst_id| {
1390 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1393 if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1394 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1396 privacy_error(self.cx, diag_info, path_str);
1403 fn report_disambiguator_mismatch(
1406 ori_link: &MarkdownLink,
1407 specified: Disambiguator,
1409 diag_info: &DiagnosticInfo<'_>,
1411 // The resolved item did not match the disambiguator; give a better error than 'not found'
1412 let msg = format!("incompatible link kind for `{}`", path_str);
1413 let callback = |diag: &mut Diagnostic, sp: Option<rustc_span::Span>| {
1415 "this link resolved to {} {}, which is not {} {}",
1418 specified.article(),
1421 if let Some(sp) = sp {
1422 diag.span_label(sp, ¬e);
1426 suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1428 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1431 fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1433 super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1434 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1435 rustc_session::parse::feature_err(
1436 &self.cx.tcx.sess.parse_sess,
1437 sym::intra_doc_pointers,
1439 "linking to associated items of raw pointers is experimental",
1441 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1445 fn resolve_with_disambiguator_cached(
1447 key: ResolutionInfo,
1448 diag: DiagnosticInfo<'_>,
1449 cache_resolution_failure: bool,
1450 ) -> Option<(Res, Option<UrlFragment>)> {
1451 if let Some(ref cached) = self.visited_links.get(&key) {
1454 return Some(cached.res.clone());
1456 None if cache_resolution_failure => return None,
1458 // Although we hit the cache and found a resolution error, this link isn't
1459 // supposed to cache those. Run link resolution again to emit the expected
1460 // resolution error.
1465 let res = self.resolve_with_disambiguator(&key, diag);
1467 // Cache only if resolved successfully - don't silence duplicate errors
1468 if let Some(res) = res {
1469 // Store result for the actual namespace
1470 self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1474 if cache_resolution_failure {
1475 // For reference-style links we only want to report one resolution error
1476 // so let's cache them as well.
1477 self.visited_links.insert(key, None);
1484 /// After parsing the disambiguator, resolve the main part of the link.
1485 // FIXME(jynelson): wow this is just so much
1486 fn resolve_with_disambiguator(
1488 key: &ResolutionInfo,
1489 diag: DiagnosticInfo<'_>,
1490 ) -> Option<(Res, Option<UrlFragment>)> {
1491 let disambiguator = key.dis;
1492 let path_str = &key.path_str;
1493 let item_id = key.item_id;
1494 let base_node = key.module_id;
1495 let extra_fragment = &key.extra_fragment;
1497 match disambiguator.map(Disambiguator::ns) {
1498 Some(expected_ns @ (ValueNS | TypeNS)) => {
1499 match self.resolve(path_str, expected_ns, item_id, base_node, extra_fragment) {
1500 Ok(res) => Some(res),
1501 Err(ErrorKind::Resolve(box mut kind)) => {
1502 // We only looked in one namespace. Try to give a better error if possible.
1503 if kind.full_res().is_none() {
1504 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1505 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1506 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1507 for new_ns in [other_ns, MacroNS] {
1508 if let Some(res) = self.check_full_res(
1515 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1520 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1521 // This could just be a normal link or a broken link
1522 // we could potentially check if something is
1523 // "intra-doc-link-like" and warn in that case.
1526 Err(ErrorKind::AnchorFailure(msg)) => {
1527 anchor_failure(self.cx, diag, msg);
1534 let mut candidates = PerNS {
1536 .resolve_macro(path_str, item_id, base_node)
1537 .map(|res| (res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1538 type_ns: match self.resolve(
1546 debug!("got res in TypeNS: {:?}", res);
1549 Err(ErrorKind::AnchorFailure(msg)) => {
1550 anchor_failure(self.cx, diag, msg);
1553 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1555 value_ns: match self.resolve(
1563 Err(ErrorKind::AnchorFailure(msg)) => {
1564 anchor_failure(self.cx, diag, msg);
1567 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1569 .and_then(|(res, fragment)| {
1570 // Constructors are picked up in the type namespace.
1572 Res::Def(DefKind::Ctor(..), _) => {
1573 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1576 match (fragment, extra_fragment.clone()) {
1577 (Some(fragment), Some(_)) => {
1578 // Shouldn't happen but who knows?
1579 Ok((res, Some(fragment)))
1581 (fragment, None) => Ok((res, fragment)),
1582 (None, fragment) => {
1583 Ok((res, fragment.map(UrlFragment::UserWritten)))
1591 let len = candidates.iter().filter(|res| res.is_ok()).count();
1599 candidates.into_iter().filter_map(|res| res.err()).collect(),
1601 // this could just be a normal link
1606 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1607 } else if len == 2 && is_derive_trait_collision(&candidates) {
1608 Some(candidates.type_ns.unwrap())
1610 if is_derive_trait_collision(&candidates) {
1611 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1613 // If we're reporting an ambiguity, don't mention the namespaces that failed
1614 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1615 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1620 match self.resolve_macro(path_str, item_id, base_node) {
1621 Ok(res) => Some((res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1623 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1624 for ns in [TypeNS, ValueNS] {
1625 if let Some(res) = self.check_full_res(
1633 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1637 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1646 /// Get the section of a link between the backticks,
1647 /// or the whole link if there aren't any backticks.
1655 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1656 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1657 let before_second_backtick_group = ori_link
1660 .skip(after_first_backtick_group)
1661 .position(|b| b == b'`')
1662 .unwrap_or(ori_link.link.len());
1663 (ori_link.range.start + after_first_backtick_group)
1664 ..(ori_link.range.start + before_second_backtick_group)
1667 /// Returns true if we should ignore `link` due to it being unlikely
1668 /// that it is an intra-doc link. `link` should still have disambiguators
1669 /// if there were any.
1671 /// The difference between this and [`should_ignore_link()`] is that this
1672 /// check should only be used on links that still have disambiguators.
1673 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1674 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1677 /// Returns true if we should ignore `path_str` due to it being unlikely
1678 /// that it is an intra-doc link.
1679 fn should_ignore_link(path_str: &str) -> bool {
1680 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1683 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1684 /// Disambiguators for a link.
1685 enum Disambiguator {
1688 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1690 /// `struct@` or `f()`
1693 Namespace(Namespace),
1696 impl Disambiguator {
1697 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1699 /// This returns `Ok(Some(...))` if a disambiguator was found,
1700 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1701 /// if there was a problem with the disambiguator.
1702 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1703 use Disambiguator::{Kind, Namespace as NS, Primitive};
1705 if let Some(idx) = link.find('@') {
1706 let (prefix, rest) = link.split_at(idx);
1707 let d = match prefix {
1708 "struct" => Kind(DefKind::Struct),
1709 "enum" => Kind(DefKind::Enum),
1710 "trait" => Kind(DefKind::Trait),
1711 "union" => Kind(DefKind::Union),
1712 "module" | "mod" => Kind(DefKind::Mod),
1713 "const" | "constant" => Kind(DefKind::Const),
1714 "static" => Kind(DefKind::Static(Mutability::Not)),
1715 "function" | "fn" | "method" => Kind(DefKind::Fn),
1716 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1717 "type" => NS(Namespace::TypeNS),
1718 "value" => NS(Namespace::ValueNS),
1719 "macro" => NS(Namespace::MacroNS),
1720 "prim" | "primitive" => Primitive,
1721 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1723 Ok(Some((d, &rest[1..], &rest[1..])))
1726 ("!()", DefKind::Macro(MacroKind::Bang)),
1727 ("!{}", DefKind::Macro(MacroKind::Bang)),
1728 ("![]", DefKind::Macro(MacroKind::Bang)),
1729 ("()", DefKind::Fn),
1730 ("!", DefKind::Macro(MacroKind::Bang)),
1732 for (suffix, kind) in suffixes {
1733 if let Some(path_str) = link.strip_suffix(suffix) {
1734 // Avoid turning `!` or `()` into an empty string
1735 if !path_str.is_empty() {
1736 return Ok(Some((Kind(kind), path_str, link)));
1744 fn ns(self) -> Namespace {
1746 Self::Namespace(n) => n,
1748 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1750 Self::Primitive => TypeNS,
1754 fn article(self) -> &'static str {
1756 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1757 Self::Kind(k) => k.article(),
1758 Self::Primitive => "a",
1762 fn descr(self) -> &'static str {
1764 Self::Namespace(n) => n.descr(),
1765 // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1766 // printing "module" vs "crate" so using the wrong ID is not a huge problem
1767 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1768 Self::Primitive => "builtin type",
1773 /// A suggestion to show in a diagnostic.
1776 Prefix(&'static str),
1781 /// `foo` without any disambiguator
1782 RemoveDisambiguator,
1786 fn descr(&self) -> Cow<'static, str> {
1788 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1789 Self::Function => "add parentheses".into(),
1790 Self::Macro => "add an exclamation mark".into(),
1791 Self::RemoveDisambiguator => "remove the disambiguator".into(),
1795 fn as_help(&self, path_str: &str) -> String {
1796 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1798 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1799 Self::Function => format!("{}()", path_str),
1800 Self::Macro => format!("{}!", path_str),
1801 Self::RemoveDisambiguator => path_str.into(),
1809 sp: rustc_span::Span,
1810 ) -> Vec<(rustc_span::Span, String)> {
1811 let inner_sp = match ori_link.find('(') {
1812 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1815 let inner_sp = match ori_link.find('!') {
1816 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1819 let inner_sp = match ori_link.find('@') {
1820 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1824 Self::Prefix(prefix) => {
1825 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1826 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1827 if sp.hi() != inner_sp.hi() {
1828 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1833 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1834 if sp.lo() != inner_sp.lo() {
1835 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1840 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1841 if sp.lo() != inner_sp.lo() {
1842 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1846 Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1851 /// Reports a diagnostic for an intra-doc link.
1853 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1854 /// the entire documentation block is used for the lint. If a range is provided but the span
1855 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1857 /// The `decorate` callback is invoked in all cases to allow further customization of the
1858 /// diagnostic before emission. If the span of the link was able to be determined, the second
1859 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1861 fn report_diagnostic(
1863 lint: &'static Lint,
1865 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1866 decorate: impl FnOnce(&mut Diagnostic, Option<rustc_span::Span>),
1868 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.def_id)
1870 // If non-local, no need to check anything.
1871 info!("ignoring warning from parent crate: {}", msg);
1875 let sp = item.attr_span(tcx);
1877 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1878 let mut diag = lint.build(msg);
1881 super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1882 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1883 && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1885 sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1891 if let Some(sp) = span {
1894 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1897 // last_new_line_offset
1898 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1899 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1901 // Print the line containing the `link_range` and manually mark it with '^'s.
1903 "the link appears in this line:\n\n{line}\n\
1904 {indicator: <before$}{indicator:^<found$}",
1907 before = link_range.start - last_new_line_offset,
1908 found = link_range.len(),
1912 decorate(&mut diag, span);
1918 /// Reports a link that failed to resolve.
1920 /// This also tries to resolve any intermediate path segments that weren't
1921 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1922 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1923 fn resolution_failure(
1924 collector: &mut LinkCollector<'_, '_>,
1925 diag_info: DiagnosticInfo<'_>,
1927 disambiguator: Option<Disambiguator>,
1928 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1930 let tcx = collector.cx.tcx;
1933 BROKEN_INTRA_DOC_LINKS,
1934 &format!("unresolved link to `{}`", path_str),
1937 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1938 let assoc_item_not_allowed = |res: Res| {
1939 let name = res.name(tcx);
1941 "`{}` is {} {}, not a module or type, and cannot have associated items",
1947 // ignore duplicates
1948 let mut variants_seen = SmallVec::<[_; 3]>::new();
1949 for mut failure in kinds {
1950 let variant = std::mem::discriminant(&failure);
1951 if variants_seen.contains(&variant) {
1954 variants_seen.push(variant);
1956 if let ResolutionFailure::NotResolved {
1965 let item_id = *item_id;
1966 let module_id = *module_id;
1967 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1968 // FIXME: maybe use itertools `collect_tuple` instead?
1969 fn split(path: &str) -> Option<(&str, &str)> {
1970 let mut splitter = path.rsplitn(2, "::");
1971 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1974 // Check if _any_ parent of the path gets resolved.
1975 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1976 let mut name = path_str;
1978 let Some((start, end)) = split(name) else {
1979 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1980 if partial_res.is_none() {
1981 *unresolved = name.into();
1986 for ns in [TypeNS, ValueNS, MacroNS] {
1988 collector.check_full_res(ns, start, item_id, module_id, &None)
1990 debug!("found partial_res={:?}", res);
1991 *partial_res = Some(res);
1992 *unresolved = end.into();
1996 *unresolved = end.into();
1999 let last_found_module = match *partial_res {
2000 Some(Res::Def(DefKind::Mod, id)) => Some(id),
2001 None => Some(module_id),
2004 // See if this was a module: `[path]` or `[std::io::nope]`
2005 if let Some(module) = last_found_module {
2006 let note = if partial_res.is_some() {
2007 // Part of the link resolved; e.g. `std::io::nonexistent`
2008 let module_name = tcx.item_name(module);
2009 format!("no item named `{}` in module `{}`", unresolved, module_name)
2011 // None of the link resolved; e.g. `Notimported`
2012 format!("no item named `{}` in scope", unresolved)
2014 if let Some(span) = sp {
2015 diag.span_label(span, ¬e);
2020 // If the link has `::` in it, assume it was meant to be an intra-doc link.
2021 // Otherwise, the `[]` might be unrelated.
2022 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
2023 if !path_str.contains("::") {
2024 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
2030 // Otherwise, it must be an associated item or variant
2031 let res = partial_res.expect("None case was handled by `last_found_module`");
2032 let name = res.name(tcx);
2033 let kind = match res {
2034 Res::Def(kind, _) => Some(kind),
2035 Res::Primitive(_) => None,
2037 let path_description = if let Some(kind) = kind {
2039 Mod | ForeignMod => "inner item",
2040 Struct => "field or associated item",
2041 Enum | Union => "variant or associated item",
2059 let note = assoc_item_not_allowed(res);
2060 if let Some(span) = sp {
2061 diag.span_label(span, ¬e);
2067 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
2068 | Static(_) => "associated item",
2069 Impl | GlobalAsm => unreachable!("not a path"),
2075 "the {} `{}` has no {} named `{}`",
2078 disambiguator.map_or(path_description, |d| d.descr()),
2081 if let Some(span) = sp {
2082 diag.span_label(span, ¬e);
2089 let note = match failure {
2090 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2091 ResolutionFailure::Dummy => continue,
2092 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2093 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2096 "this link resolves to {}, which is not in the {} namespace",
2101 ResolutionFailure::NoParentItem => {
2102 // FIXME(eddyb) this doesn't belong here, whatever made
2103 // the `ResolutionFailure::NoParentItem` should emit an
2104 // immediate or delayed `span_bug` about the issue.
2105 tcx.sess.delay_span_bug(
2106 sp.unwrap_or(DUMMY_SP),
2107 "intra-doc link missing parent item",
2110 "BUG: all intra-doc links should have a parent item".to_owned()
2112 ResolutionFailure::MalformedGenerics(variant) => match variant {
2113 MalformedGenerics::UnbalancedAngleBrackets => {
2114 String::from("unbalanced angle brackets")
2116 MalformedGenerics::MissingType => {
2117 String::from("missing type for generic parameters")
2119 MalformedGenerics::HasFullyQualifiedSyntax => {
2120 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2121 String::from("fully-qualified syntax is unsupported")
2123 MalformedGenerics::InvalidPathSeparator => {
2124 String::from("has invalid path separator")
2126 MalformedGenerics::TooManyAngleBrackets => {
2127 String::from("too many angle brackets")
2129 MalformedGenerics::EmptyAngleBrackets => {
2130 String::from("empty angle brackets")
2134 if let Some(span) = sp {
2135 diag.span_label(span, ¬e);
2144 /// Report an anchor failure.
2145 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2146 let (msg, anchor_idx) = match failure {
2147 AnchorFailure::MultipleAnchors => {
2148 (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2150 AnchorFailure::RustdocAnchorConflict(res) => (
2152 "`{}` contains an anchor, but links to {kind}s are already anchored",
2160 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2161 if let Some(mut sp) = sp {
2162 if let Some((fragment_offset, _)) =
2163 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2165 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2167 diag.span_label(sp, "invalid anchor");
2169 if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2170 if let Some(sp) = sp {
2171 span_bug!(sp, "anchors should be allowed now");
2173 bug!("anchors should be allowed now");
2179 /// Report an error in the link disambiguator.
2180 fn disambiguator_error(
2181 cx: &DocContext<'_>,
2182 mut diag_info: DiagnosticInfo<'_>,
2183 disambiguator_range: Range<usize>,
2186 diag_info.link_range = disambiguator_range;
2187 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2189 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2190 crate::DOC_RUST_LANG_ORG_CHANNEL
2196 /// Report an ambiguity error, where there were multiple possible resolutions.
2198 cx: &DocContext<'_>,
2199 diag_info: DiagnosticInfo<'_>,
2201 candidates: Vec<Res>,
2203 let mut msg = format!("`{}` is ", path_str);
2205 match candidates.as_slice() {
2206 [first_def, second_def] => {
2208 "both {} {} and {} {}",
2209 first_def.article(),
2211 second_def.article(),
2216 let mut candidates = candidates.iter().peekable();
2217 while let Some(res) = candidates.next() {
2218 if candidates.peek().is_some() {
2219 msg += &format!("{} {}, ", res.article(), res.descr());
2221 msg += &format!("and {} {}", res.article(), res.descr());
2227 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2228 if let Some(sp) = sp {
2229 diag.span_label(sp, "ambiguous link");
2231 diag.note("ambiguous link");
2234 for res in candidates {
2235 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2240 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2242 fn suggest_disambiguator(
2244 diag: &mut Diagnostic,
2247 sp: Option<rustc_span::Span>,
2249 let suggestion = res.disambiguator_suggestion();
2250 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2252 if let Some(sp) = sp {
2253 let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2254 if spans.len() > 1 {
2255 diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2257 let (sp, suggestion_text) = spans.pop().unwrap();
2258 diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2261 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2265 /// Report a link from a public item to a private one.
2266 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2268 let item_name = match diag_info.item.name {
2273 None => "<unknown>",
2276 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2278 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2279 if let Some(sp) = sp {
2280 diag.span_label(sp, "this item is private");
2283 let note_msg = if cx.render_options.document_private {
2284 "this link resolves only because you passed `--document-private-items`, but will break without"
2286 "this link will resolve properly if you pass `--document-private-items`"
2288 diag.note(note_msg);
2292 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2294 cx: &DocContext<'_>,
2296 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'static>> {
2298 .parent(res.def_id(cx.tcx))
2300 let parent_def = Res::Def(DefKind::Enum, parent);
2301 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2302 (parent_def, Some(ItemFragment(FragmentKind::Variant, variant.def_id)))
2304 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2307 /// Resolve a primitive type or value.
2308 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2312 use PrimitiveType::*;
2313 let prim = match path_str {
2329 "bool" | "true" | "false" => Bool,
2330 "str" | "&str" => Str,
2331 // See #80181 for why these don't have symbols associated.
2336 "pointer" | "*const" | "*mut" => RawPointer,
2337 "reference" | "&" | "&mut" => Reference,
2339 "never" | "!" => Never,
2342 debug!("resolved primitives {:?}", prim);
2343 Some(Res::Primitive(prim))
2346 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2347 let mut stripped_segments = vec![];
2348 let mut path = path_str.chars().peekable();
2349 let mut segment = Vec::new();
2351 while let Some(chr) = path.next() {
2354 if path.next_if_eq(&':').is_some() {
2355 let stripped_segment =
2356 strip_generics_from_path_segment(mem::take(&mut segment))?;
2357 if !stripped_segment.is_empty() {
2358 stripped_segments.push(stripped_segment);
2361 return Err(ResolutionFailure::MalformedGenerics(
2362 MalformedGenerics::InvalidPathSeparator,
2371 return Err(ResolutionFailure::MalformedGenerics(
2372 MalformedGenerics::TooManyAngleBrackets,
2376 return Err(ResolutionFailure::MalformedGenerics(
2377 MalformedGenerics::EmptyAngleBrackets,
2383 while let Some(chr) = path.next_if(|c| *c != '>') {
2390 _ => segment.push(chr),
2392 trace!("raw segment: {:?}", segment);
2395 if !segment.is_empty() {
2396 let stripped_segment = strip_generics_from_path_segment(segment)?;
2397 if !stripped_segment.is_empty() {
2398 stripped_segments.push(stripped_segment);
2402 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2404 let stripped_path = stripped_segments.join("::");
2406 if !stripped_path.is_empty() {
2409 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2413 fn strip_generics_from_path_segment(
2415 ) -> Result<String, ResolutionFailure<'static>> {
2416 let mut stripped_segment = String::new();
2417 let mut param_depth = 0;
2419 let mut latest_generics_chunk = String::new();
2424 latest_generics_chunk.clear();
2425 } else if c == '>' {
2427 if latest_generics_chunk.contains(" as ") {
2428 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2429 // Give a helpful error message instead of completely ignoring the angle brackets.
2430 return Err(ResolutionFailure::MalformedGenerics(
2431 MalformedGenerics::HasFullyQualifiedSyntax,
2435 if param_depth == 0 {
2436 stripped_segment.push(c);
2438 latest_generics_chunk.push(c);
2443 if param_depth == 0 {
2444 Ok(stripped_segment)
2446 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2447 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))