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, SyntaxContext};
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.ident.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 fn trait_impls_for<'a>(
924 cx: &mut DocContext<'a>,
927 ) -> FxHashSet<(DefId, DefId)> {
928 let mut resolver = cx.resolver.borrow_mut();
929 let in_scope_traits = cx.module_trait_cache.entry(module).or_insert_with(|| {
930 resolver.access(|resolver| {
931 let parent_scope = &ParentScope::module(resolver.expect_module(module), resolver);
933 .traits_in_scope(None, parent_scope, SyntaxContext::root(), None)
935 .map(|candidate| candidate.def_id)
941 let iter = in_scope_traits.iter().flat_map(|&trait_| {
942 trace!("considering explicit impl for trait {:?}", trait_);
944 // Look at each trait implementation to see if it's an impl for `did`
945 tcx.find_map_relevant_impl(trait_, ty, |impl_| {
946 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
947 // Check if these are the same type.
948 let impl_type = trait_ref.self_ty();
950 "comparing type {} with kind {:?} against type {:?}",
955 // Fast path: if this is a primitive simple `==` will work
956 // NOTE: the `match` is necessary; see #92662.
957 // this allows us to ignore generics because the user input
958 // may not include the generic placeholders
959 // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
960 let saw_impl = impl_type == ty
961 || match (impl_type.kind(), ty.kind()) {
962 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
963 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did, ty_def.did);
964 impl_def.did == ty_def.did
969 if saw_impl { Some((impl_, trait_)) } else { None }
975 /// Check for resolve collisions between a trait and its derive.
977 /// These are common and we should just resolve to the trait in that case.
978 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
982 type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
983 macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
989 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
990 fn visit_item(&mut self, item: &Item) {
992 item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
993 if parent_node.is_some() {
994 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
997 // find item's parent to resolve `Self` in item's docs below
998 debug!("looking for the `Self` type");
999 let self_id = match item.def_id.as_def_id() {
1002 if (matches!(self.cx.tcx.def_kind(did), DefKind::Field)
1004 self.cx.tcx.def_kind(self.cx.tcx.parent(did).unwrap()),
1008 self.cx.tcx.parent(did).and_then(|item_id| self.cx.tcx.parent(item_id))
1012 self.cx.tcx.def_kind(did),
1020 self.cx.tcx.parent(did)
1022 Some(did) => Some(did),
1025 // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
1026 let self_name = self_id.and_then(|self_id| {
1027 if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
1028 // using `ty.to_string()` (or any variant) has issues with raw idents
1029 let ty = self.cx.tcx.type_of(self_id);
1030 let name = match ty.kind() {
1031 ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
1032 other if other.is_primitive() => Some(ty.to_string()),
1035 debug!("using type_of(): {:?}", name);
1038 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
1039 debug!("using item_name(): {:?}", name);
1044 let inner_docs = item.inner_docs(self.cx.tcx);
1046 if item.is_mod() && inner_docs {
1047 self.mod_ids.push(item.def_id.expect_def_id());
1050 // We want to resolve in the lexical scope of the documentation.
1051 // In the presence of re-exports, this is not the same as the module of the item.
1052 // Rather than merging all documentation into one, resolve it one attribute at a time
1053 // so we know which module it came from.
1054 for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
1055 debug!("combined_docs={}", doc);
1057 let (krate, parent_node) = if let Some(id) = parent_module {
1058 (id.krate, Some(id))
1060 (item.def_id.krate(), parent_node)
1062 // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1063 // This is a degenerate case and it's not supported by rustdoc.
1064 for md_link in markdown_links(&doc) {
1065 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
1066 if let Some(link) = link {
1067 self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
1074 self.mod_ids.push(item.def_id.expect_def_id());
1077 self.visit_item_recur(item);
1080 self.visit_item_recur(item)
1085 enum PreprocessingError<'a> {
1086 Anchor(AnchorFailure),
1087 Disambiguator(Range<usize>, String),
1088 Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
1091 impl From<AnchorFailure> for PreprocessingError<'_> {
1092 fn from(err: AnchorFailure) -> Self {
1097 struct PreprocessingInfo {
1099 disambiguator: Option<Disambiguator>,
1100 extra_fragment: Option<String>,
1105 /// - `None` if the link should be ignored.
1106 /// - `Some(Err)` if the link should emit an error
1107 /// - `Some(Ok)` if the link is valid
1109 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
1110 fn preprocess_link<'a>(
1111 ori_link: &'a MarkdownLink,
1112 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
1113 // [] is mostly likely not supposed to be a link
1114 if ori_link.link.is_empty() {
1118 // Bail early for real links.
1119 if ori_link.link.contains('/') {
1123 let stripped = ori_link.link.replace('`', "");
1124 let mut parts = stripped.split('#');
1126 let link = parts.next().unwrap();
1127 if link.trim().is_empty() {
1128 // This is an anchor to an element of the current page, nothing to do in here!
1131 let extra_fragment = parts.next();
1132 if parts.next().is_some() {
1133 // A valid link can't have multiple #'s
1134 return Some(Err(AnchorFailure::MultipleAnchors.into()));
1137 // Parse and strip the disambiguator from the link, if present.
1138 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1139 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1140 Ok(None) => (None, link.trim(), link.trim()),
1141 Err((err_msg, relative_range)) => {
1142 // Only report error if we would not have ignored this link. See issue #83859.
1143 if !should_ignore_link_with_disambiguators(link) {
1144 let no_backticks_range = range_between_backticks(ori_link);
1145 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1146 ..(no_backticks_range.start + relative_range.end);
1147 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1154 if should_ignore_link(path_str) {
1158 // Strip generics from the path.
1159 let path_str = if path_str.contains(['<', '>'].as_slice()) {
1160 match strip_generics_from_path(path_str) {
1163 debug!("link has malformed generics: {}", path_str);
1164 return Some(Err(PreprocessingError::Resolution(
1166 path_str.to_owned(),
1175 // Sanity check to make sure we don't have any angle brackets after stripping generics.
1176 assert!(!path_str.contains(['<', '>'].as_slice()));
1178 // The link is not an intra-doc link if it still contains spaces after stripping generics.
1179 if path_str.contains(' ') {
1183 Some(Ok(PreprocessingInfo {
1186 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1187 link_text: link_text.to_owned(),
1191 impl LinkCollector<'_, '_> {
1192 /// This is the entry point for resolving an intra-doc link.
1194 /// FIXME(jynelson): this is way too many arguments
1199 self_name: &Option<String>,
1200 parent_node: Option<DefId>,
1202 ori_link: MarkdownLink,
1203 ) -> Option<ItemLink> {
1204 trace!("considering link '{}'", ori_link.link);
1206 let diag_info = DiagnosticInfo {
1209 ori_link: &ori_link.link,
1210 link_range: ori_link.range.clone(),
1213 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1214 match preprocess_link(&ori_link)? {
1218 PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1219 PreprocessingError::Disambiguator(range, msg) => {
1220 disambiguator_error(self.cx, diag_info, range, &msg)
1222 PreprocessingError::Resolution(err, path_str, disambiguator) => {
1235 let mut path_str = &*path_str;
1237 let inner_docs = item.inner_docs(self.cx.tcx);
1239 // In order to correctly resolve intra-doc links we need to
1240 // pick a base AST node to work from. If the documentation for
1241 // this module came from an inner comment (//!) then we anchor
1242 // our name resolution *inside* the module. If, on the other
1243 // hand it was an outer comment (///) then we anchor the name
1244 // resolution in the parent module on the basis that the names
1245 // used are more likely to be intended to be parent names. For
1246 // this, we set base_node to None for inner comments since
1247 // we've already pushed this node onto the resolution stack but
1248 // for outer comments we explicitly try and resolve against the
1249 // parent_node first.
1251 if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1253 let mut module_id = if let Some(id) = base_node {
1257 debug!("attempting to resolve item without parent module: {}", path_str);
1263 smallvec![ResolutionFailure::NoParentItem],
1269 // replace `Self` with suitable item's parent name
1270 let is_lone_self = path_str == "Self";
1271 let is_lone_crate = path_str == "crate";
1272 if path_str.starts_with("Self::") || is_lone_self {
1273 if let Some(ref name) = self_name {
1277 resolved_self = format!("{}::{}", name, &path_str[6..]);
1278 path_str = &resolved_self;
1281 } else if path_str.starts_with("crate::") || is_lone_crate {
1282 use rustc_span::def_id::CRATE_DEF_INDEX;
1284 // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1285 // But rustdoc wants it to mean the crate this item was originally present in.
1286 // To work around this, remove it and resolve relative to the crate root instead.
1287 // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1288 // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1289 // FIXME(#78696): This doesn't always work.
1293 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1294 path_str = &resolved_self;
1296 module_id = DefId { krate, index: CRATE_DEF_INDEX };
1299 let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1303 path_str: path_str.to_owned(),
1306 diag_info.clone(), // this struct should really be Copy, but Range is not :(
1307 matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1310 // Check for a primitive which might conflict with a module
1311 // Report the ambiguity and require that the user specify which one they meant.
1312 // FIXME: could there ever be a primitive not in the type namespace?
1315 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1316 ) && !matches!(res, Res::Primitive(_))
1318 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1320 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1323 // `[char]` when a `char` module is in scope
1324 let candidates = vec![res, prim];
1325 ambiguity_error(self.cx, diag_info, path_str, candidates);
1332 Res::Primitive(prim) => {
1333 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1334 // We're actually resolving an associated item of a primitive, so we need to
1335 // verify the disambiguator (if any) matches the type of the associated item.
1336 // This case should really follow the same flow as the `Res::Def` branch below,
1337 // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1338 // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1339 // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1340 // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1341 // for discussion on the matter.
1342 let kind = self.cx.tcx.def_kind(id);
1343 self.verify_disambiguator(
1353 // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1354 // However I'm not sure how to check that across crates.
1355 if prim == PrimitiveType::RawPointer
1356 && item.def_id.is_local()
1357 && !self.cx.tcx.features().intra_doc_pointers
1359 self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1362 match disambiguator {
1363 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1365 self.report_disambiguator_mismatch(
1366 path_str, &ori_link, other, res, &diag_info,
1374 link: ori_link.link,
1376 did: res.def_id(self.cx.tcx),
1380 Res::Def(kind, id) => {
1381 let (kind_for_dis, id_for_dis) =
1382 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1383 (self.cx.tcx.def_kind(id), id)
1387 self.verify_disambiguator(
1396 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1397 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1402 fn verify_disambiguator(
1405 ori_link: &MarkdownLink,
1408 disambiguator: Option<Disambiguator>,
1410 diag_info: &DiagnosticInfo<'_>,
1412 debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1414 // Disallow e.g. linking to enums with `struct@`
1415 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1416 match (kind, disambiguator) {
1417 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1418 // NOTE: this allows 'method' to mean both normal functions and associated functions
1419 // This can't cause ambiguity because both are in the same namespace.
1420 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1421 // These are namespaces; allow anything in the namespace to match
1422 | (_, Some(Disambiguator::Namespace(_)))
1423 // If no disambiguator given, allow anything
1425 // All of these are valid, so do nothing
1427 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1428 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1429 self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1434 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1435 if let Some((src_id, dst_id)) = id
1437 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1438 // would presumably panic if a fake `DefIndex` were passed.
1439 .and_then(|dst_id| {
1440 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1443 if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1444 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1446 privacy_error(self.cx, diag_info, path_str);
1453 fn report_disambiguator_mismatch(
1456 ori_link: &MarkdownLink,
1457 specified: Disambiguator,
1459 diag_info: &DiagnosticInfo<'_>,
1461 // The resolved item did not match the disambiguator; give a better error than 'not found'
1462 let msg = format!("incompatible link kind for `{}`", path_str);
1463 let callback = |diag: &mut DiagnosticBuilder<'_>, sp: Option<rustc_span::Span>| {
1465 "this link resolved to {} {}, which is not {} {}",
1468 specified.article(),
1471 if let Some(sp) = sp {
1472 diag.span_label(sp, ¬e);
1476 suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1478 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1481 fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1483 super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1484 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1485 rustc_session::parse::feature_err(
1486 &self.cx.tcx.sess.parse_sess,
1487 sym::intra_doc_pointers,
1489 "linking to associated items of raw pointers is experimental",
1491 .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1495 fn resolve_with_disambiguator_cached(
1497 key: ResolutionInfo,
1498 diag: DiagnosticInfo<'_>,
1499 cache_resolution_failure: bool,
1500 ) -> Option<(Res, Option<UrlFragment>)> {
1501 if let Some(ref cached) = self.visited_links.get(&key) {
1504 return Some(cached.res.clone());
1506 None if cache_resolution_failure => return None,
1508 // Although we hit the cache and found a resolution error, this link isn't
1509 // supposed to cache those. Run link resolution again to emit the expected
1510 // resolution error.
1515 let res = self.resolve_with_disambiguator(&key, diag);
1517 // Cache only if resolved successfully - don't silence duplicate errors
1518 if let Some(res) = res {
1519 // Store result for the actual namespace
1520 self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1524 if cache_resolution_failure {
1525 // For reference-style links we only want to report one resolution error
1526 // so let's cache them as well.
1527 self.visited_links.insert(key, None);
1534 /// After parsing the disambiguator, resolve the main part of the link.
1535 // FIXME(jynelson): wow this is just so much
1536 fn resolve_with_disambiguator(
1538 key: &ResolutionInfo,
1539 diag: DiagnosticInfo<'_>,
1540 ) -> Option<(Res, Option<UrlFragment>)> {
1541 let disambiguator = key.dis;
1542 let path_str = &key.path_str;
1543 let base_node = key.module_id;
1544 let extra_fragment = &key.extra_fragment;
1546 match disambiguator.map(Disambiguator::ns) {
1547 Some(expected_ns @ (ValueNS | TypeNS)) => {
1548 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1549 Ok(res) => Some(res),
1550 Err(ErrorKind::Resolve(box mut kind)) => {
1551 // We only looked in one namespace. Try to give a better error if possible.
1552 if kind.full_res().is_none() {
1553 let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1554 // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1555 // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1556 for new_ns in [other_ns, MacroNS] {
1558 self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1560 kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1565 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1566 // This could just be a normal link or a broken link
1567 // we could potentially check if something is
1568 // "intra-doc-link-like" and warn in that case.
1571 Err(ErrorKind::AnchorFailure(msg)) => {
1572 anchor_failure(self.cx, diag, msg);
1579 let mut candidates = PerNS {
1581 .resolve_macro(path_str, base_node)
1582 .map(|res| (res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1583 type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1585 debug!("got res in TypeNS: {:?}", res);
1588 Err(ErrorKind::AnchorFailure(msg)) => {
1589 anchor_failure(self.cx, diag, msg);
1592 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1594 value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1596 Err(ErrorKind::AnchorFailure(msg)) => {
1597 anchor_failure(self.cx, diag, msg);
1600 Err(ErrorKind::Resolve(box kind)) => Err(kind),
1602 .and_then(|(res, fragment)| {
1603 // Constructors are picked up in the type namespace.
1605 Res::Def(DefKind::Ctor(..), _) => {
1606 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1609 match (fragment, extra_fragment.clone()) {
1610 (Some(fragment), Some(_)) => {
1611 // Shouldn't happen but who knows?
1612 Ok((res, Some(fragment)))
1614 (fragment, None) => Ok((res, fragment)),
1615 (None, fragment) => {
1616 Ok((res, fragment.map(UrlFragment::UserWritten)))
1624 let len = candidates.iter().filter(|res| res.is_ok()).count();
1632 candidates.into_iter().filter_map(|res| res.err()).collect(),
1634 // this could just be a normal link
1639 Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1640 } else if len == 2 && is_derive_trait_collision(&candidates) {
1641 Some(candidates.type_ns.unwrap())
1643 if is_derive_trait_collision(&candidates) {
1644 candidates.macro_ns = Err(ResolutionFailure::Dummy);
1646 // If we're reporting an ambiguity, don't mention the namespaces that failed
1647 let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1648 ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1653 match self.resolve_macro(path_str, base_node) {
1654 Ok(res) => Some((res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1656 // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1657 for ns in [TypeNS, ValueNS] {
1659 self.check_full_res(ns, path_str, base_node, extra_fragment)
1662 ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1666 resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1675 /// Get the section of a link between the backticks,
1676 /// or the whole link if there aren't any backticks.
1684 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1685 let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1686 let before_second_backtick_group = ori_link
1689 .skip(after_first_backtick_group)
1690 .position(|b| b == b'`')
1691 .unwrap_or(ori_link.link.len());
1692 (ori_link.range.start + after_first_backtick_group)
1693 ..(ori_link.range.start + before_second_backtick_group)
1696 /// Returns true if we should ignore `link` due to it being unlikely
1697 /// that it is an intra-doc link. `link` should still have disambiguators
1698 /// if there were any.
1700 /// The difference between this and [`should_ignore_link()`] is that this
1701 /// check should only be used on links that still have disambiguators.
1702 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1703 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1706 /// Returns true if we should ignore `path_str` due to it being unlikely
1707 /// that it is an intra-doc link.
1708 fn should_ignore_link(path_str: &str) -> bool {
1709 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1712 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1713 /// Disambiguators for a link.
1714 enum Disambiguator {
1717 /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1719 /// `struct@` or `f()`
1722 Namespace(Namespace),
1725 impl Disambiguator {
1726 /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1728 /// This returns `Ok(Some(...))` if a disambiguator was found,
1729 /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1730 /// if there was a problem with the disambiguator.
1731 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1732 use Disambiguator::{Kind, Namespace as NS, Primitive};
1734 if let Some(idx) = link.find('@') {
1735 let (prefix, rest) = link.split_at(idx);
1736 let d = match prefix {
1737 "struct" => Kind(DefKind::Struct),
1738 "enum" => Kind(DefKind::Enum),
1739 "trait" => Kind(DefKind::Trait),
1740 "union" => Kind(DefKind::Union),
1741 "module" | "mod" => Kind(DefKind::Mod),
1742 "const" | "constant" => Kind(DefKind::Const),
1743 "static" => Kind(DefKind::Static),
1744 "function" | "fn" | "method" => Kind(DefKind::Fn),
1745 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1746 "type" => NS(Namespace::TypeNS),
1747 "value" => NS(Namespace::ValueNS),
1748 "macro" => NS(Namespace::MacroNS),
1749 "prim" | "primitive" => Primitive,
1750 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1752 Ok(Some((d, &rest[1..], &rest[1..])))
1755 ("!()", DefKind::Macro(MacroKind::Bang)),
1756 ("!{}", DefKind::Macro(MacroKind::Bang)),
1757 ("![]", DefKind::Macro(MacroKind::Bang)),
1758 ("()", DefKind::Fn),
1759 ("!", DefKind::Macro(MacroKind::Bang)),
1761 for (suffix, kind) in suffixes {
1762 if let Some(path_str) = link.strip_suffix(suffix) {
1763 // Avoid turning `!` or `()` into an empty string
1764 if !path_str.is_empty() {
1765 return Ok(Some((Kind(kind), path_str, link)));
1773 fn ns(self) -> Namespace {
1775 Self::Namespace(n) => n,
1777 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1779 Self::Primitive => TypeNS,
1783 fn article(self) -> &'static str {
1785 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1786 Self::Kind(k) => k.article(),
1787 Self::Primitive => "a",
1791 fn descr(self) -> &'static str {
1793 Self::Namespace(n) => n.descr(),
1794 // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1795 // printing "module" vs "crate" so using the wrong ID is not a huge problem
1796 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1797 Self::Primitive => "builtin type",
1802 /// A suggestion to show in a diagnostic.
1805 Prefix(&'static str),
1810 /// `foo` without any disambiguator
1811 RemoveDisambiguator,
1815 fn descr(&self) -> Cow<'static, str> {
1817 Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1818 Self::Function => "add parentheses".into(),
1819 Self::Macro => "add an exclamation mark".into(),
1820 Self::RemoveDisambiguator => "remove the disambiguator".into(),
1824 fn as_help(&self, path_str: &str) -> String {
1825 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1827 Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1828 Self::Function => format!("{}()", path_str),
1829 Self::Macro => format!("{}!", path_str),
1830 Self::RemoveDisambiguator => path_str.into(),
1838 sp: rustc_span::Span,
1839 ) -> Vec<(rustc_span::Span, String)> {
1840 let inner_sp = match ori_link.find('(') {
1841 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1844 let inner_sp = match ori_link.find('!') {
1845 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1848 let inner_sp = match ori_link.find('@') {
1849 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1853 Self::Prefix(prefix) => {
1854 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1855 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1856 if sp.hi() != inner_sp.hi() {
1857 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1862 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1863 if sp.lo() != inner_sp.lo() {
1864 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1869 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1870 if sp.lo() != inner_sp.lo() {
1871 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1875 Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1880 /// Reports a diagnostic for an intra-doc link.
1882 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1883 /// the entire documentation block is used for the lint. If a range is provided but the span
1884 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1886 /// The `decorate` callback is invoked in all cases to allow further customization of the
1887 /// diagnostic before emission. If the span of the link was able to be determined, the second
1888 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1890 fn report_diagnostic(
1892 lint: &'static Lint,
1894 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1895 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1897 let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1898 Some(hir_id) => hir_id,
1900 // If non-local, no need to check anything.
1901 info!("ignoring warning from parent crate: {}", msg);
1906 let sp = item.attr_span(tcx);
1908 tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1909 let mut diag = lint.build(msg);
1912 super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1913 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1914 && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1916 sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1922 if let Some(sp) = span {
1925 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1928 // last_new_line_offset
1929 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1930 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1932 // Print the line containing the `link_range` and manually mark it with '^'s.
1934 "the link appears in this line:\n\n{line}\n\
1935 {indicator: <before$}{indicator:^<found$}",
1938 before = link_range.start - last_new_line_offset,
1939 found = link_range.len(),
1943 decorate(&mut diag, span);
1949 /// Reports a link that failed to resolve.
1951 /// This also tries to resolve any intermediate path segments that weren't
1952 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1953 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1954 fn resolution_failure(
1955 collector: &mut LinkCollector<'_, '_>,
1956 diag_info: DiagnosticInfo<'_>,
1958 disambiguator: Option<Disambiguator>,
1959 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1961 let tcx = collector.cx.tcx;
1964 BROKEN_INTRA_DOC_LINKS,
1965 &format!("unresolved link to `{}`", path_str),
1968 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1969 let assoc_item_not_allowed = |res: Res| {
1970 let name = res.name(tcx);
1972 "`{}` is {} {}, not a module or type, and cannot have associated items",
1978 // ignore duplicates
1979 let mut variants_seen = SmallVec::<[_; 3]>::new();
1980 for mut failure in kinds {
1981 let variant = std::mem::discriminant(&failure);
1982 if variants_seen.contains(&variant) {
1985 variants_seen.push(variant);
1987 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1992 let module_id = *module_id;
1993 // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1994 // FIXME: maybe use itertools `collect_tuple` instead?
1995 fn split(path: &str) -> Option<(&str, &str)> {
1996 let mut splitter = path.rsplitn(2, "::");
1997 splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
2000 // Check if _any_ parent of the path gets resolved.
2001 // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
2002 let mut name = path_str;
2004 let (start, end) = if let Some(x) = split(name) {
2007 // avoid bug that marked [Quux::Z] as missing Z, not Quux
2008 if partial_res.is_none() {
2009 *unresolved = name.into();
2014 for ns in [TypeNS, ValueNS, MacroNS] {
2015 if let Some(res) = collector.check_full_res(ns, start, module_id, &None)
2017 debug!("found partial_res={:?}", res);
2018 *partial_res = Some(res);
2019 *unresolved = end.into();
2023 *unresolved = end.into();
2026 let last_found_module = match *partial_res {
2027 Some(Res::Def(DefKind::Mod, id)) => Some(id),
2028 None => Some(module_id),
2031 // See if this was a module: `[path]` or `[std::io::nope]`
2032 if let Some(module) = last_found_module {
2033 let note = if partial_res.is_some() {
2034 // Part of the link resolved; e.g. `std::io::nonexistent`
2035 let module_name = tcx.item_name(module);
2036 format!("no item named `{}` in module `{}`", unresolved, module_name)
2038 // None of the link resolved; e.g. `Notimported`
2039 format!("no item named `{}` in scope", unresolved)
2041 if let Some(span) = sp {
2042 diag.span_label(span, ¬e);
2047 // If the link has `::` in it, assume it was meant to be an intra-doc link.
2048 // Otherwise, the `[]` might be unrelated.
2049 // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
2050 if !path_str.contains("::") {
2051 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
2057 // Otherwise, it must be an associated item or variant
2058 let res = partial_res.expect("None case was handled by `last_found_module`");
2059 let name = res.name(tcx);
2060 let kind = match res {
2061 Res::Def(kind, _) => Some(kind),
2062 Res::Primitive(_) => None,
2064 let path_description = if let Some(kind) = kind {
2066 Mod | ForeignMod => "inner item",
2067 Struct => "field or associated item",
2068 Enum | Union => "variant or associated item",
2086 let note = assoc_item_not_allowed(res);
2087 if let Some(span) = sp {
2088 diag.span_label(span, ¬e);
2094 Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
2095 | Static => "associated item",
2096 Impl | GlobalAsm => unreachable!("not a path"),
2102 "the {} `{}` has no {} named `{}`",
2105 disambiguator.map_or(path_description, |d| d.descr()),
2108 if let Some(span) = sp {
2109 diag.span_label(span, ¬e);
2116 let note = match failure {
2117 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2118 ResolutionFailure::Dummy => continue,
2119 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2120 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2123 "this link resolves to {}, which is not in the {} namespace",
2128 ResolutionFailure::NoParentItem => {
2129 diag.level = rustc_errors::Level::Bug;
2130 "all intra-doc links should have a parent item".to_owned()
2132 ResolutionFailure::MalformedGenerics(variant) => match variant {
2133 MalformedGenerics::UnbalancedAngleBrackets => {
2134 String::from("unbalanced angle brackets")
2136 MalformedGenerics::MissingType => {
2137 String::from("missing type for generic parameters")
2139 MalformedGenerics::HasFullyQualifiedSyntax => {
2140 diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2141 String::from("fully-qualified syntax is unsupported")
2143 MalformedGenerics::InvalidPathSeparator => {
2144 String::from("has invalid path separator")
2146 MalformedGenerics::TooManyAngleBrackets => {
2147 String::from("too many angle brackets")
2149 MalformedGenerics::EmptyAngleBrackets => {
2150 String::from("empty angle brackets")
2154 if let Some(span) = sp {
2155 diag.span_label(span, ¬e);
2164 /// Report an anchor failure.
2165 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2166 let (msg, anchor_idx) = match failure {
2167 AnchorFailure::MultipleAnchors => {
2168 (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2170 AnchorFailure::RustdocAnchorConflict(res) => (
2172 "`{}` contains an anchor, but links to {kind}s are already anchored",
2180 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2181 if let Some(mut sp) = sp {
2182 if let Some((fragment_offset, _)) =
2183 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2185 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2187 diag.span_label(sp, "invalid anchor");
2189 if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2190 if let Some(sp) = sp {
2191 span_bug!(sp, "anchors should be allowed now");
2193 bug!("anchors should be allowed now");
2199 /// Report an error in the link disambiguator.
2200 fn disambiguator_error(
2201 cx: &DocContext<'_>,
2202 mut diag_info: DiagnosticInfo<'_>,
2203 disambiguator_range: Range<usize>,
2206 diag_info.link_range = disambiguator_range;
2207 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2209 "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2210 crate::DOC_RUST_LANG_ORG_CHANNEL
2216 /// Report an ambiguity error, where there were multiple possible resolutions.
2218 cx: &DocContext<'_>,
2219 diag_info: DiagnosticInfo<'_>,
2221 candidates: Vec<Res>,
2223 let mut msg = format!("`{}` is ", path_str);
2225 match candidates.as_slice() {
2226 [first_def, second_def] => {
2228 "both {} {} and {} {}",
2229 first_def.article(),
2231 second_def.article(),
2236 let mut candidates = candidates.iter().peekable();
2237 while let Some(res) = candidates.next() {
2238 if candidates.peek().is_some() {
2239 msg += &format!("{} {}, ", res.article(), res.descr());
2241 msg += &format!("and {} {}", res.article(), res.descr());
2247 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2248 if let Some(sp) = sp {
2249 diag.span_label(sp, "ambiguous link");
2251 diag.note("ambiguous link");
2254 for res in candidates {
2255 suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2260 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2262 fn suggest_disambiguator(
2264 diag: &mut DiagnosticBuilder<'_>,
2267 sp: Option<rustc_span::Span>,
2269 let suggestion = res.disambiguator_suggestion();
2270 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2272 if let Some(sp) = sp {
2273 let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2274 if spans.len() > 1 {
2275 diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2277 let (sp, suggestion_text) = spans.pop().unwrap();
2278 diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2281 diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2285 /// Report a link from a public item to a private one.
2286 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2288 let item_name = match diag_info.item.name {
2293 None => "<unknown>",
2296 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2298 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2299 if let Some(sp) = sp {
2300 diag.span_label(sp, "this item is private");
2303 let note_msg = if cx.render_options.document_private {
2304 "this link resolves only because you passed `--document-private-items`, but will break without"
2306 "this link will resolve properly if you pass `--document-private-items`"
2308 diag.note(note_msg);
2312 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2314 cx: &DocContext<'_>,
2316 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'static>> {
2318 .parent(res.def_id(cx.tcx))
2320 let parent_def = Res::Def(DefKind::Enum, parent);
2321 let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2322 (parent_def, Some(ItemFragment(FragmentKind::Variant, variant.def_id)))
2324 .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2327 /// Resolve a primitive type or value.
2328 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2332 use PrimitiveType::*;
2333 let prim = match path_str {
2349 "bool" | "true" | "false" => Bool,
2350 "str" | "&str" => Str,
2351 // See #80181 for why these don't have symbols associated.
2356 "pointer" | "*const" | "*mut" => RawPointer,
2357 "reference" | "&" | "&mut" => Reference,
2359 "never" | "!" => Never,
2362 debug!("resolved primitives {:?}", prim);
2363 Some(Res::Primitive(prim))
2366 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2367 let mut stripped_segments = vec![];
2368 let mut path = path_str.chars().peekable();
2369 let mut segment = Vec::new();
2371 while let Some(chr) = path.next() {
2374 if path.next_if_eq(&':').is_some() {
2375 let stripped_segment =
2376 strip_generics_from_path_segment(mem::take(&mut segment))?;
2377 if !stripped_segment.is_empty() {
2378 stripped_segments.push(stripped_segment);
2381 return Err(ResolutionFailure::MalformedGenerics(
2382 MalformedGenerics::InvalidPathSeparator,
2391 return Err(ResolutionFailure::MalformedGenerics(
2392 MalformedGenerics::TooManyAngleBrackets,
2396 return Err(ResolutionFailure::MalformedGenerics(
2397 MalformedGenerics::EmptyAngleBrackets,
2403 while let Some(chr) = path.next_if(|c| *c != '>') {
2410 _ => segment.push(chr),
2412 trace!("raw segment: {:?}", segment);
2415 if !segment.is_empty() {
2416 let stripped_segment = strip_generics_from_path_segment(segment)?;
2417 if !stripped_segment.is_empty() {
2418 stripped_segments.push(stripped_segment);
2422 debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2424 let stripped_path = stripped_segments.join("::");
2426 if !stripped_path.is_empty() {
2429 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2433 fn strip_generics_from_path_segment(
2435 ) -> Result<String, ResolutionFailure<'static>> {
2436 let mut stripped_segment = String::new();
2437 let mut param_depth = 0;
2439 let mut latest_generics_chunk = String::new();
2444 latest_generics_chunk.clear();
2445 } else if c == '>' {
2447 if latest_generics_chunk.contains(" as ") {
2448 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2449 // Give a helpful error message instead of completely ignoring the angle brackets.
2450 return Err(ResolutionFailure::MalformedGenerics(
2451 MalformedGenerics::HasFullyQualifiedSyntax,
2455 if param_depth == 0 {
2456 stripped_segment.push(c);
2458 latest_generics_chunk.push(c);
2463 if param_depth == 0 {
2464 Ok(stripped_segment)
2466 // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2467 Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))