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, stable_set::FxHashSet};
6 use rustc_errors::{Applicability, DiagnosticBuilder};
12 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_ID};
13 use rustc_middle::ty::{DefIdTree, Ty, TyCtxt};
14 use rustc_middle::{bug, span_bug, ty};
15 use rustc_session::lint::Lint;
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::symbol::{sym, Ident, Symbol};
18 use rustc_span::{BytePos, DUMMY_SP};
19 use smallvec::{smallvec, SmallVec};
21 use pulldown_cmark::LinkType;
24 use std::convert::{TryFrom, TryInto};
29 use crate::clean::{self, utils::find_nearest_parent_module, Crate, Item, ItemLink, PrimitiveType};
30 use crate::core::DocContext;
31 use crate::html::markdown::{markdown_links, MarkdownLink};
32 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
33 use crate::passes::Pass;
34 use crate::visit::DocVisitor;
37 crate use early::early_resolve_intra_doc_links;
39 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
40 name: "collect-intra-doc-links",
41 run: collect_intra_doc_links,
42 description: "resolves intra-doc links",
45 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
47 LinkCollector { cx, mod_ids: Vec::new(), visited_links: FxHashMap::default() };
48 collector.visit_crate(&krate);
52 /// Top-level errors emitted by this pass.
54 Resolve(Box<ResolutionFailure<'a>>),
55 AnchorFailure(AnchorFailure),
58 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
59 fn from(err: ResolutionFailure<'a>) -> Self {
60 ErrorKind::Resolve(box err)
64 #[derive(Copy, Clone, Debug, Hash)]
67 Primitive(PrimitiveType),
70 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
73 fn descr(self) -> &'static str {
75 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
76 Res::Primitive(_) => "builtin type",
80 fn article(self) -> &'static str {
82 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
83 Res::Primitive(_) => "a",
87 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
89 Res::Def(_, id) => tcx.item_name(id),
90 Res::Primitive(prim) => prim.as_sym(),
94 fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
96 Res::Def(_, id) => id,
97 Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
101 fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
103 Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
104 // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
105 Res::Primitive(_) => None,
109 /// Used for error reporting.
110 fn disambiguator_suggestion(self) -> Suggestion {
111 let kind = match self {
112 Res::Primitive(_) => return Suggestion::Prefix("prim"),
113 Res::Def(kind, _) => kind,
115 if kind == DefKind::Macro(MacroKind::Bang) {
116 return Suggestion::Macro;
117 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
118 return Suggestion::Function;
119 } else if kind == DefKind::Field {
120 return Suggestion::RemoveDisambiguator;
123 let prefix = match kind {
124 DefKind::Struct => "struct",
125 DefKind::Enum => "enum",
126 DefKind::Trait => "trait",
127 DefKind::Union => "union",
128 DefKind::Mod => "mod",
129 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
132 DefKind::Static => "static",
133 DefKind::Macro(MacroKind::Derive) => "derive",
134 // Now handle things that don't have a specific disambiguator
137 .expect("tried to calculate a disambiguator for a def without a namespace?")
139 Namespace::TypeNS => "type",
140 Namespace::ValueNS => "value",
141 Namespace::MacroNS => "macro",
145 Suggestion::Prefix(prefix)
149 impl TryFrom<ResolveRes> for Res {
152 fn try_from(res: ResolveRes) -> Result<Self, ()> {
153 use rustc_hir::def::Res::*;
155 Def(kind, id) => Ok(Res::Def(kind, id)),
156 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
158 NonMacroAttr(..) | Err => Result::Err(()),
159 other => bug!("unrecognized res {:?}", other),
164 /// A link failed to resolve.
166 enum ResolutionFailure<'a> {
167 /// This resolved, but with the wrong namespace.
169 /// What the link resolved to.
171 /// The expected namespace for the resolution, determined from the link's disambiguator.
173 /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
174 /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
175 expected_ns: Namespace,
177 /// The link failed to resolve. [`resolution_failure`] should look to see if there's
178 /// a more helpful error that can be given.
180 /// The scope the link was resolved in.
182 /// If part of the link resolved, this has the `Res`.
184 /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
185 partial_res: Option<Res>,
186 /// The remaining unresolved path segments.
188 /// In `[std::io::Error::x]`, `x` would be unresolved.
189 unresolved: Cow<'a, str>,
191 /// This happens when rustdoc can't determine the parent scope for an item.
192 /// It is always a bug in rustdoc.
194 /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
195 MalformedGenerics(MalformedGenerics),
196 /// Used to communicate that this should be ignored, but shouldn't be reported to the user.
198 /// This happens when there is no disambiguator and one of the namespaces
199 /// failed to resolve.
204 enum MalformedGenerics {
205 /// This link has unbalanced angle brackets.
207 /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
208 UnbalancedAngleBrackets,
209 /// The generics are not attached to a type.
211 /// For example, `<T>` should trigger this.
213 /// This is detected by checking if the path is empty after the generics are stripped.
215 /// The link uses fully-qualified syntax, which is currently unsupported.
217 /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
219 /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
221 HasFullyQualifiedSyntax,
222 /// The link has an invalid path separator.
224 /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
225 /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
228 /// Note that this will also **not** be triggered if the invalid path separator is inside angle
229 /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
230 /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
232 /// This is detected by checking if there is a colon followed by a non-colon in the link.
233 InvalidPathSeparator,
234 /// The link has too many angle brackets.
236 /// For example, `Vec<<T>>` should trigger this.
237 TooManyAngleBrackets,
238 /// The link has empty angle brackets.
240 /// For example, `Vec<>` should trigger this.
244 impl ResolutionFailure<'_> {
245 /// This resolved fully (not just partially) but is erroneous for some other reason
247 /// Returns the full resolution of the link, if present.
248 fn full_res(&self) -> Option<Res> {
250 Self::WrongNamespace { res, expected_ns: _ } => Some(*res),
257 /// User error: `[std#x#y]` is not valid
259 /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
261 /// This is an unfortunate state of affairs. Not every item that can be
262 /// linked to has its own page; sometimes it is a subheading within a page,
263 /// like for associated items. In those cases, rustdoc uses an anchor to
264 /// link to the subheading. Since you can't have two anchors for the same
265 /// link, Rustdoc disallows having a user-specified anchor.
267 /// Most of the time this is fine, because you can just link to the page of
268 /// the item if you want to provide your own anchor.
269 RustdocAnchorConflict(Res),
272 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
273 crate enum UrlFragment {
279 /// Render the fragment, including the leading `#`.
280 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
282 UrlFragment::Item(frag) => frag.render(s, tcx),
283 UrlFragment::UserWritten(raw) => write!(s, "#{}", raw),
288 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
289 crate struct ItemFragment(FragmentKind, DefId);
291 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
292 crate enum FragmentKind {
304 /// Create a fragment for an associated item.
305 #[instrument(level = "debug")]
306 fn from_assoc_item(item: &ty::AssocItem) -> Self {
307 let def_id = item.def_id;
309 ty::AssocKind::Fn => {
310 if item.defaultness.has_value() {
311 ItemFragment(FragmentKind::Method, def_id)
313 ItemFragment(FragmentKind::TyMethod, def_id)
316 ty::AssocKind::Const => ItemFragment(FragmentKind::AssociatedConstant, def_id),
317 ty::AssocKind::Type => ItemFragment(FragmentKind::AssociatedType, def_id),
321 /// Render the fragment, including the leading `#`.
322 crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
325 ItemFragment(kind, def_id) => {
326 let name = tcx.item_name(def_id);
328 FragmentKind::Method => write!(s, "method.{}", name),
329 FragmentKind::TyMethod => write!(s, "tymethod.{}", name),
330 FragmentKind::AssociatedConstant => write!(s, "associatedconstant.{}", name),
331 FragmentKind::AssociatedType => write!(s, "associatedtype.{}", name),
332 FragmentKind::StructField => write!(s, "structfield.{}", name),
333 FragmentKind::Variant => write!(s, "variant.{}", name),
334 FragmentKind::VariantField => {
335 let variant = tcx.item_name(tcx.parent(def_id).unwrap());
336 write!(s, "variant.{}.field.{}", variant, name)
344 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
345 struct ResolutionInfo {
347 dis: Option<Disambiguator>,
349 extra_fragment: Option<String>,
353 struct DiagnosticInfo<'a> {
357 link_range: Range<usize>,
360 #[derive(Clone, Debug, Hash)]
362 res: (Res, Option<UrlFragment>),
365 struct LinkCollector<'a, 'tcx> {
366 cx: &'a mut DocContext<'tcx>,
367 /// A stack of modules used to decide what scope to resolve in.
369 /// The last module will be used if the parent scope of the current item is
372 /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
373 /// The link will be `None` if it could not be resolved (i.e. the error was cached).
374 visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
377 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
378 /// Given a full link, parse it as an [enum struct variant].
380 /// In particular, this will return an error whenever there aren't three
381 /// full path segments left in the link.
383 /// [enum struct variant]: rustc_hir::VariantData::Struct
384 fn variant_field<'path>(
386 path_str: &'path str,
388 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
389 let tcx = self.cx.tcx;
390 let no_res = || ResolutionFailure::NotResolved {
393 unresolved: path_str.into(),
396 debug!("looking for enum variant {}", path_str);
397 let mut split = path_str.rsplitn(3, "::");
398 let variant_field_name = split
400 .map(|f| Symbol::intern(f))
401 .expect("fold_item should ensure link is non-empty");
403 // we're not sure this is a variant at all, so use the full string
404 // If there's no second component, the link looks like `[path]`.
405 // So there's no partial res and we should say the whole link failed to resolve.
406 split.next().map(|f| Symbol::intern(f)).ok_or_else(no_res)?;
409 .map(|f| f.to_owned())
410 // If there's no third component, we saw `[a::b]` before and it failed to resolve.
411 // So there's no partial res.
412 .ok_or_else(no_res)?;
415 .enter_resolver(|resolver| {
416 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
418 .and_then(|(_, res)| res.try_into())
419 .map_err(|()| no_res())?;
422 Res::Def(DefKind::Enum, did) => {
426 .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
427 .any(|item| item.name == variant_name)
429 // This is just to let `fold_item` know that this shouldn't be considered;
430 // it's a bug for the error to make it to the user
431 return Err(ResolutionFailure::Dummy.into());
433 match tcx.type_of(did).kind() {
434 ty::Adt(def, _) if def.is_enum() => {
435 if let Some(field) = def.all_fields().find(|f| f.name == variant_field_name)
437 Ok((ty_res, Some(ItemFragment(FragmentKind::VariantField, field.did))))
439 Err(ResolutionFailure::NotResolved {
441 partial_res: Some(Res::Def(DefKind::Enum, def.did)),
442 unresolved: variant_field_name.to_string().into(),
450 _ => Err(ResolutionFailure::NotResolved {
452 partial_res: Some(ty_res),
453 unresolved: variant_name.to_string().into(),
459 /// Given a primitive type, try to resolve an associated item.
460 fn resolve_primitive_associated_item(
462 prim_ty: PrimitiveType,
465 ) -> Option<(Res, ItemFragment)> {
466 let tcx = self.cx.tcx;
468 prim_ty.impls(tcx).into_iter().find_map(|&impl_| {
469 tcx.associated_items(impl_)
470 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
472 let fragment = ItemFragment::from_assoc_item(item);
473 (Res::Primitive(prim_ty), fragment)
478 /// Resolves a string as a macro.
480 /// FIXME(jynelson): Can this be unified with `resolve()`?
485 ) -> Result<Res, ResolutionFailure<'a>> {
486 self.cx.enter_resolver(|resolver| {
487 // NOTE: this needs 2 separate lookups because `resolve_str_path_error` doesn't take
488 // lexical scope into account (it ignores all macros not defined at the mod-level)
489 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
490 if let Ok((_, res)) =
491 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
493 // don't resolve builtins like `#[derive]`
494 if let Ok(res) = res.try_into() {
498 if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
499 return Ok(res.try_into().unwrap());
501 Err(ResolutionFailure::NotResolved {
504 unresolved: path_str.into(),
509 /// Convenience wrapper around `resolve_str_path_error`.
511 /// This also handles resolving `true` and `false` as booleans.
512 /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
513 /// Associated items will never be resolved by this function.
514 fn resolve_path(&self, path_str: &str, ns: Namespace, module_id: DefId) -> Option<Res> {
515 let result = self.cx.enter_resolver(|resolver| {
517 .resolve_str_path_error(DUMMY_SP, path_str, ns, module_id)
518 .and_then(|(_, res)| res.try_into())
520 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
522 // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
524 Err(()) => resolve_primitive(path_str, ns),
525 Ok(res) => Some(res),
529 /// Resolves a string as a path within a particular namespace. Returns an
530 /// optional URL fragment in the case of variants and methods.
533 path_str: &'path str,
536 user_fragment: &Option<String>,
537 ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'path>> {
538 let (res, rustdoc_fragment) = self.resolve_inner(path_str, ns, module_id)?;
539 let chosen_fragment = match (user_fragment, rustdoc_fragment) {
540 (Some(_), Some(r_frag)) => {
541 let diag_res = match r_frag {
542 ItemFragment(_, did) => Res::Def(self.cx.tcx.def_kind(did), did),
544 let failure = AnchorFailure::RustdocAnchorConflict(diag_res);
545 return Err(ErrorKind::AnchorFailure(failure));
547 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
548 (None, Some(r_frag)) => Some(UrlFragment::Item(r_frag)),
549 (None, None) => None,
551 Ok((res, chosen_fragment))
554 fn resolve_inner<'path>(
556 path_str: &'path str,
559 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
560 if let Some(res) = self.resolve_path(path_str, ns, module_id) {
562 // FIXME(#76467): make this fallthrough to lookup the associated
563 // item a separate function.
564 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
565 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
566 Res::Def(DefKind::Variant, _) => {
567 return handle_variant(self.cx, res);
569 // Not a trait item; just return what we found.
570 _ => return Ok((res, None)),
574 // Try looking for methods and associated items.
575 let mut split = path_str.rsplitn(2, "::");
576 // NB: `split`'s first element is always defined, even if the delimiter was not present.
577 // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
578 let item_str = split.next().unwrap();
579 let item_name = Symbol::intern(item_str);
580 let path_root = split
582 .map(|f| f.to_owned())
583 // If there's no `::`, it's not an associated item.
584 // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
586 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
587 ResolutionFailure::NotResolved {
590 unresolved: item_str.into(),
594 // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
595 // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
596 // error instead and special case *only* modules with `#[doc(primitive)]`, not all
598 resolve_primitive(&path_root, TypeNS)
599 .or_else(|| self.resolve_path(&path_root, TypeNS, module_id))
601 let (res, fragment) =
602 self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
604 Some(Ok((res, Some(fragment))))
607 if ns == Namespace::ValueNS {
608 self.variant_field(path_str, module_id)
610 Err(ResolutionFailure::NotResolved {
613 unresolved: path_root.into(),
620 /// Convert a DefId to a Res, where possible.
622 /// This is used for resolving type aliases.
623 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
624 use PrimitiveType::*;
625 Some(match *self.cx.tcx.type_of(ty_id).kind() {
626 ty::Bool => Res::Primitive(Bool),
627 ty::Char => Res::Primitive(Char),
628 ty::Int(ity) => Res::Primitive(ity.into()),
629 ty::Uint(uty) => Res::Primitive(uty.into()),
630 ty::Float(fty) => Res::Primitive(fty.into()),
631 ty::Str => Res::Primitive(Str),
632 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
633 ty::Tuple(_) => Res::Primitive(Tuple),
634 ty::Array(..) => Res::Primitive(Array),
635 ty::Slice(_) => Res::Primitive(Slice),
636 ty::RawPtr(_) => Res::Primitive(RawPointer),
637 ty::Ref(..) => Res::Primitive(Reference),
638 ty::FnDef(..) => panic!("type alias to a function definition"),
639 ty::FnPtr(_) => Res::Primitive(Fn),
640 ty::Never => Res::Primitive(Never),
641 ty::Adt(&ty::AdtDef { did, .. }, _) | ty::Foreign(did) => {
642 Res::Def(self.cx.tcx.def_kind(did), did)
647 | ty::GeneratorWitness(_)
654 | ty::Error(_) => return None,
658 /// Convert a PrimitiveType to a Ty, where possible.
660 /// This is used for resolving trait impls for primitives
661 fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
662 use PrimitiveType::*;
663 let tcx = self.cx.tcx;
665 // FIXME: Only simple types are supported here, see if we can support
666 // other types such as Tuple, Array, Slice, etc.
667 // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
668 Some(tcx.mk_ty(match prim {
673 I8 => ty::Int(ty::IntTy::I8),
674 I16 => ty::Int(ty::IntTy::I16),
675 I32 => ty::Int(ty::IntTy::I32),
676 I64 => ty::Int(ty::IntTy::I64),
677 I128 => ty::Int(ty::IntTy::I128),
678 Isize => ty::Int(ty::IntTy::Isize),
679 F32 => ty::Float(ty::FloatTy::F32),
680 F64 => ty::Float(ty::FloatTy::F64),
681 U8 => ty::Uint(ty::UintTy::U8),
682 U16 => ty::Uint(ty::UintTy::U16),
683 U32 => ty::Uint(ty::UintTy::U32),
684 U64 => ty::Uint(ty::UintTy::U64),
685 U128 => ty::Uint(ty::UintTy::U128),
686 Usize => ty::Uint(ty::UintTy::Usize),
691 /// Resolve an associated item, returning its containing page's `Res`
692 /// and the fragment targeting the associated item on its page.
693 fn resolve_associated_item(
699 ) -> Option<(Res, ItemFragment)> {
700 let tcx = self.cx.tcx;
703 Res::Primitive(prim) => {
704 self.resolve_primitive_associated_item(prim, ns, item_name).or_else(|| {
705 let assoc_item = self
706 .primitive_type_to_ty(prim)
708 resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
712 assoc_item.map(|item| {
713 let fragment = ItemFragment::from_assoc_item(&item);
718 Res::Def(DefKind::TyAlias, did) => {
719 // Resolve the link on the type the alias points to.
720 // FIXME: if the associated item is defined directly on the type alias,
721 // it will show up on its documentation page, we should link there instead.
722 let res = self.def_id_to_res(did)?;
723 self.resolve_associated_item(res, item_name, ns, module_id)
726 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy,
729 debug!("looking for associated item named {} for item {:?}", item_name, did);
730 // Checks if item_name belongs to `impl SomeItem`
735 tcx.associated_items(imp).find_by_name_and_namespace(
737 Ident::with_dummy_span(item_name),
743 // There should only ever be one associated item that matches from any inherent impl
745 // Check if item_name belongs to `impl SomeTrait for SomeItem`
746 // FIXME(#74563): This gives precedence to `impl SomeItem`:
747 // Although having both would be ambiguous, use impl version for compatibility's sake.
748 // To handle that properly resolve() would have to support
749 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
751 resolve_associated_trait_item(
760 debug!("got associated item {:?}", assoc_item);
762 if let Some(item) = assoc_item {
763 let fragment = ItemFragment::from_assoc_item(&item);
764 return Some((root_res, fragment));
767 if ns != Namespace::ValueNS {
770 debug!("looking for fields named {} for {:?}", item_name, did);
771 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
772 // NOTE: it's different from variant_field because it only resolves struct fields,
773 // not variant fields (2 path segments, not 3).
775 // We need to handle struct (and union) fields in this code because
776 // syntactically their paths are identical to associated item paths:
777 // `module::Type::field` and `module::Type::Assoc`.
779 // On the other hand, variant fields can't be mistaken for associated
780 // items because they look like this: `module::Type::Variant::field`.
782 // Variants themselves don't need to be handled here, even though
783 // they also look like associated items (`module::Type::Variant`),
784 // because they are real Rust syntax (unlike the intra-doc links
785 // field syntax) and are handled by the compiler's resolver.
786 let def = match tcx.type_of(did).kind() {
787 ty::Adt(def, _) if !def.is_enum() => def,
791 def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?;
792 Some((root_res, ItemFragment(FragmentKind::StructField, field.did)))
794 Res::Def(DefKind::Trait, did) => tcx
795 .associated_items(did)
796 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
798 let fragment = ItemFragment::from_assoc_item(item);
799 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
806 /// Used for reporting better errors.
808 /// Returns whether the link resolved 'fully' in another namespace.
809 /// 'fully' here means that all parts of the link resolved, not just some path segments.
810 /// This returns the `Res` even if it was erroneous for some reason
811 /// (such as having invalid URL fragments or being in the wrong namespace).
817 extra_fragment: &Option<String>,
819 // resolve() can't be used for macro namespace
820 let result = match ns {
821 Namespace::MacroNS => self
822 .resolve_macro(path_str, module_id)
823 .map(|res| (res, None))
824 .map_err(ErrorKind::from),
825 Namespace::TypeNS | Namespace::ValueNS => {
826 self.resolve(path_str, ns, module_id, extra_fragment)
830 let res = match result {
832 if let Some(UrlFragment::Item(ItemFragment(_, id))) = frag {
833 Some(Res::Def(self.cx.tcx.def_kind(id), id))
838 Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
839 Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
840 Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
846 /// Look to see if a resolved item has an associated item named `item_name`.
848 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
849 /// find `std::error::Error::source` and return
850 /// `<io::Error as error::Error>::source`.
851 fn resolve_associated_trait_item<'a>(
856 cx: &mut DocContext<'a>,
857 ) -> Option<ty::AssocItem> {
858 // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
859 // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
860 // meantime, just don't look for these blanket impls.
862 // Next consider explicit impls: `impl MyTrait for MyType`
863 // Give precedence to inherent impls.
864 let traits = trait_impls_for(cx, ty, module);
865 debug!("considering traits {:?}", traits);
866 let mut candidates = traits.iter().filter_map(|&(impl_, trait_)| {
868 .associated_items(trait_)
869 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
871 trait_assoc_to_impl_assoc_item(cx.tcx, impl_, trait_assoc.def_id)
872 .unwrap_or(trait_assoc)
875 // FIXME(#74563): warn about ambiguity
876 debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
877 candidates.next().copied()
880 /// Find the associated item in the impl `impl_id` that corresponds to the
881 /// trait associated item `trait_assoc_id`.
883 /// This function returns `None` if no associated item was found in the impl.
884 /// This can occur when the trait associated item has a default value that is
885 /// not overriden in the impl.
887 /// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
888 /// [`TyCtxt::associated_item()`] (with some helpful logging added).
889 #[instrument(level = "debug", skip(tcx))]
890 fn trait_assoc_to_impl_assoc_item<'tcx>(
893 trait_assoc_id: DefId,
894 ) -> Option<&'tcx ty::AssocItem> {
895 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
896 debug!(?trait_to_impl_assoc_map);
897 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
898 debug!(?impl_assoc_id);
899 let impl_assoc = tcx.associated_item(impl_assoc_id);
904 /// Given a type, return all trait impls in scope in `module` for that type.
905 /// Returns a set of pairs of `(impl_id, trait_id)`.
907 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
908 /// So it is not stable to serialize cross-crate.
909 #[instrument(level = "debug", skip(cx))]
910 fn trait_impls_for<'a>(
911 cx: &mut DocContext<'a>,
914 ) -> FxHashSet<(DefId, DefId)> {
916 let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
917 let trait_ = trait_candidate.def_id;
918 trace!("considering explicit impl for trait {:?}", trait_);
920 // Look at each trait implementation to see if it's an impl for `did`
921 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
922 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
923 // Check if these are the same type.
924 let impl_type = trait_ref.self_ty();
926 "comparing type {} with kind {:?} against type {:?}",
931 // Fast path: if this is a primitive simple `==` will work
932 // NOTE: the `match` is necessary; see #92662.
933 // this allows us to ignore generics because the user input
934 // may not include the generic placeholders
935 // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
936 let saw_impl = impl_type == ty
937 || match (impl_type.kind(), ty.kind()) {
938 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
939 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did, ty_def.did);
940 impl_def.did == ty_def.did
945 if saw_impl { Some((impl_, trait_)) } else { None }
951 /// Check for resolve collisions between a trait and its derive.
953 /// These are common and we should just resolve to the trait in that case.
954 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
958 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
959 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
965 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
966 fn visit_item(&mut self, item: &Item) {
968 item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
969 if parent_node.is_some() {
970 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
973 // find item's parent to resolve `Self` in item's docs below
974 debug!("looking for the `Self` type");
975 let self_id = match item.def_id.as_def_id() {
978 if (matches!(self.cx.tcx.def_kind(did), DefKind::Field)
980 self.cx.tcx.def_kind(self.cx.tcx.parent(did).unwrap()),
984 self.cx.tcx.parent(did).and_then(|item_id| self.cx.tcx.parent(item_id))
988 self.cx.tcx.def_kind(did),
996 self.cx.tcx.parent(did)
998 Some(did) => Some(did),
1001 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
1002 let self_name = self_id.and_then(|self_id| {
1003 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
1004 // using `ty.to_string()` (or any variant) has issues with raw idents
1005 let ty = self.cx.tcx.type_of(self_id);
1006 let name = match ty.kind() {
1007 ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
1008 other if other.is_primitive() => Some(ty.to_string()),
1011 debug!("using type_of(): {:?}", name);
1014 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
1015 debug!("using item_name(): {:?}", name);
1020 let inner_docs = item.inner_docs(self.cx.tcx);
1022 if item.is_mod() && inner_docs {
1023 self.mod_ids.push(item.def_id.expect_def_id());
1026 // We want to resolve in the lexical scope of the documentation.
1027 // In the presence of re-exports, this is not the same as the module of the item.
1028 // Rather than merging all documentation into one, resolve it one attribute at a time
1029 // so we know which module it came from.
1030 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
1031 debug!("combined_docs={}", doc);
1033 let (krate, parent_node) = if let Some(id) = parent_module {
1034 (id.krate, Some(id))
1036 (item.def_id.krate(), parent_node)
1038 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1039 // This is a degenerate case and it's not supported by rustdoc.
1040 for md_link in markdown_links(&doc) {
1041 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
1042 if let Some(link) = link {
1043 self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
1050 self.mod_ids.push(item.def_id.expect_def_id());
1053 self.visit_item_recur(item);
1056 self.visit_item_recur(item)
1061 enum PreprocessingError<'a> {
1062 Anchor(AnchorFailure),
1063 Disambiguator(Range<usize>, String),
1064 Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
1067 impl From<AnchorFailure> for PreprocessingError<'_> {
1068 fn from(err: AnchorFailure) -> Self {
1073 struct PreprocessingInfo {
1075 disambiguator: Option<Disambiguator>,
1076 extra_fragment: Option<String>,
1081 /// - `None` if the link should be ignored.
1082 /// - `Some(Err)` if the link should emit an error
1083 /// - `Some(Ok)` if the link is valid
1085 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
1086 fn preprocess_link<'a>(
1087 ori_link: &'a MarkdownLink,
1088 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
1089 // [] is mostly likely not supposed to be a link
1090 if ori_link.link.is_empty() {
1094 // Bail early for real links.
1095 if ori_link.link.contains('/') {
1099 let stripped = ori_link.link.replace('`', "");
1100 let mut parts = stripped.split('#');
1102 let link = parts.next().unwrap();
1103 if link.trim().is_empty() {
1104 // This is an anchor to an element of the current page, nothing to do in here!
1107 let extra_fragment = parts.next();
1108 if parts.next().is_some() {
1109 // A valid link can't have multiple #'s
1110 return Some(Err(AnchorFailure::MultipleAnchors.into()));
1113 // Parse and strip the disambiguator from the link, if present.
1114 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1115 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1116 Ok(None) => (None, link.trim(), link.trim()),
1117 Err((err_msg, relative_range)) => {
1118 // Only report error if we would not have ignored this link. See issue #83859.
1119 if !should_ignore_link_with_disambiguators(link) {
1120 let no_backticks_range = range_between_backticks(ori_link);
1121 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1122 ..(no_backticks_range.start + relative_range.end);
1123 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1130 if should_ignore_link(path_str) {
1134 // Strip generics from the path.
1135 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1136 match strip_generics_from_path(path_str) {
1139 debug!("link has malformed generics: {}", path_str);
1140 return Some(Err(PreprocessingError::Resolution(
1142 path_str.to_owned(),
1151 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1152 assert!(!path_str.contains(['<', '>'].as_slice()));
1154 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1155 if path_str.contains(' ') {
1159 Some(Ok(PreprocessingInfo {
1162 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1163 link_text: link_text.to_owned(),
1167 impl LinkCollector<'_, '_> {
1168 /// This is the entry point for resolving an intra-doc link.
1170 /// FIXME(jynelson): this is way too many arguments
1175 self_name: &Option<String>,
1176 parent_node: Option<DefId>,
1178 ori_link: MarkdownLink,
1179 ) -> Option<ItemLink> {
1180 trace!("considering link '{}'", ori_link.link);
1182 let diag_info = DiagnosticInfo {
1185 ori_link: &ori_link.link,
1186 link_range: ori_link.range.clone(),
1189 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1190 match preprocess_link(&ori_link)? {
1194 PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1195 PreprocessingError::Disambiguator(range, msg) => {
1196 disambiguator_error(self.cx, diag_info, range, &msg)
1198 PreprocessingError::Resolution(err, path_str, disambiguator) => {
1211 let mut path_str = &*path_str;
1213 let inner_docs = item.inner_docs(self.cx.tcx);
1215 // In order to correctly resolve intra-doc links we need to
1216 // pick a base AST node to work from. If the documentation for
1217 // this module came from an inner comment (//!) then we anchor
1218 // our name resolution *inside* the module. If, on the other
1219 // hand it was an outer comment (///) then we anchor the name
1220 // resolution in the parent module on the basis that the names
1221 // used are more likely to be intended to be parent names. For
1222 // this, we set base_node to None for inner comments since
1223 // we've already pushed this node onto the resolution stack but
1224 // for outer comments we explicitly try and resolve against the
1225 // parent_node first.
1227 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1229 let mut module_id = if let Some(id) = base_node {
1233 debug!("attempting to resolve item without parent module: {}", path_str);
1239 smallvec![ResolutionFailure::NoParentItem],
1245 // replace `Self` with suitable item's parent name
1246 let is_lone_self = path_str == "Self";
1247 let is_lone_crate = path_str == "crate";
1248 if path_str.starts_with("Self::") || is_lone_self {
1249 if let Some(ref name) = self_name {
1253 resolved_self = format!("{}::{}", name, &path_str[6..]);
1254 path_str = &resolved_self;
1257 } else if path_str.starts_with("crate::") || is_lone_crate {
1258 use rustc_span::def_id::CRATE_DEF_INDEX;
1260 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1261 // But rustdoc wants it to mean the crate this item was originally present in.
1262 // To work around this, remove it and resolve relative to the crate root instead.
1263 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1264 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1265 // FIXME(#78696): This doesn't always work.
1269 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1270 path_str = &resolved_self;
1272 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1275 let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1279 path_str: path_str.to_owned(),
1282 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1283 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1286 // Check for a primitive which might conflict with a module
1287 // Report the ambiguity and require that the user specify which one they meant.
1288 // FIXME: could there ever be a primitive not in the type namespace?
1291 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1292 ) && !matches!(res, Res::Primitive(_))
1294 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1296 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1299 // `[char]` when a `char` module is in scope
1300 let candidates = vec![res, prim];
1301 ambiguity_error(self.cx, diag_info, path_str, candidates);
1308 Res::Primitive(prim) => {
1309 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1310 // We're actually resolving an associated item of a primitive, so we need to
1311 // verify the disambiguator (if any) matches the type of the associated item.
1312 // This case should really follow the same flow as the `Res::Def` branch below,
1313 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1314 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1315 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1316 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1317 // for discussion on the matter.
1318 let kind = self.cx.tcx.def_kind(id);
1319 self.verify_disambiguator(
1329 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1330 // However I'm not sure how to check that across crates.
1331 if prim == PrimitiveType::RawPointer
1332 && item.def_id.is_local()
1333 && !self.cx.tcx.features().intra_doc_pointers
1335 self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1338 match disambiguator {
1339 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1341 self.report_disambiguator_mismatch(
1342 path_str, &ori_link, other, res, &diag_info,
1350 link: ori_link.link,
1352 did: res.def_id(self.cx.tcx),
1356 Res::Def(kind, id) => {
1357 let (kind_for_dis, id_for_dis) =
1358 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1359 (self.cx.tcx.def_kind(id), id)
1363 self.verify_disambiguator(
1372 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1373 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1378 fn verify_disambiguator(
1381 ori_link: &MarkdownLink,
1384 disambiguator: Option<Disambiguator>,
1386 diag_info: &DiagnosticInfo<'_>,
1388 debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1390 // Disallow e.g. linking to enums with `struct@`
1391 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1392 match (kind, disambiguator) {
1393 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1394 // NOTE: this allows 'method' to mean both normal functions and associated functions
1395 // This can't cause ambiguity because both are in the same namespace.
1396 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1397 // These are namespaces; allow anything in the namespace to match
1398 | (_, Some(Disambiguator::Namespace(_)))
1399 // If no disambiguator given, allow anything
1401 // All of these are valid, so do nothing
1403 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1404 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1405 self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1410 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1411 if let Some((src_id, dst_id)) = id
1413 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1414 // would presumably panic if a fake `DefIndex` were passed.
1415 .and_then(|dst_id| {
1416 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1419 if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1420 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1422 privacy_error(self.cx, diag_info, path_str);
1429 fn report_disambiguator_mismatch(
1432 ori_link: &MarkdownLink,
1433 specified: Disambiguator,
1435 diag_info: &DiagnosticInfo<'_>,
1437 // The resolved item did not match the disambiguator; give a better error than 'not found'
1438 let msg = format!("incompatible link kind for `{}`", path_str);
1439 let callback = |diag: &mut DiagnosticBuilder<'_>, sp: Option<rustc_span::Span>| {
1441 "this link resolved to {} {}, which is not {} {}",
1444 specified.article(),
1447 if let Some(sp) = sp {
1448 diag.span_label(sp, ¬e);
1452 suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1454 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1457 fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1459 super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1460 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1461 rustc_session::parse::feature_err(
1462 &self.cx.tcx.sess.parse_sess,
1463 sym::intra_doc_pointers,
1465 "linking to associated items of raw pointers is experimental",
1467 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1471 fn resolve_with_disambiguator_cached(
1473 key: ResolutionInfo,
1474 diag: DiagnosticInfo<'_>,
1475 cache_resolution_failure: bool,
1476 ) -> Option<(Res, Option<UrlFragment>)> {
1477 if let Some(ref cached) = self.visited_links.get(&key) {
1480 return Some(cached.res.clone());
1482 None if cache_resolution_failure => return None,
1484 // Although we hit the cache and found a resolution error, this link isn't
1485 // supposed to cache those. Run link resolution again to emit the expected
1486 // resolution error.
1491 let res = self.resolve_with_disambiguator(&key, diag);
1493 // Cache only if resolved successfully - don't silence duplicate errors
1494 if let Some(res) = res {
1495 // Store result for the actual namespace
1496 self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1500 if cache_resolution_failure {
1501 // For reference-style links we only want to report one resolution error
1502 // so let's cache them as well.
1503 self.visited_links.insert(key, None);
1510 /// After parsing the disambiguator, resolve the main part of the link.
1511 // FIXME(jynelson): wow this is just so much
1512 fn resolve_with_disambiguator(
1514 key: &ResolutionInfo,
1515 diag: DiagnosticInfo<'_>,
1516 ) -> Option<(Res, Option<UrlFragment>)> {
1517 let disambiguator = key.dis;
1518 let path_str = &key.path_str;
1519 let base_node = key.module_id;
1520 let extra_fragment = &key.extra_fragment;
1522 match disambiguator.map(Disambiguator::ns) {
1523 Some(expected_ns @ (ValueNS | TypeNS)) => {
1524 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1525 Ok(res) => Some(res),
1526 Err(ErrorKind::Resolve(box mut kind)) => {
1527 // We only looked in one namespace. Try to give a better error if possible.
1528 if kind.full_res().is_none() {
1529 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1530 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1531 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1532 for new_ns in [other_ns, MacroNS] {
1534 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1536 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1541 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1542 // This could just be a normal link or a broken link
1543 // we could potentially check if something is
1544 // "intra-doc-link-like" and warn in that case.
1547 Err(ErrorKind::AnchorFailure(msg)) => {
1548 anchor_failure(self.cx, diag, msg);
1555 let mut candidates = PerNS {
1557 .resolve_macro(path_str, base_node)
1558 .map(|res| (res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1559 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1561 debug!("got res in TypeNS: {:?}", res);
1564 Err(ErrorKind::AnchorFailure(msg)) => {
1565 anchor_failure(self.cx, diag, msg);
1568 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1570 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1572 Err(ErrorKind::AnchorFailure(msg)) => {
1573 anchor_failure(self.cx, diag, msg);
1576 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1578 .and_then(|(res, fragment)| {
1579 // Constructors are picked up in the type namespace.
1581 Res::Def(DefKind::Ctor(..), _) => {
1582 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1585 match (fragment, extra_fragment.clone()) {
1586 (Some(fragment), Some(_)) => {
1587 // Shouldn't happen but who knows?
1588 Ok((res, Some(fragment)))
1590 (fragment, None) => Ok((res, fragment)),
1591 (None, fragment) => {
1592 Ok((res, fragment.map(UrlFragment::UserWritten)))
1600 let len = candidates.iter().filter(|res| res.is_ok()).count();
1608 candidates.into_iter().filter_map(|res| res.err()).collect(),
1610 // this could just be a normal link
1615 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1616 } else if len == 2 && is_derive_trait_collision(&candidates) {
1617 Some(candidates.type_ns.unwrap())
1619 if is_derive_trait_collision(&candidates) {
1620 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1622 // If we're reporting an ambiguity, don't mention the namespaces that failed
1623 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1624 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1629 match self.resolve_macro(path_str, base_node) {
1630 Ok(res) => Some((res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1632 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1633 for ns in [TypeNS, ValueNS] {
1635 self.check_full_res(ns, path_str, base_node, extra_fragment)
1638 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1642 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1651 /// Get the section of a link between the backticks,
1652 /// or the whole link if there aren't any backticks.
1660 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1661 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1662 let before_second_backtick_group = ori_link
1665 .skip(after_first_backtick_group)
1666 .position(|b| b == b'`')
1667 .unwrap_or(ori_link.link.len());
1668 (ori_link.range.start + after_first_backtick_group)
1669 ..(ori_link.range.start + before_second_backtick_group)
1672 /// Returns true if we should ignore `link` due to it being unlikely
1673 /// that it is an intra-doc link. `link` should still have disambiguators
1674 /// if there were any.
1676 /// The difference between this and [`should_ignore_link()`] is that this
1677 /// check should only be used on links that still have disambiguators.
1678 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1679 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1682 /// Returns true if we should ignore `path_str` due to it being unlikely
1683 /// that it is an intra-doc link.
1684 fn should_ignore_link(path_str: &str) -> bool {
1685 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1688 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1689 /// Disambiguators for a link.
1690 enum Disambiguator {
1693 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1695 /// `struct@` or `f()`
1698 Namespace(Namespace),
1701 impl Disambiguator {
1702 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1704 /// This returns `Ok(Some(...))` if a disambiguator was found,
1705 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1706 /// if there was a problem with the disambiguator.
1707 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1708 use Disambiguator::{Kind, Namespace as NS, Primitive};
1710 if let Some(idx) = link.find('@') {
1711 let (prefix, rest) = link.split_at(idx);
1712 let d = match prefix {
1713 "struct" => Kind(DefKind::Struct),
1714 "enum" => Kind(DefKind::Enum),
1715 "trait" => Kind(DefKind::Trait),
1716 "union" => Kind(DefKind::Union),
1717 "module" | "mod" => Kind(DefKind::Mod),
1718 "const" | "constant" => Kind(DefKind::Const),
1719 "static" => Kind(DefKind::Static),
1720 "function" | "fn" | "method" => Kind(DefKind::Fn),
1721 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1722 "type" => NS(Namespace::TypeNS),
1723 "value" => NS(Namespace::ValueNS),
1724 "macro" => NS(Namespace::MacroNS),
1725 "prim" | "primitive" => Primitive,
1726 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1728 Ok(Some((d, &rest[1..], &rest[1..])))
1731 ("!()", DefKind::Macro(MacroKind::Bang)),
1732 ("!{}", DefKind::Macro(MacroKind::Bang)),
1733 ("![]", DefKind::Macro(MacroKind::Bang)),
1734 ("()", DefKind::Fn),
1735 ("!", DefKind::Macro(MacroKind::Bang)),
1737 for (suffix, kind) in suffixes {
1738 if let Some(path_str) = link.strip_suffix(suffix) {
1739 // Avoid turning `!` or `()` into an empty string
1740 if !path_str.is_empty() {
1741 return Ok(Some((Kind(kind), path_str, link)));
1749 fn ns(self) -> Namespace {
1751 Self::Namespace(n) => n,
1753 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1755 Self::Primitive => TypeNS,
1759 fn article(self) -> &'static str {
1761 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1762 Self::Kind(k) => k.article(),
1763 Self::Primitive => "a",
1767 fn descr(self) -> &'static str {
1769 Self::Namespace(n) => n.descr(),
1770 // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1771 // printing "module" vs "crate" so using the wrong ID is not a huge problem
1772 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1773 Self::Primitive => "builtin type",
1778 /// A suggestion to show in a diagnostic.
1781 Prefix(&'static str),
1786 /// `foo` without any disambiguator
1787 RemoveDisambiguator,
1791 fn descr(&self) -> Cow<'static, str> {
1793 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1794 Self::Function => "add parentheses".into(),
1795 Self::Macro => "add an exclamation mark".into(),
1796 Self::RemoveDisambiguator => "remove the disambiguator".into(),
1800 fn as_help(&self, path_str: &str) -> String {
1801 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1803 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1804 Self::Function => format!("{}()", path_str),
1805 Self::Macro => format!("{}!", path_str),
1806 Self::RemoveDisambiguator => path_str.into(),
1814 sp: rustc_span::Span,
1815 ) -> Vec<(rustc_span::Span, String)> {
1816 let inner_sp = match ori_link.find('(') {
1817 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1820 let inner_sp = match ori_link.find('!') {
1821 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1824 let inner_sp = match ori_link.find('@') {
1825 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1829 Self::Prefix(prefix) => {
1830 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1831 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1832 if sp.hi() != inner_sp.hi() {
1833 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1838 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1839 if sp.lo() != inner_sp.lo() {
1840 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1845 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1846 if sp.lo() != inner_sp.lo() {
1847 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1851 Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1856 /// Reports a diagnostic for an intra-doc link.
1858 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1859 /// the entire documentation block is used for the lint. If a range is provided but the span
1860 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1862 /// The `decorate` callback is invoked in all cases to allow further customization of the
1863 /// diagnostic before emission. If the span of the link was able to be determined, the second
1864 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1866 fn report_diagnostic(
1868 lint: &'static Lint,
1870 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1871 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1873 let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1874 Some(hir_id) => hir_id,
1876 // If non-local, no need to check anything.
1877 info!("ignoring warning from parent crate: {}", msg);
1882 let sp = item.attr_span(tcx);
1884 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1885 let mut diag = lint.build(msg);
1888 super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1889 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1890 && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1892 sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1898 if let Some(sp) = span {
1901 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1904 // last_new_line_offset
1905 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1906 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1908 // Print the line containing the `link_range` and manually mark it with '^'s.
1910 "the link appears in this line:\n\n{line}\n\
1911 {indicator: <before$}{indicator:^<found$}",
1914 before = link_range.start - last_new_line_offset,
1915 found = link_range.len(),
1919 decorate(&mut diag, span);
1925 /// Reports a link that failed to resolve.
1927 /// This also tries to resolve any intermediate path segments that weren't
1928 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1929 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1930 fn resolution_failure(
1931 collector: &mut LinkCollector<'_, '_>,
1932 diag_info: DiagnosticInfo<'_>,
1934 disambiguator: Option<Disambiguator>,
1935 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1937 let tcx = collector.cx.tcx;
1940 BROKEN_INTRA_DOC_LINKS,
1941 &format!("unresolved link to `{}`", path_str),
1944 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1945 let assoc_item_not_allowed = |res: Res| {
1946 let name = res.name(tcx);
1948 "`{}` is {} {}, not a module or type, and cannot have associated items",
1954 // ignore duplicates
1955 let mut variants_seen = SmallVec::<[_; 3]>::new();
1956 for mut failure in kinds {
1957 let variant = std::mem::discriminant(&failure);
1958 if variants_seen.contains(&variant) {
1961 variants_seen.push(variant);
1963 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1968 let module_id = *module_id;
1969 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1970 // FIXME: maybe use itertools `collect_tuple` instead?
1971 fn split(path: &str) -> Option<(&str, &str)> {
1972 let mut splitter = path.rsplitn(2, "::");
1973 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1976 // Check if _any_ parent of the path gets resolved.
1977 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1978 let mut name = path_str;
1980 let (start, end) = if let Some(x) = split(name) {
1983 // avoid bug that marked [Quux::Z] as missing Z, not Quux
1984 if partial_res.is_none() {
1985 *unresolved = name.into();
1990 for ns in [TypeNS, ValueNS, MacroNS] {
1991 if let Some(res) = collector.check_full_res(ns, start, module_id, &None)
1993 debug!("found partial_res={:?}", res);
1994 *partial_res = Some(res);
1995 *unresolved = end.into();
1999 *unresolved = end.into();
2002 let last_found_module = match *partial_res {
2003 Some(Res::Def(DefKind::Mod, id)) => Some(id),
2004 None => Some(module_id),
2007 // See if this was a module: `[path]` or `[std::io::nope]`
2008 if let Some(module) = last_found_module {
2009 let note = if partial_res.is_some() {
2010 // Part of the link resolved; e.g. `std::io::nonexistent`
2011 let module_name = tcx.item_name(module);
2012 format!("no item named `{}` in module `{}`", unresolved, module_name)
2014 // None of the link resolved; e.g. `Notimported`
2015 format!("no item named `{}` in scope", unresolved)
2017 if let Some(span) = sp {
2018 diag.span_label(span, ¬e);
2023 // If the link has `::` in it, assume it was meant to be an intra-doc link.
2024 // Otherwise, the `[]` might be unrelated.
2025 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
2026 if !path_str.contains("::") {
2027 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
2033 // Otherwise, it must be an associated item or variant
2034 let res = partial_res.expect("None case was handled by `last_found_module`");
2035 let name = res.name(tcx);
2036 let kind = match res {
2037 Res::Def(kind, _) => Some(kind),
2038 Res::Primitive(_) => None,
2040 let path_description = if let Some(kind) = kind {
2042 Mod | ForeignMod => "inner item",
2043 Struct => "field or associated item",
2044 Enum | Union => "variant or associated item",
2062 let note = assoc_item_not_allowed(res);
2063 if let Some(span) = sp {
2064 diag.span_label(span, ¬e);
2070 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
2071 | Static => "associated item",
2072 Impl | GlobalAsm => unreachable!("not a path"),
2078 "the {} `{}` has no {} named `{}`",
2081 disambiguator.map_or(path_description, |d| d.descr()),
2084 if let Some(span) = sp {
2085 diag.span_label(span, ¬e);
2092 let note = match failure {
2093 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2094 ResolutionFailure::Dummy => continue,
2095 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2096 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2099 "this link resolves to {}, which is not in the {} namespace",
2104 ResolutionFailure::NoParentItem => {
2105 diag.level = rustc_errors::Level::Bug;
2106 "all intra-doc links should have a parent item".to_owned()
2108 ResolutionFailure::MalformedGenerics(variant) => match variant {
2109 MalformedGenerics::UnbalancedAngleBrackets => {
2110 String::from("unbalanced angle brackets")
2112 MalformedGenerics::MissingType => {
2113 String::from("missing type for generic parameters")
2115 MalformedGenerics::HasFullyQualifiedSyntax => {
2116 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2117 String::from("fully-qualified syntax is unsupported")
2119 MalformedGenerics::InvalidPathSeparator => {
2120 String::from("has invalid path separator")
2122 MalformedGenerics::TooManyAngleBrackets => {
2123 String::from("too many angle brackets")
2125 MalformedGenerics::EmptyAngleBrackets => {
2126 String::from("empty angle brackets")
2130 if let Some(span) = sp {
2131 diag.span_label(span, ¬e);
2140 /// Report an anchor failure.
2141 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2142 let (msg, anchor_idx) = match failure {
2143 AnchorFailure::MultipleAnchors => {
2144 (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2146 AnchorFailure::RustdocAnchorConflict(res) => (
2148 "`{}` contains an anchor, but links to {kind}s are already anchored",
2156 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2157 if let Some(mut sp) = sp {
2158 if let Some((fragment_offset, _)) =
2159 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2161 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2163 diag.span_label(sp, "invalid anchor");
2165 if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2166 if let Some(sp) = sp {
2167 span_bug!(sp, "anchors should be allowed now");
2169 bug!("anchors should be allowed now");
2175 /// Report an error in the link disambiguator.
2176 fn disambiguator_error(
2177 cx: &DocContext<'_>,
2178 mut diag_info: DiagnosticInfo<'_>,
2179 disambiguator_range: Range<usize>,
2182 diag_info.link_range = disambiguator_range;
2183 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2185 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2186 crate::DOC_RUST_LANG_ORG_CHANNEL
2192 /// Report an ambiguity error, where there were multiple possible resolutions.
2194 cx: &DocContext<'_>,
2195 diag_info: DiagnosticInfo<'_>,
2197 candidates: Vec<Res>,
2199 let mut msg = format!("`{}` is ", path_str);
2201 match candidates.as_slice() {
2202 [first_def, second_def] => {
2204 "both {} {} and {} {}",
2205 first_def.article(),
2207 second_def.article(),
2212 let mut candidates = candidates.iter().peekable();
2213 while let Some(res) = candidates.next() {
2214 if candidates.peek().is_some() {
2215 msg += &format!("{} {}, ", res.article(), res.descr());
2217 msg += &format!("and {} {}", res.article(), res.descr());
2223 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2224 if let Some(sp) = sp {
2225 diag.span_label(sp, "ambiguous link");
2227 diag.note("ambiguous link");
2230 for res in candidates {
2231 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2236 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2238 fn suggest_disambiguator(
2240 diag: &mut DiagnosticBuilder<'_>,
2243 sp: Option<rustc_span::Span>,
2245 let suggestion = res.disambiguator_suggestion();
2246 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2248 if let Some(sp) = sp {
2249 let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2250 if spans.len() > 1 {
2251 diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2253 let (sp, suggestion_text) = spans.pop().unwrap();
2254 diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2257 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2261 /// Report a link from a public item to a private one.
2262 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2264 let item_name = match diag_info.item.name {
2269 None => "<unknown>",
2272 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2274 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2275 if let Some(sp) = sp {
2276 diag.span_label(sp, "this item is private");
2279 let note_msg = if cx.render_options.document_private {
2280 "this link resolves only because you passed `--document-private-items`, but will break without"
2282 "this link will resolve properly if you pass `--document-private-items`"
2284 diag.note(note_msg);
2288 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2290 cx: &DocContext<'_>,
2292 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'static>> {
2294 .parent(res.def_id(cx.tcx))
2296 let parent_def = Res::Def(DefKind::Enum, parent);
2297 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2298 (parent_def, Some(ItemFragment(FragmentKind::Variant, variant.def_id)))
2300 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2303 /// Resolve a primitive type or value.
2304 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2308 use PrimitiveType::*;
2309 let prim = match path_str {
2325 "bool" | "true" | "false" => Bool,
2326 "str" | "&str" => Str,
2327 // See #80181 for why these don't have symbols associated.
2332 "pointer" | "*const" | "*mut" => RawPointer,
2333 "reference" | "&" | "&mut" => Reference,
2335 "never" | "!" => Never,
2338 debug!("resolved primitives {:?}", prim);
2339 Some(Res::Primitive(prim))
2342 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2343 let mut stripped_segments = vec![];
2344 let mut path = path_str.chars().peekable();
2345 let mut segment = Vec::new();
2347 while let Some(chr) = path.next() {
2350 if path.next_if_eq(&':').is_some() {
2351 let stripped_segment =
2352 strip_generics_from_path_segment(mem::take(&mut segment))?;
2353 if !stripped_segment.is_empty() {
2354 stripped_segments.push(stripped_segment);
2357 return Err(ResolutionFailure::MalformedGenerics(
2358 MalformedGenerics::InvalidPathSeparator,
2367 return Err(ResolutionFailure::MalformedGenerics(
2368 MalformedGenerics::TooManyAngleBrackets,
2372 return Err(ResolutionFailure::MalformedGenerics(
2373 MalformedGenerics::EmptyAngleBrackets,
2379 while let Some(chr) = path.next_if(|c| *c != '>') {
2386 _ => segment.push(chr),
2388 trace!("raw segment: {:?}", segment);
2391 if !segment.is_empty() {
2392 let stripped_segment = strip_generics_from_path_segment(segment)?;
2393 if !stripped_segment.is_empty() {
2394 stripped_segments.push(stripped_segment);
2398 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2400 let stripped_path = stripped_segments.join("::");
2402 if !stripped_path.is_empty() {
2405 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2409 fn strip_generics_from_path_segment(
2411 ) -> Result<String, ResolutionFailure<'static>> {
2412 let mut stripped_segment = String::new();
2413 let mut param_depth = 0;
2415 let mut latest_generics_chunk = String::new();
2420 latest_generics_chunk.clear();
2421 } else if c == '>' {
2423 if latest_generics_chunk.contains(" as ") {
2424 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2425 // Give a helpful error message instead of completely ignoring the angle brackets.
2426 return Err(ResolutionFailure::MalformedGenerics(
2427 MalformedGenerics::HasFullyQualifiedSyntax,
2431 if param_depth == 0 {
2432 stripped_segment.push(c);
2434 latest_generics_chunk.push(c);
2439 if param_depth == 0 {
2440 Ok(stripped_segment)
2442 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2443 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))