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;
14 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_ID};
15 use rustc_middle::ty::{DefIdTree, Ty, TyCtxt};
16 use rustc_middle::{bug, span_bug, ty};
17 use rustc_resolve::ParentScope;
18 use rustc_session::lint::Lint;
19 use rustc_span::hygiene::MacroKind;
20 use rustc_span::symbol::{sym, Ident, Symbol};
21 use rustc_span::{BytePos, DUMMY_SP};
22 use smallvec::{smallvec, SmallVec};
24 use pulldown_cmark::LinkType;
27 use std::convert::{TryFrom, TryInto};
32 use crate::clean::{self, utils::find_nearest_parent_module, Crate, Item, ItemLink, PrimitiveType};
33 use crate::core::DocContext;
34 use crate::html::markdown::{markdown_links, MarkdownLink};
35 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
36 use crate::passes::Pass;
37 use crate::visit::DocVisitor;
40 crate use early::early_resolve_intra_doc_links;
42 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
43 name: "collect-intra-doc-links",
44 run: collect_intra_doc_links,
45 description: "resolves intra-doc links",
48 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
50 LinkCollector { cx, mod_ids: Vec::new(), visited_links: FxHashMap::default() };
51 collector.visit_crate(&krate);
55 /// Top-level errors emitted by this pass.
57 Resolve(Box<ResolutionFailure<'a>>),
58 AnchorFailure(AnchorFailure),
61 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
62 fn from(err: ResolutionFailure<'a>) -> Self {
63 ErrorKind::Resolve(box err)
67 #[derive(Copy, Clone, Debug, Hash)]
70 Primitive(PrimitiveType),
73 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
76 fn descr(self) -> &'static str {
78 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
79 Res::Primitive(_) => "builtin type",
83 fn article(self) -> &'static str {
85 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
86 Res::Primitive(_) => "a",
90 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
92 Res::Def(_, id) => tcx.item_name(id),
93 Res::Primitive(prim) => prim.as_sym(),
97 fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
99 Res::Def(_, id) => id,
100 Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
104 fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
106 Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
107 // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
108 Res::Primitive(_) => None,
112 /// Used for error reporting.
113 fn disambiguator_suggestion(self) -> Suggestion {
114 let kind = match self {
115 Res::Primitive(_) => return Suggestion::Prefix("prim"),
116 Res::Def(kind, _) => kind,
118 if kind == DefKind::Macro(MacroKind::Bang) {
119 return Suggestion::Macro;
120 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
121 return Suggestion::Function;
122 } else if kind == DefKind::Field {
123 return Suggestion::RemoveDisambiguator;
126 let prefix = match kind {
127 DefKind::Struct => "struct",
128 DefKind::Enum => "enum",
129 DefKind::Trait => "trait",
130 DefKind::Union => "union",
131 DefKind::Mod => "mod",
132 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
135 DefKind::Static => "static",
136 DefKind::Macro(MacroKind::Derive) => "derive",
137 // Now handle things that don't have a specific disambiguator
140 .expect("tried to calculate a disambiguator for a def without a namespace?")
142 Namespace::TypeNS => "type",
143 Namespace::ValueNS => "value",
144 Namespace::MacroNS => "macro",
148 Suggestion::Prefix(prefix)
152 impl TryFrom<ResolveRes> for Res {
155 fn try_from(res: ResolveRes) -> Result<Self, ()> {
156 use rustc_hir::def::Res::*;
158 Def(kind, id) => Ok(Res::Def(kind, id)),
159 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
161 NonMacroAttr(..) | Err => Result::Err(()),
162 other => bug!("unrecognized res {:?}", other),
167 /// A link failed to resolve.
169 enum ResolutionFailure<'a> {
170 /// This resolved, but with the wrong namespace.
172 /// What the link resolved to.
174 /// The expected namespace for the resolution, determined from the link's disambiguator.
176 /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
177 /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
178 expected_ns: Namespace,
180 /// The link failed to resolve. [`resolution_failure`] should look to see if there's
181 /// a more helpful error that can be given.
183 /// The scope the link was resolved in.
185 /// If part of the link resolved, this has the `Res`.
187 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
188 partial_res: Option<Res>,
189 /// The remaining unresolved path segments.
191 /// In `[std::io::Error::x]`, `x` would be unresolved.
192 unresolved: Cow<'a, str>,
194 /// This happens when rustdoc can't determine the parent scope for an item.
195 /// It is always a bug in rustdoc.
197 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
198 MalformedGenerics(MalformedGenerics),
199 /// Used to communicate that this should be ignored, but shouldn't be reported to the user.
201 /// This happens when there is no disambiguator and one of the namespaces
202 /// failed to resolve.
207 enum MalformedGenerics {
208 /// This link has unbalanced angle brackets.
210 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
211 UnbalancedAngleBrackets,
212 /// The generics are not attached to a type.
214 /// For example, `<T>` should trigger this.
216 /// This is detected by checking if the path is empty after the generics are stripped.
218 /// The link uses fully-qualified syntax, which is currently unsupported.
220 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
222 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
224 HasFullyQualifiedSyntax,
225 /// The link has an invalid path separator.
227 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
228 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
231 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
232 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
233 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
235 /// This is detected by checking if there is a colon followed by a non-colon in the link.
236 InvalidPathSeparator,
237 /// The link has too many angle brackets.
239 /// For example, `Vec<<T>>` should trigger this.
240 TooManyAngleBrackets,
241 /// The link has empty angle brackets.
243 /// For example, `Vec<>` should trigger this.
247 impl ResolutionFailure<'_> {
248 /// This resolved fully (not just partially) but is erroneous for some other reason
250 /// Returns the full resolution of the link, if present.
251 fn full_res(&self) -> Option<Res> {
253 Self::WrongNamespace { res, expected_ns: _ } => Some(*res),
260 /// User error: `[std#x#y]` is not valid
262 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
264 /// This is an unfortunate state of affairs. Not every item that can be
265 /// linked to has its own page; sometimes it is a subheading within a page,
266 /// like for associated items. In those cases, rustdoc uses an anchor to
267 /// link to the subheading. Since you can't have two anchors for the same
268 /// link, Rustdoc disallows having a user-specified anchor.
270 /// Most of the time this is fine, because you can just link to the page of
271 /// the item if you want to provide your own anchor.
272 RustdocAnchorConflict(Res),
275 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
276 crate enum UrlFragment {
282 /// Render the fragment, including the leading `#`.
283 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
285 UrlFragment::Item(frag) => frag.render(s, tcx),
286 UrlFragment::UserWritten(raw) => write!(s, "#{}", raw),
291 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
292 crate struct ItemFragment(FragmentKind, DefId);
294 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
295 crate enum FragmentKind {
307 /// Create a fragment for an associated item.
308 #[instrument(level = "debug")]
309 fn from_assoc_item(item: &ty::AssocItem) -> Self {
310 let def_id = item.def_id;
312 ty::AssocKind::Fn => {
313 if item.defaultness.has_value() {
314 ItemFragment(FragmentKind::Method, def_id)
316 ItemFragment(FragmentKind::TyMethod, def_id)
319 ty::AssocKind::Const => ItemFragment(FragmentKind::AssociatedConstant, def_id),
320 ty::AssocKind::Type => ItemFragment(FragmentKind::AssociatedType, def_id),
324 /// Render the fragment, including the leading `#`.
325 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
328 ItemFragment(kind, def_id) => {
329 let name = tcx.item_name(def_id);
331 FragmentKind::Method => write!(s, "method.{}", name),
332 FragmentKind::TyMethod => write!(s, "tymethod.{}", name),
333 FragmentKind::AssociatedConstant => write!(s, "associatedconstant.{}", name),
334 FragmentKind::AssociatedType => write!(s, "associatedtype.{}", name),
335 FragmentKind::StructField => write!(s, "structfield.{}", name),
336 FragmentKind::Variant => write!(s, "variant.{}", name),
337 FragmentKind::VariantField => {
338 let variant = tcx.item_name(tcx.parent(def_id).unwrap());
339 write!(s, "variant.{}.field.{}", variant, name)
347 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
348 struct ResolutionInfo {
350 dis: Option<Disambiguator>,
352 extra_fragment: Option<String>,
356 struct DiagnosticInfo<'a> {
360 link_range: Range<usize>,
363 #[derive(Clone, Debug, Hash)]
365 res: (Res, Option<UrlFragment>),
368 struct LinkCollector<'a, 'tcx> {
369 cx: &'a mut DocContext<'tcx>,
370 /// A stack of modules used to decide what scope to resolve in.
372 /// The last module will be used if the parent scope of the current item is
375 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
376 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
377 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
380 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
381 /// Given a full link, parse it as an [enum struct variant].
383 /// In particular, this will return an error whenever there aren't three
384 /// full path segments left in the link.
386 /// [enum struct variant]: rustc_hir::VariantData::Struct
387 fn variant_field<'path>(
389 path_str: &'path str,
391 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
392 let tcx = self.cx.tcx;
393 let no_res = || ResolutionFailure::NotResolved {
396 unresolved: path_str.into(),
399 debug!("looking for enum variant {}", path_str);
400 let mut split = path_str.rsplitn(3, "::");
401 let variant_field_name = split
403 .map(|f| Symbol::intern(f))
404 .expect("fold_item should ensure link is non-empty");
406 // we're not sure this is a variant at all, so use the full string
407 // If there's no second component, the link looks like `[path]`.
408 // So there's no partial res and we should say the whole link failed to resolve.
409 split.next().map(|f| Symbol::intern(f)).ok_or_else(no_res)?;
412 .map(|f| f.to_owned())
413 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
414 // So there's no partial res.
415 .ok_or_else(no_res)?;
418 .enter_resolver(|resolver| {
419 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
421 .and_then(|(_, res)| res.try_into())
422 .map_err(|()| no_res())?;
425 Res::Def(DefKind::Enum, did) => {
429 .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
430 .any(|item| item.name == variant_name)
432 // This is just to let `fold_item` know that this shouldn't be considered;
433 // it's a bug for the error to make it to the user
434 return Err(ResolutionFailure::Dummy.into());
436 match tcx.type_of(did).kind() {
437 ty::Adt(def, _) if def.is_enum() => {
438 if let Some(field) = def.all_fields().find(|f| f.name == variant_field_name)
440 Ok((ty_res, Some(ItemFragment(FragmentKind::VariantField, field.did))))
442 Err(ResolutionFailure::NotResolved {
444 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
445 unresolved: variant_field_name.to_string().into(),
453 _ => 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).into_iter().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()`?
488 ) -> Result<Res, ResolutionFailure<'a>> {
489 let path = ast::Path::from_ident(Ident::from_str(path_str));
490 self.cx.enter_resolver(|resolver| {
491 // FIXME(jynelson): does this really need 3 separate lookups?
492 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
495 &ParentScope::module(resolver.graph_root(), resolver),
499 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
500 return Ok(res.try_into().unwrap());
503 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
504 return Ok(res.try_into().unwrap());
506 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
507 if let Ok((_, res)) =
508 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
510 // don't resolve builtins like `#[derive]`
511 if let Ok(res) = res.try_into() {
515 Err(ResolutionFailure::NotResolved {
518 unresolved: path_str.into(),
523 /// Convenience wrapper around `resolve_str_path_error`.
525 /// This also handles resolving `true` and `false` as booleans.
526 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
527 /// Associated items will never be resolved by this function.
528 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
529 let result = self.cx.enter_resolver(|resolver| {
531 .resolve_str_path_error(DUMMY_SP, path_str, ns, module_id)
532 .and_then(|(_, res)| res.try_into())
534 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
536 // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
538 Err(()) => resolve_primitive(path_str, ns),
539 Ok(res) => Some(res),
543 /// Resolves a string as a path within a particular namespace. Returns an
544 /// optional URL fragment in the case of variants and methods.
547 path_str: &'path str,
550 user_fragment: &Option<String>,
551 ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'path>> {
552 let (res, rustdoc_fragment) = self.resolve_inner(path_str, ns, module_id)?;
553 let chosen_fragment = match (user_fragment, rustdoc_fragment) {
554 (Some(_), Some(r_frag)) => {
555 let diag_res = match r_frag {
556 ItemFragment(_, did) => Res::Def(self.cx.tcx.def_kind(did), did),
558 let failure = AnchorFailure::RustdocAnchorConflict(diag_res);
559 return Err(ErrorKind::AnchorFailure(failure));
561 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
562 (None, Some(r_frag)) => Some(UrlFragment::Item(r_frag)),
563 (None, None) => None,
565 Ok((res, chosen_fragment))
568 fn resolve_inner<'path>(
570 path_str: &'path str,
573 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
574 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
576 // FIXME(#76467): make this fallthrough to lookup the associated
577 // item a separate function.
578 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
579 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
580 Res::Def(DefKind::Variant, _) => {
581 return handle_variant(self.cx, res);
583 // Not a trait item; just return what we found.
584 _ => return Ok((res, None)),
588 // Try looking for methods and associated items.
589 let mut split = path_str.rsplitn(2, "::");
590 // NB: `split`'s first element is always defined, even if the delimiter was not present.
591 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
592 let item_str = split.next().unwrap();
593 let item_name = Symbol::intern(item_str);
594 let path_root = split
596 .map(|f| f.to_owned())
597 // If there's no `::`, it's not an associated item.
598 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
600 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
601 ResolutionFailure::NotResolved {
604 unresolved: item_str.into(),
608 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
609 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
610 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
612 resolve_primitive(&path_root, TypeNS)
613 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
615 let (res, fragment) =
616 self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
618 Some(Ok((res, Some(fragment))))
621 if ns == Namespace::ValueNS {
622 self.variant_field(path_str, module_id)
624 Err(ResolutionFailure::NotResolved {
627 unresolved: path_root.into(),
634 /// Convert a DefId to a Res, where possible.
636 /// This is used for resolving type aliases.
637 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
638 use PrimitiveType::*;
639 Some(match *self.cx.tcx.type_of(ty_id).kind() {
640 ty::Bool => Res::Primitive(Bool),
641 ty::Char => Res::Primitive(Char),
642 ty::Int(ity) => Res::Primitive(ity.into()),
643 ty::Uint(uty) => Res::Primitive(uty.into()),
644 ty::Float(fty) => Res::Primitive(fty.into()),
645 ty::Str => Res::Primitive(Str),
646 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
647 ty::Tuple(_) => Res::Primitive(Tuple),
648 ty::Array(..) => Res::Primitive(Array),
649 ty::Slice(_) => Res::Primitive(Slice),
650 ty::RawPtr(_) => Res::Primitive(RawPointer),
651 ty::Ref(..) => Res::Primitive(Reference),
652 ty::FnDef(..) => panic!("type alias to a function definition"),
653 ty::FnPtr(_) => Res::Primitive(Fn),
654 ty::Never => Res::Primitive(Never),
655 ty::Adt(&ty::AdtDef { did, .. }, _) | ty::Foreign(did) => {
656 Res::Def(self.cx.tcx.def_kind(did), did)
661 | ty::GeneratorWitness(_)
668 | ty::Error(_) => return None,
672 /// Convert a PrimitiveType to a Ty, where possible.
674 /// This is used for resolving trait impls for primitives
675 fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
676 use PrimitiveType::*;
677 let tcx = self.cx.tcx;
679 // FIXME: Only simple types are supported here, see if we can support
680 // other types such as Tuple, Array, Slice, etc.
681 // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
682 Some(tcx.mk_ty(match prim {
687 I8 => ty::Int(ty::IntTy::I8),
688 I16 => ty::Int(ty::IntTy::I16),
689 I32 => ty::Int(ty::IntTy::I32),
690 I64 => ty::Int(ty::IntTy::I64),
691 I128 => ty::Int(ty::IntTy::I128),
692 Isize => ty::Int(ty::IntTy::Isize),
693 F32 => ty::Float(ty::FloatTy::F32),
694 F64 => ty::Float(ty::FloatTy::F64),
695 U8 => ty::Uint(ty::UintTy::U8),
696 U16 => ty::Uint(ty::UintTy::U16),
697 U32 => ty::Uint(ty::UintTy::U32),
698 U64 => ty::Uint(ty::UintTy::U64),
699 U128 => ty::Uint(ty::UintTy::U128),
700 Usize => ty::Uint(ty::UintTy::Usize),
705 /// Resolve an associated item, returning its containing page's `Res`
706 /// and the fragment targeting the associated item on its page.
707 fn resolve_associated_item(
713 ) -> Option<(Res, ItemFragment)> {
714 let tcx = self.cx.tcx;
717 Res::Primitive(prim) => {
718 self.resolve_primitive_associated_item(prim, ns, item_name).or_else(|| {
719 let assoc_item = self
720 .primitive_type_to_ty(prim)
722 resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
726 assoc_item.map(|item| {
727 let fragment = ItemFragment::from_assoc_item(&item);
732 Res::Def(DefKind::TyAlias, did) => {
733 // Resolve the link on the type the alias points to.
734 // FIXME: if the associated item is defined directly on the type alias,
735 // it will show up on its documentation page, we should link there instead.
736 let res = self.def_id_to_res(did)?;
737 self.resolve_associated_item(res, item_name, ns, module_id)
740 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy,
743 debug!("looking for associated item named {} for item {:?}", item_name, did);
744 // Checks if item_name belongs to `impl SomeItem`
749 tcx.associated_items(imp).find_by_name_and_namespace(
751 Ident::with_dummy_span(item_name),
757 // There should only ever be one associated item that matches from any inherent impl
759 // Check if item_name belongs to `impl SomeTrait for SomeItem`
760 // FIXME(#74563): This gives precedence to `impl SomeItem`:
761 // Although having both would be ambiguous, use impl version for compatibility's sake.
762 // To handle that properly resolve() would have to support
763 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
765 resolve_associated_trait_item(
774 debug!("got associated item {:?}", assoc_item);
776 if let Some(item) = assoc_item {
777 let fragment = ItemFragment::from_assoc_item(&item);
778 return Some((root_res, fragment));
781 if ns != Namespace::ValueNS {
784 debug!("looking for fields named {} for {:?}", item_name, did);
785 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
786 // NOTE: it's different from variant_field because it only resolves struct fields,
787 // not variant fields (2 path segments, not 3).
789 // We need to handle struct (and union) fields in this code because
790 // syntactically their paths are identical to associated item paths:
791 // `module::Type::field` and `module::Type::Assoc`.
793 // On the other hand, variant fields can't be mistaken for associated
794 // items because they look like this: `module::Type::Variant::field`.
796 // Variants themselves don't need to be handled here, even though
797 // they also look like associated items (`module::Type::Variant`),
798 // because they are real Rust syntax (unlike the intra-doc links
799 // field syntax) and are handled by the compiler's resolver.
800 let def = match tcx.type_of(did).kind() {
801 ty::Adt(def, _) if !def.is_enum() => def,
805 def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?;
806 Some((root_res, ItemFragment(FragmentKind::StructField, field.did)))
808 Res::Def(DefKind::Trait, did) => tcx
809 .associated_items(did)
810 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
812 let fragment = ItemFragment::from_assoc_item(item);
813 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
820 /// Used for reporting better errors.
822 /// Returns whether the link resolved 'fully' in another namespace.
823 /// 'fully' here means that all parts of the link resolved, not just some path segments.
824 /// This returns the `Res` even if it was erroneous for some reason
825 /// (such as having invalid URL fragments or being in the wrong namespace).
831 extra_fragment: &Option<String>,
833 // resolve() can't be used for macro namespace
834 let result = match ns {
835 Namespace::MacroNS => self
836 .resolve_macro(path_str, module_id)
837 .map(|res| (res, None))
838 .map_err(ErrorKind::from),
839 Namespace::TypeNS | Namespace::ValueNS => {
840 self.resolve(path_str, ns, module_id, extra_fragment)
844 let res = match result {
846 if let Some(UrlFragment::Item(ItemFragment(_, id))) = frag {
847 Some(Res::Def(self.cx.tcx.def_kind(id), id))
852 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
853 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
854 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
860 /// Look to see if a resolved item has an associated item named `item_name`.
862 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
863 /// find `std::error::Error::source` and return
864 /// `<io::Error as error::Error>::source`.
865 fn resolve_associated_trait_item<'a>(
870 cx: &mut DocContext<'a>,
871 ) -> Option<ty::AssocItem> {
872 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
873 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
874 // meantime, just don't look for these blanket impls.
876 // Next consider explicit impls: `impl MyTrait for MyType`
877 // Give precedence to inherent impls.
878 let traits = trait_impls_for(cx, ty, module);
879 debug!("considering traits {:?}", traits);
880 let mut candidates = traits.iter().filter_map(|&(impl_, trait_)| {
882 .associated_items(trait_)
883 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
885 trait_assoc_to_impl_assoc_item(cx.tcx, impl_, trait_assoc.def_id)
886 .unwrap_or(trait_assoc)
889 // FIXME(#74563): warn about ambiguity
890 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
891 candidates.next().copied()
894 /// Find the associated item in the impl `impl_id` that corresponds to the
895 /// trait associated item `trait_assoc_id`.
897 /// This function returns `None` if no associated item was found in the impl.
898 /// This can occur when the trait associated item has a default value that is
899 /// not overriden in the impl.
901 /// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
902 /// [`TyCtxt::associated_item()`] (with some helpful logging added).
903 #[instrument(level = "debug", skip(tcx))]
904 fn trait_assoc_to_impl_assoc_item<'tcx>(
907 trait_assoc_id: DefId,
908 ) -> Option<&'tcx ty::AssocItem> {
909 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
910 debug!(?trait_to_impl_assoc_map);
911 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
912 debug!(?impl_assoc_id);
913 let impl_assoc = tcx.associated_item(impl_assoc_id);
918 /// Given a type, return all trait impls in scope in `module` for that type.
919 /// Returns a set of pairs of `(impl_id, trait_id)`.
921 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
922 /// So it is not stable to serialize cross-crate.
923 #[instrument(level = "debug", skip(cx))]
924 fn trait_impls_for<'a>(
925 cx: &mut DocContext<'a>,
928 ) -> FxHashSet<(DefId, DefId)> {
930 let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
931 let trait_ = trait_candidate.def_id;
932 trace!("considering explicit impl for trait {:?}", trait_);
934 // Look at each trait implementation to see if it's an impl for `did`
935 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
936 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
937 // Check if these are the same type.
938 let impl_type = trait_ref.self_ty();
940 "comparing type {} with kind {:?} against type {:?}",
945 // Fast path: if this is a primitive simple `==` will work
946 // NOTE: the `match` is necessary; see #92662.
947 // this allows us to ignore generics because the user input
948 // may not include the generic placeholders
949 // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
950 let saw_impl = impl_type == ty
951 || match (impl_type.kind(), ty.kind()) {
952 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
953 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did, ty_def.did);
954 impl_def.did == ty_def.did
959 if saw_impl { Some((impl_, trait_)) } else { None }
965 /// Check for resolve collisions between a trait and its derive.
967 /// These are common and we should just resolve to the trait in that case.
968 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
972 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
973 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
979 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
980 fn visit_item(&mut self, item: &Item) {
982 item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
983 if parent_node.is_some() {
984 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
987 // find item's parent to resolve `Self` in item's docs below
988 debug!("looking for the `Self` type");
989 let self_id = match item.def_id.as_def_id() {
992 if (matches!(self.cx.tcx.def_kind(did), DefKind::Field)
994 self.cx.tcx.def_kind(self.cx.tcx.parent(did).unwrap()),
998 self.cx.tcx.parent(did).and_then(|item_id| self.cx.tcx.parent(item_id))
1002 self.cx.tcx.def_kind(did),
1010 self.cx.tcx.parent(did)
1012 Some(did) => Some(did),
1015 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
1016 let self_name = self_id.and_then(|self_id| {
1017 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
1018 // using `ty.to_string()` (or any variant) has issues with raw idents
1019 let ty = self.cx.tcx.type_of(self_id);
1020 let name = match ty.kind() {
1021 ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
1022 other if other.is_primitive() => Some(ty.to_string()),
1025 debug!("using type_of(): {:?}", name);
1028 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
1029 debug!("using item_name(): {:?}", name);
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);
1047 let (krate, parent_node) = if let Some(id) = parent_module {
1048 (id.krate, Some(id))
1050 (item.def_id.krate(), parent_node)
1052 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1053 // This is a degenerate case and it's not supported by rustdoc.
1054 for md_link in markdown_links(&doc) {
1055 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
1056 if let Some(link) = link {
1057 self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
1064 self.mod_ids.push(item.def_id.expect_def_id());
1067 self.visit_item_recur(item);
1070 self.visit_item_recur(item)
1075 enum PreprocessingError<'a> {
1076 Anchor(AnchorFailure),
1077 Disambiguator(Range<usize>, String),
1078 Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
1081 impl From<AnchorFailure> for PreprocessingError<'_> {
1082 fn from(err: AnchorFailure) -> Self {
1087 struct PreprocessingInfo {
1089 disambiguator: Option<Disambiguator>,
1090 extra_fragment: Option<String>,
1095 /// - `None` if the link should be ignored.
1096 /// - `Some(Err)` if the link should emit an error
1097 /// - `Some(Ok)` if the link is valid
1099 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
1100 fn preprocess_link<'a>(
1101 ori_link: &'a MarkdownLink,
1102 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
1103 // [] is mostly likely not supposed to be a link
1104 if ori_link.link.is_empty() {
1108 // Bail early for real links.
1109 if ori_link.link.contains('/') {
1113 let stripped = ori_link.link.replace('`', "");
1114 let mut parts = stripped.split('#');
1116 let link = parts.next().unwrap();
1117 if link.trim().is_empty() {
1118 // This is an anchor to an element of the current page, nothing to do in here!
1121 let extra_fragment = parts.next();
1122 if parts.next().is_some() {
1123 // A valid link can't have multiple #'s
1124 return Some(Err(AnchorFailure::MultipleAnchors.into()));
1127 // Parse and strip the disambiguator from the link, if present.
1128 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1129 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1130 Ok(None) => (None, link.trim(), link.trim()),
1131 Err((err_msg, relative_range)) => {
1132 // Only report error if we would not have ignored this link. See issue #83859.
1133 if !should_ignore_link_with_disambiguators(link) {
1134 let no_backticks_range = range_between_backticks(ori_link);
1135 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1136 ..(no_backticks_range.start + relative_range.end);
1137 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1144 if should_ignore_link(path_str) {
1148 // Strip generics from the path.
1149 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1150 match strip_generics_from_path(path_str) {
1153 debug!("link has malformed generics: {}", path_str);
1154 return Some(Err(PreprocessingError::Resolution(
1156 path_str.to_owned(),
1165 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1166 assert!(!path_str.contains(['<', '>'].as_slice()));
1168 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1169 if path_str.contains(' ') {
1173 Some(Ok(PreprocessingInfo {
1176 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1177 link_text: link_text.to_owned(),
1181 impl LinkCollector<'_, '_> {
1182 /// This is the entry point for resolving an intra-doc link.
1184 /// FIXME(jynelson): this is way too many arguments
1189 self_name: &Option<String>,
1190 parent_node: Option<DefId>,
1192 ori_link: MarkdownLink,
1193 ) -> Option<ItemLink> {
1194 trace!("considering link '{}'", ori_link.link);
1196 let diag_info = DiagnosticInfo {
1199 ori_link: &ori_link.link,
1200 link_range: ori_link.range.clone(),
1203 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1204 match preprocess_link(&ori_link)? {
1208 PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1209 PreprocessingError::Disambiguator(range, msg) => {
1210 disambiguator_error(self.cx, diag_info, range, &msg)
1212 PreprocessingError::Resolution(err, path_str, disambiguator) => {
1225 let mut path_str = &*path_str;
1227 let inner_docs = item.inner_docs(self.cx.tcx);
1229 // In order to correctly resolve intra-doc links we need to
1230 // pick a base AST node to work from. If the documentation for
1231 // this module came from an inner comment (//!) then we anchor
1232 // our name resolution *inside* the module. If, on the other
1233 // hand it was an outer comment (///) then we anchor the name
1234 // resolution in the parent module on the basis that the names
1235 // used are more likely to be intended to be parent names. For
1236 // this, we set base_node to None for inner comments since
1237 // we've already pushed this node onto the resolution stack but
1238 // for outer comments we explicitly try and resolve against the
1239 // parent_node first.
1241 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1243 let mut module_id = if let Some(id) = base_node {
1247 debug!("attempting to resolve item without parent module: {}", path_str);
1253 smallvec![ResolutionFailure::NoParentItem],
1259 // replace `Self` with suitable item's parent name
1260 let is_lone_self = path_str == "Self";
1261 let is_lone_crate = path_str == "crate";
1262 if path_str.starts_with("Self::") || is_lone_self {
1263 if let Some(ref name) = self_name {
1267 resolved_self = format!("{}::{}", name, &path_str[6..]);
1268 path_str = &resolved_self;
1271 } else if path_str.starts_with("crate::") || is_lone_crate {
1272 use rustc_span::def_id::CRATE_DEF_INDEX;
1274 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1275 // But rustdoc wants it to mean the crate this item was originally present in.
1276 // To work around this, remove it and resolve relative to the crate root instead.
1277 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1278 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1279 // FIXME(#78696): This doesn't always work.
1283 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1284 path_str = &resolved_self;
1286 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1289 let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1293 path_str: path_str.to_owned(),
1296 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1297 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1300 // Check for a primitive which might conflict with a module
1301 // Report the ambiguity and require that the user specify which one they meant.
1302 // FIXME: could there ever be a primitive not in the type namespace?
1305 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1306 ) && !matches!(res, Res::Primitive(_))
1308 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1310 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1313 // `[char]` when a `char` module is in scope
1314 let candidates = vec![res, prim];
1315 ambiguity_error(self.cx, diag_info, path_str, candidates);
1322 Res::Primitive(prim) => {
1323 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1324 // We're actually resolving an associated item of a primitive, so we need to
1325 // verify the disambiguator (if any) matches the type of the associated item.
1326 // This case should really follow the same flow as the `Res::Def` branch below,
1327 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1328 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1329 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1330 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1331 // for discussion on the matter.
1332 let kind = self.cx.tcx.def_kind(id);
1333 self.verify_disambiguator(
1343 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1344 // However I'm not sure how to check that across crates.
1345 if prim == PrimitiveType::RawPointer
1346 && item.def_id.is_local()
1347 && !self.cx.tcx.features().intra_doc_pointers
1349 self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1352 match disambiguator {
1353 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1355 self.report_disambiguator_mismatch(
1356 path_str, &ori_link, other, res, &diag_info,
1364 link: ori_link.link,
1366 did: res.def_id(self.cx.tcx),
1370 Res::Def(kind, id) => {
1371 let (kind_for_dis, id_for_dis) =
1372 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1373 (self.cx.tcx.def_kind(id), id)
1377 self.verify_disambiguator(
1386 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1387 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1392 fn verify_disambiguator(
1395 ori_link: &MarkdownLink,
1398 disambiguator: Option<Disambiguator>,
1400 diag_info: &DiagnosticInfo<'_>,
1402 debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1404 // Disallow e.g. linking to enums with `struct@`
1405 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1406 match (kind, disambiguator) {
1407 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1408 // NOTE: this allows 'method' to mean both normal functions and associated functions
1409 // This can't cause ambiguity because both are in the same namespace.
1410 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1411 // These are namespaces; allow anything in the namespace to match
1412 | (_, Some(Disambiguator::Namespace(_)))
1413 // If no disambiguator given, allow anything
1415 // All of these are valid, so do nothing
1417 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1418 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1419 self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1424 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1425 if let Some((src_id, dst_id)) = id
1427 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1428 // would presumably panic if a fake `DefIndex` were passed.
1429 .and_then(|dst_id| {
1430 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1433 if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1434 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1436 privacy_error(self.cx, diag_info, path_str);
1443 fn report_disambiguator_mismatch(
1446 ori_link: &MarkdownLink,
1447 specified: Disambiguator,
1449 diag_info: &DiagnosticInfo<'_>,
1451 // The resolved item did not match the disambiguator; give a better error than 'not found'
1452 let msg = format!("incompatible link kind for `{}`", path_str);
1453 let callback = |diag: &mut DiagnosticBuilder<'_>, sp: Option<rustc_span::Span>| {
1455 "this link resolved to {} {}, which is not {} {}",
1458 specified.article(),
1461 if let Some(sp) = sp {
1462 diag.span_label(sp, ¬e);
1466 suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1468 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1471 fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1473 super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1474 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1475 rustc_session::parse::feature_err(
1476 &self.cx.tcx.sess.parse_sess,
1477 sym::intra_doc_pointers,
1479 "linking to associated items of raw pointers is experimental",
1481 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1485 fn resolve_with_disambiguator_cached(
1487 key: ResolutionInfo,
1488 diag: DiagnosticInfo<'_>,
1489 cache_resolution_failure: bool,
1490 ) -> Option<(Res, Option<UrlFragment>)> {
1491 if let Some(ref cached) = self.visited_links.get(&key) {
1494 return Some(cached.res.clone());
1496 None if cache_resolution_failure => return None,
1498 // Although we hit the cache and found a resolution error, this link isn't
1499 // supposed to cache those. Run link resolution again to emit the expected
1500 // resolution error.
1505 let res = self.resolve_with_disambiguator(&key, diag);
1507 // Cache only if resolved successfully - don't silence duplicate errors
1508 if let Some(res) = res {
1509 // Store result for the actual namespace
1510 self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1514 if cache_resolution_failure {
1515 // For reference-style links we only want to report one resolution error
1516 // so let's cache them as well.
1517 self.visited_links.insert(key, None);
1524 /// After parsing the disambiguator, resolve the main part of the link.
1525 // FIXME(jynelson): wow this is just so much
1526 fn resolve_with_disambiguator(
1528 key: &ResolutionInfo,
1529 diag: DiagnosticInfo<'_>,
1530 ) -> Option<(Res, Option<UrlFragment>)> {
1531 let disambiguator = key.dis;
1532 let path_str = &key.path_str;
1533 let base_node = key.module_id;
1534 let extra_fragment = &key.extra_fragment;
1536 match disambiguator.map(Disambiguator::ns) {
1537 Some(expected_ns @ (ValueNS | TypeNS)) => {
1538 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1539 Ok(res) => Some(res),
1540 Err(ErrorKind::Resolve(box mut kind)) => {
1541 // We only looked in one namespace. Try to give a better error if possible.
1542 if kind.full_res().is_none() {
1543 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1544 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1545 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1546 for new_ns in [other_ns, MacroNS] {
1548 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1550 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1555 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1556 // This could just be a normal link or a broken link
1557 // we could potentially check if something is
1558 // "intra-doc-link-like" and warn in that case.
1561 Err(ErrorKind::AnchorFailure(msg)) => {
1562 anchor_failure(self.cx, diag, msg);
1569 let mut candidates = PerNS {
1571 .resolve_macro(path_str, base_node)
1572 .map(|res| (res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1573 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1575 debug!("got res in TypeNS: {:?}", res);
1578 Err(ErrorKind::AnchorFailure(msg)) => {
1579 anchor_failure(self.cx, diag, msg);
1582 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1584 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1586 Err(ErrorKind::AnchorFailure(msg)) => {
1587 anchor_failure(self.cx, diag, msg);
1590 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1592 .and_then(|(res, fragment)| {
1593 // Constructors are picked up in the type namespace.
1595 Res::Def(DefKind::Ctor(..), _) => {
1596 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1599 match (fragment, extra_fragment.clone()) {
1600 (Some(fragment), Some(_)) => {
1601 // Shouldn't happen but who knows?
1602 Ok((res, Some(fragment)))
1604 (fragment, None) => Ok((res, fragment)),
1605 (None, fragment) => {
1606 Ok((res, fragment.map(UrlFragment::UserWritten)))
1614 let len = candidates.iter().filter(|res| res.is_ok()).count();
1622 candidates.into_iter().filter_map(|res| res.err()).collect(),
1624 // this could just be a normal link
1629 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1630 } else if len == 2 && is_derive_trait_collision(&candidates) {
1631 Some(candidates.type_ns.unwrap())
1633 if is_derive_trait_collision(&candidates) {
1634 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1636 // If we're reporting an ambiguity, don't mention the namespaces that failed
1637 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1638 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1643 match self.resolve_macro(path_str, base_node) {
1644 Ok(res) => Some((res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1646 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1647 for ns in [TypeNS, ValueNS] {
1649 self.check_full_res(ns, path_str, base_node, extra_fragment)
1652 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1656 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1665 /// Get the section of a link between the backticks,
1666 /// or the whole link if there aren't any backticks.
1674 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1675 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1676 let before_second_backtick_group = ori_link
1679 .skip(after_first_backtick_group)
1680 .position(|b| b == b'`')
1681 .unwrap_or(ori_link.link.len());
1682 (ori_link.range.start + after_first_backtick_group)
1683 ..(ori_link.range.start + before_second_backtick_group)
1686 /// Returns true if we should ignore `link` due to it being unlikely
1687 /// that it is an intra-doc link. `link` should still have disambiguators
1688 /// if there were any.
1690 /// The difference between this and [`should_ignore_link()`] is that this
1691 /// check should only be used on links that still have disambiguators.
1692 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1693 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1696 /// Returns true if we should ignore `path_str` due to it being unlikely
1697 /// that it is an intra-doc link.
1698 fn should_ignore_link(path_str: &str) -> bool {
1699 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1702 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1703 /// Disambiguators for a link.
1704 enum Disambiguator {
1707 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1709 /// `struct@` or `f()`
1712 Namespace(Namespace),
1715 impl Disambiguator {
1716 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1718 /// This returns `Ok(Some(...))` if a disambiguator was found,
1719 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1720 /// if there was a problem with the disambiguator.
1721 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1722 use Disambiguator::{Kind, Namespace as NS, Primitive};
1724 if let Some(idx) = link.find('@') {
1725 let (prefix, rest) = link.split_at(idx);
1726 let d = match prefix {
1727 "struct" => Kind(DefKind::Struct),
1728 "enum" => Kind(DefKind::Enum),
1729 "trait" => Kind(DefKind::Trait),
1730 "union" => Kind(DefKind::Union),
1731 "module" | "mod" => Kind(DefKind::Mod),
1732 "const" | "constant" => Kind(DefKind::Const),
1733 "static" => Kind(DefKind::Static),
1734 "function" | "fn" | "method" => Kind(DefKind::Fn),
1735 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1736 "type" => NS(Namespace::TypeNS),
1737 "value" => NS(Namespace::ValueNS),
1738 "macro" => NS(Namespace::MacroNS),
1739 "prim" | "primitive" => Primitive,
1740 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1742 Ok(Some((d, &rest[1..], &rest[1..])))
1745 ("!()", DefKind::Macro(MacroKind::Bang)),
1746 ("!{}", DefKind::Macro(MacroKind::Bang)),
1747 ("![]", DefKind::Macro(MacroKind::Bang)),
1748 ("()", DefKind::Fn),
1749 ("!", DefKind::Macro(MacroKind::Bang)),
1751 for (suffix, kind) in suffixes {
1752 if let Some(path_str) = link.strip_suffix(suffix) {
1753 // Avoid turning `!` or `()` into an empty string
1754 if !path_str.is_empty() {
1755 return Ok(Some((Kind(kind), path_str, link)));
1763 fn ns(self) -> Namespace {
1765 Self::Namespace(n) => n,
1767 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1769 Self::Primitive => TypeNS,
1773 fn article(self) -> &'static str {
1775 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1776 Self::Kind(k) => k.article(),
1777 Self::Primitive => "a",
1781 fn descr(self) -> &'static str {
1783 Self::Namespace(n) => n.descr(),
1784 // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1785 // printing "module" vs "crate" so using the wrong ID is not a huge problem
1786 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1787 Self::Primitive => "builtin type",
1792 /// A suggestion to show in a diagnostic.
1795 Prefix(&'static str),
1800 /// `foo` without any disambiguator
1801 RemoveDisambiguator,
1805 fn descr(&self) -> Cow<'static, str> {
1807 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1808 Self::Function => "add parentheses".into(),
1809 Self::Macro => "add an exclamation mark".into(),
1810 Self::RemoveDisambiguator => "remove the disambiguator".into(),
1814 fn as_help(&self, path_str: &str) -> String {
1815 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1817 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1818 Self::Function => format!("{}()", path_str),
1819 Self::Macro => format!("{}!", path_str),
1820 Self::RemoveDisambiguator => path_str.into(),
1828 sp: rustc_span::Span,
1829 ) -> Vec<(rustc_span::Span, String)> {
1830 let inner_sp = match ori_link.find('(') {
1831 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1834 let inner_sp = match ori_link.find('!') {
1835 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1838 let inner_sp = match ori_link.find('@') {
1839 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1843 Self::Prefix(prefix) => {
1844 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1845 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1846 if sp.hi() != inner_sp.hi() {
1847 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1852 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1853 if sp.lo() != inner_sp.lo() {
1854 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1859 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1860 if sp.lo() != inner_sp.lo() {
1861 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1865 Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1870 /// Reports a diagnostic for an intra-doc link.
1872 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1873 /// the entire documentation block is used for the lint. If a range is provided but the span
1874 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1876 /// The `decorate` callback is invoked in all cases to allow further customization of the
1877 /// diagnostic before emission. If the span of the link was able to be determined, the second
1878 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1880 fn report_diagnostic(
1882 lint: &'static Lint,
1884 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1885 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1887 let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1888 Some(hir_id) => hir_id,
1890 // If non-local, no need to check anything.
1891 info!("ignoring warning from parent crate: {}", msg);
1896 let sp = item.attr_span(tcx);
1898 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1899 let mut diag = lint.build(msg);
1902 super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1903 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1904 && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1906 sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1912 if let Some(sp) = span {
1915 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1918 // last_new_line_offset
1919 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1920 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1922 // Print the line containing the `link_range` and manually mark it with '^'s.
1924 "the link appears in this line:\n\n{line}\n\
1925 {indicator: <before$}{indicator:^<found$}",
1928 before = link_range.start - last_new_line_offset,
1929 found = link_range.len(),
1933 decorate(&mut diag, span);
1939 /// Reports a link that failed to resolve.
1941 /// This also tries to resolve any intermediate path segments that weren't
1942 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1943 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1944 fn resolution_failure(
1945 collector: &mut LinkCollector<'_, '_>,
1946 diag_info: DiagnosticInfo<'_>,
1948 disambiguator: Option<Disambiguator>,
1949 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1951 let tcx = collector.cx.tcx;
1954 BROKEN_INTRA_DOC_LINKS,
1955 &format!("unresolved link to `{}`", path_str),
1958 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1959 let assoc_item_not_allowed = |res: Res| {
1960 let name = res.name(tcx);
1962 "`{}` is {} {}, not a module or type, and cannot have associated items",
1968 // ignore duplicates
1969 let mut variants_seen = SmallVec::<[_; 3]>::new();
1970 for mut failure in kinds {
1971 let variant = std::mem::discriminant(&failure);
1972 if variants_seen.contains(&variant) {
1975 variants_seen.push(variant);
1977 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1982 let module_id = *module_id;
1983 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1984 // FIXME: maybe use itertools `collect_tuple` instead?
1985 fn split(path: &str) -> Option<(&str, &str)> {
1986 let mut splitter = path.rsplitn(2, "::");
1987 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1990 // Check if _any_ parent of the path gets resolved.
1991 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1992 let mut name = path_str;
1994 let (start, end) = if let Some(x) = split(name) {
1997 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1998 if partial_res.is_none() {
1999 *unresolved = name.into();
2004 for ns in [TypeNS, ValueNS, MacroNS] {
2005 if let Some(res) = collector.check_full_res(ns, start, module_id, &None)
2007 debug!("found partial_res={:?}", res);
2008 *partial_res = Some(res);
2009 *unresolved = end.into();
2013 *unresolved = end.into();
2016 let last_found_module = match *partial_res {
2017 Some(Res::Def(DefKind::Mod, id)) => Some(id),
2018 None => Some(module_id),
2021 // See if this was a module: `[path]` or `[std::io::nope]`
2022 if let Some(module) = last_found_module {
2023 let note = if partial_res.is_some() {
2024 // Part of the link resolved; e.g. `std::io::nonexistent`
2025 let module_name = tcx.item_name(module);
2026 format!("no item named `{}` in module `{}`", unresolved, module_name)
2028 // None of the link resolved; e.g. `Notimported`
2029 format!("no item named `{}` in scope", unresolved)
2031 if let Some(span) = sp {
2032 diag.span_label(span, ¬e);
2037 // If the link has `::` in it, assume it was meant to be an intra-doc link.
2038 // Otherwise, the `[]` might be unrelated.
2039 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
2040 if !path_str.contains("::") {
2041 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
2047 // Otherwise, it must be an associated item or variant
2048 let res = partial_res.expect("None case was handled by `last_found_module`");
2049 let name = res.name(tcx);
2050 let kind = match res {
2051 Res::Def(kind, _) => Some(kind),
2052 Res::Primitive(_) => None,
2054 let path_description = if let Some(kind) = kind {
2056 Mod | ForeignMod => "inner item",
2057 Struct => "field or associated item",
2058 Enum | Union => "variant or associated item",
2076 let note = assoc_item_not_allowed(res);
2077 if let Some(span) = sp {
2078 diag.span_label(span, ¬e);
2084 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
2085 | Static => "associated item",
2086 Impl | GlobalAsm => unreachable!("not a path"),
2092 "the {} `{}` has no {} named `{}`",
2095 disambiguator.map_or(path_description, |d| d.descr()),
2098 if let Some(span) = sp {
2099 diag.span_label(span, ¬e);
2106 let note = match failure {
2107 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2108 ResolutionFailure::Dummy => continue,
2109 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2110 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2113 "this link resolves to {}, which is not in the {} namespace",
2118 ResolutionFailure::NoParentItem => {
2119 diag.level = rustc_errors::Level::Bug;
2120 "all intra-doc links should have a parent item".to_owned()
2122 ResolutionFailure::MalformedGenerics(variant) => match variant {
2123 MalformedGenerics::UnbalancedAngleBrackets => {
2124 String::from("unbalanced angle brackets")
2126 MalformedGenerics::MissingType => {
2127 String::from("missing type for generic parameters")
2129 MalformedGenerics::HasFullyQualifiedSyntax => {
2130 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2131 String::from("fully-qualified syntax is unsupported")
2133 MalformedGenerics::InvalidPathSeparator => {
2134 String::from("has invalid path separator")
2136 MalformedGenerics::TooManyAngleBrackets => {
2137 String::from("too many angle brackets")
2139 MalformedGenerics::EmptyAngleBrackets => {
2140 String::from("empty angle brackets")
2144 if let Some(span) = sp {
2145 diag.span_label(span, ¬e);
2154 /// Report an anchor failure.
2155 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2156 let (msg, anchor_idx) = match failure {
2157 AnchorFailure::MultipleAnchors => {
2158 (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2160 AnchorFailure::RustdocAnchorConflict(res) => (
2162 "`{}` contains an anchor, but links to {kind}s are already anchored",
2170 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2171 if let Some(mut sp) = sp {
2172 if let Some((fragment_offset, _)) =
2173 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2175 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2177 diag.span_label(sp, "invalid anchor");
2179 if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2180 if let Some(sp) = sp {
2181 span_bug!(sp, "anchors should be allowed now");
2183 bug!("anchors should be allowed now");
2189 /// Report an error in the link disambiguator.
2190 fn disambiguator_error(
2191 cx: &DocContext<'_>,
2192 mut diag_info: DiagnosticInfo<'_>,
2193 disambiguator_range: Range<usize>,
2196 diag_info.link_range = disambiguator_range;
2197 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2199 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2200 crate::DOC_RUST_LANG_ORG_CHANNEL
2206 /// Report an ambiguity error, where there were multiple possible resolutions.
2208 cx: &DocContext<'_>,
2209 diag_info: DiagnosticInfo<'_>,
2211 candidates: Vec<Res>,
2213 let mut msg = format!("`{}` is ", path_str);
2215 match candidates.as_slice() {
2216 [first_def, second_def] => {
2218 "both {} {} and {} {}",
2219 first_def.article(),
2221 second_def.article(),
2226 let mut candidates = candidates.iter().peekable();
2227 while let Some(res) = candidates.next() {
2228 if candidates.peek().is_some() {
2229 msg += &format!("{} {}, ", res.article(), res.descr());
2231 msg += &format!("and {} {}", res.article(), res.descr());
2237 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2238 if let Some(sp) = sp {
2239 diag.span_label(sp, "ambiguous link");
2241 diag.note("ambiguous link");
2244 for res in candidates {
2245 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2250 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2252 fn suggest_disambiguator(
2254 diag: &mut DiagnosticBuilder<'_>,
2257 sp: Option<rustc_span::Span>,
2259 let suggestion = res.disambiguator_suggestion();
2260 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2262 if let Some(sp) = sp {
2263 let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2264 if spans.len() > 1 {
2265 diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2267 let (sp, suggestion_text) = spans.pop().unwrap();
2268 diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2271 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2275 /// Report a link from a public item to a private one.
2276 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2278 let item_name = match diag_info.item.name {
2283 None => "<unknown>",
2286 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2288 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2289 if let Some(sp) = sp {
2290 diag.span_label(sp, "this item is private");
2293 let note_msg = if cx.render_options.document_private {
2294 "this link resolves only because you passed `--document-private-items`, but will break without"
2296 "this link will resolve properly if you pass `--document-private-items`"
2298 diag.note(note_msg);
2302 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2304 cx: &DocContext<'_>,
2306 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'static>> {
2308 .parent(res.def_id(cx.tcx))
2310 let parent_def = Res::Def(DefKind::Enum, parent);
2311 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2312 (parent_def, Some(ItemFragment(FragmentKind::Variant, variant.def_id)))
2314 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2317 /// Resolve a primitive type or value.
2318 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2322 use PrimitiveType::*;
2323 let prim = match path_str {
2339 "bool" | "true" | "false" => Bool,
2340 "str" | "&str" => Str,
2341 // See #80181 for why these don't have symbols associated.
2346 "pointer" | "*const" | "*mut" => RawPointer,
2347 "reference" | "&" | "&mut" => Reference,
2349 "never" | "!" => Never,
2352 debug!("resolved primitives {:?}", prim);
2353 Some(Res::Primitive(prim))
2356 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2357 let mut stripped_segments = vec![];
2358 let mut path = path_str.chars().peekable();
2359 let mut segment = Vec::new();
2361 while let Some(chr) = path.next() {
2364 if path.next_if_eq(&':').is_some() {
2365 let stripped_segment =
2366 strip_generics_from_path_segment(mem::take(&mut segment))?;
2367 if !stripped_segment.is_empty() {
2368 stripped_segments.push(stripped_segment);
2371 return Err(ResolutionFailure::MalformedGenerics(
2372 MalformedGenerics::InvalidPathSeparator,
2381 return Err(ResolutionFailure::MalformedGenerics(
2382 MalformedGenerics::TooManyAngleBrackets,
2386 return Err(ResolutionFailure::MalformedGenerics(
2387 MalformedGenerics::EmptyAngleBrackets,
2393 while let Some(chr) = path.next_if(|c| *c != '>') {
2400 _ => segment.push(chr),
2402 trace!("raw segment: {:?}", segment);
2405 if !segment.is_empty() {
2406 let stripped_segment = strip_generics_from_path_segment(segment)?;
2407 if !stripped_segment.is_empty() {
2408 stripped_segments.push(stripped_segment);
2412 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2414 let stripped_path = stripped_segments.join("::");
2416 if !stripped_path.is_empty() {
2419 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2423 fn strip_generics_from_path_segment(
2425 ) -> Result<String, ResolutionFailure<'static>> {
2426 let mut stripped_segment = String::new();
2427 let mut param_depth = 0;
2429 let mut latest_generics_chunk = String::new();
2434 latest_generics_chunk.clear();
2435 } else if c == '>' {
2437 if latest_generics_chunk.contains(" as ") {
2438 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2439 // Give a helpful error message instead of completely ignoring the angle brackets.
2440 return Err(ResolutionFailure::MalformedGenerics(
2441 MalformedGenerics::HasFullyQualifiedSyntax,
2445 if param_depth == 0 {
2446 stripped_segment.push(c);
2448 latest_generics_chunk.push(c);
2453 if param_depth == 0 {
2454 Ok(stripped_segment)
2456 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2457 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))