]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_intra_doc_links.rs
Auto merge of #95107 - r00ster91:fmt, r=joshtriplett
[rust.git] / src / librustdoc / passes / collect_intra_doc_links.rs
1 //! This module implements [RFC 1946]: Intra-rustdoc-links
2 //!
3 //! [RFC 1946]: https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md
4
5 use rustc_data_structures::{fx::FxHashMap, intern::Interned, stable_set::FxHashSet};
6 use rustc_errors::{Applicability, Diagnostic};
7 use rustc_hir::def::{
8     DefKind,
9     Namespace::{self, *},
10     PerNS,
11 };
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};
20
21 use pulldown_cmark::LinkType;
22
23 use std::borrow::Cow;
24 use std::convert::{TryFrom, TryInto};
25 use std::fmt::Write;
26 use std::mem;
27 use std::ops::Range;
28
29 use crate::clean::{self, utils::find_nearest_parent_module};
30 use crate::clean::{Crate, Item, ItemId, ItemLink, PrimitiveType};
31 use crate::core::DocContext;
32 use crate::html::markdown::{markdown_links, MarkdownLink};
33 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
34 use crate::passes::Pass;
35 use crate::visit::DocVisitor;
36
37 mod early;
38 crate use early::early_resolve_intra_doc_links;
39
40 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
41     name: "collect-intra-doc-links",
42     run: collect_intra_doc_links,
43     description: "resolves intra-doc links",
44 };
45
46 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
47     let mut collector =
48         LinkCollector { cx, mod_ids: Vec::new(), visited_links: FxHashMap::default() };
49     collector.visit_crate(&krate);
50     krate
51 }
52
53 /// Top-level errors emitted by this pass.
54 enum ErrorKind<'a> {
55     Resolve(Box<ResolutionFailure<'a>>),
56     AnchorFailure(AnchorFailure),
57 }
58
59 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
60     fn from(err: ResolutionFailure<'a>) -> Self {
61         ErrorKind::Resolve(box err)
62     }
63 }
64
65 #[derive(Copy, Clone, Debug, Hash)]
66 enum Res {
67     Def(DefKind, DefId),
68     Primitive(PrimitiveType),
69 }
70
71 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
72
73 impl Res {
74     fn descr(self) -> &'static str {
75         match self {
76             Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
77             Res::Primitive(_) => "builtin type",
78         }
79     }
80
81     fn article(self) -> &'static str {
82         match self {
83             Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
84             Res::Primitive(_) => "a",
85         }
86     }
87
88     fn name(self, tcx: TyCtxt<'_>) -> Symbol {
89         match self {
90             Res::Def(_, id) => tcx.item_name(id),
91             Res::Primitive(prim) => prim.as_sym(),
92         }
93     }
94
95     fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
96         match self {
97             Res::Def(_, id) => id,
98             Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
99         }
100     }
101
102     fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
103         match self {
104             Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
105             // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
106             Res::Primitive(_) => None,
107         }
108     }
109
110     /// Used for error reporting.
111     fn disambiguator_suggestion(self) -> Suggestion {
112         let kind = match self {
113             Res::Primitive(_) => return Suggestion::Prefix("prim"),
114             Res::Def(kind, _) => kind,
115         };
116         if kind == DefKind::Macro(MacroKind::Bang) {
117             return Suggestion::Macro;
118         } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
119             return Suggestion::Function;
120         } else if kind == DefKind::Field {
121             return Suggestion::RemoveDisambiguator;
122         }
123
124         let prefix = match kind {
125             DefKind::Struct => "struct",
126             DefKind::Enum => "enum",
127             DefKind::Trait => "trait",
128             DefKind::Union => "union",
129             DefKind::Mod => "mod",
130             DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
131                 "const"
132             }
133             DefKind::Static => "static",
134             DefKind::Macro(MacroKind::Derive) => "derive",
135             // Now handle things that don't have a specific disambiguator
136             _ => match kind
137                 .ns()
138                 .expect("tried to calculate a disambiguator for a def without a namespace?")
139             {
140                 Namespace::TypeNS => "type",
141                 Namespace::ValueNS => "value",
142                 Namespace::MacroNS => "macro",
143             },
144         };
145
146         Suggestion::Prefix(prefix)
147     }
148 }
149
150 impl TryFrom<ResolveRes> for Res {
151     type Error = ();
152
153     fn try_from(res: ResolveRes) -> Result<Self, ()> {
154         use rustc_hir::def::Res::*;
155         match res {
156             Def(kind, id) => Ok(Res::Def(kind, id)),
157             PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
158             // e.g. `#[derive]`
159             NonMacroAttr(..) | Err => Result::Err(()),
160             other => bug!("unrecognized res {:?}", other),
161         }
162     }
163 }
164
165 /// A link failed to resolve.
166 #[derive(Debug)]
167 enum ResolutionFailure<'a> {
168     /// This resolved, but with the wrong namespace.
169     WrongNamespace {
170         /// What the link resolved to.
171         res: Res,
172         /// The expected namespace for the resolution, determined from the link's disambiguator.
173         ///
174         /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
175         /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
176         expected_ns: Namespace,
177     },
178     /// The link failed to resolve. [`resolution_failure`] should look to see if there's
179     /// a more helpful error that can be given.
180     NotResolved {
181         /// Item on which the link is resolved, used for resolving `Self`.
182         item_id: ItemId,
183         /// The scope the link was resolved in.
184         module_id: DefId,
185         /// If part of the link resolved, this has the `Res`.
186         ///
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.
190         ///
191         /// In `[std::io::Error::x]`, `x` would be unresolved.
192         unresolved: Cow<'a, str>,
193     },
194     /// This happens when rustdoc can't determine the parent scope for an item.
195     /// It is always a bug in rustdoc.
196     NoParentItem,
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.
200     ///
201     /// This happens when there is no disambiguator and one of the namespaces
202     /// failed to resolve.
203     Dummy,
204 }
205
206 #[derive(Debug)]
207 enum MalformedGenerics {
208     /// This link has unbalanced angle brackets.
209     ///
210     /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
211     UnbalancedAngleBrackets,
212     /// The generics are not attached to a type.
213     ///
214     /// For example, `<T>` should trigger this.
215     ///
216     /// This is detected by checking if the path is empty after the generics are stripped.
217     MissingType,
218     /// The link uses fully-qualified syntax, which is currently unsupported.
219     ///
220     /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
221     ///
222     /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
223     /// angle brackets.
224     HasFullyQualifiedSyntax,
225     /// The link has an invalid path separator.
226     ///
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
229     /// called.
230     ///
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)).
234     ///
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.
238     ///
239     /// For example, `Vec<<T>>` should trigger this.
240     TooManyAngleBrackets,
241     /// The link has empty angle brackets.
242     ///
243     /// For example, `Vec<>` should trigger this.
244     EmptyAngleBrackets,
245 }
246
247 impl ResolutionFailure<'_> {
248     /// This resolved fully (not just partially) but is erroneous for some other reason
249     ///
250     /// Returns the full resolution of the link, if present.
251     fn full_res(&self) -> Option<Res> {
252         match self {
253             Self::WrongNamespace { res, expected_ns: _ } => Some(*res),
254             _ => None,
255         }
256     }
257 }
258
259 enum AnchorFailure {
260     /// User error: `[std#x#y]` is not valid
261     MultipleAnchors,
262     /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
263     ///
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.
269     ///
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),
273 }
274
275 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
276 crate enum UrlFragment {
277     Item(ItemFragment),
278     UserWritten(String),
279 }
280
281 impl UrlFragment {
282     /// Render the fragment, including the leading `#`.
283     crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
284         match self {
285             UrlFragment::Item(frag) => frag.render(s, tcx),
286             UrlFragment::UserWritten(raw) => write!(s, "#{}", raw),
287         }
288     }
289 }
290
291 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
292 crate struct ItemFragment(FragmentKind, DefId);
293
294 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
295 crate enum FragmentKind {
296     Method,
297     TyMethod,
298     AssociatedConstant,
299     AssociatedType,
300
301     StructField,
302     Variant,
303     VariantField,
304 }
305
306 impl ItemFragment {
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;
311         match item.kind {
312             ty::AssocKind::Fn => {
313                 if item.defaultness.has_value() {
314                     ItemFragment(FragmentKind::Method, def_id)
315                 } else {
316                     ItemFragment(FragmentKind::TyMethod, def_id)
317                 }
318             }
319             ty::AssocKind::Const => ItemFragment(FragmentKind::AssociatedConstant, def_id),
320             ty::AssocKind::Type => ItemFragment(FragmentKind::AssociatedType, def_id),
321         }
322     }
323
324     /// Render the fragment, including the leading `#`.
325     crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
326         write!(s, "#")?;
327         match *self {
328             ItemFragment(kind, def_id) => {
329                 let name = tcx.item_name(def_id);
330                 match kind {
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)
340                     }
341                 }
342             }
343         }
344     }
345 }
346
347 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
348 struct ResolutionInfo {
349     item_id: ItemId,
350     module_id: DefId,
351     dis: Option<Disambiguator>,
352     path_str: String,
353     extra_fragment: Option<String>,
354 }
355
356 #[derive(Clone)]
357 struct DiagnosticInfo<'a> {
358     item: &'a Item,
359     dox: &'a str,
360     ori_link: &'a str,
361     link_range: Range<usize>,
362 }
363
364 #[derive(Clone, Debug, Hash)]
365 struct CachedLink {
366     res: (Res, Option<UrlFragment>),
367 }
368
369 struct LinkCollector<'a, 'tcx> {
370     cx: &'a mut DocContext<'tcx>,
371     /// A stack of modules used to decide what scope to resolve in.
372     ///
373     /// The last module will be used if the parent scope of the current item is
374     /// unknown.
375     mod_ids: Vec<DefId>,
376     /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
377     /// The link will be `None` if it could not be resolved (i.e. the error was cached).
378     visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
379 }
380
381 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
382     /// Given a full link, parse it as an [enum struct variant].
383     ///
384     /// In particular, this will return an error whenever there aren't three
385     /// full path segments left in the link.
386     ///
387     /// [enum struct variant]: rustc_hir::VariantData::Struct
388     fn variant_field<'path>(
389         &self,
390         path_str: &'path str,
391         item_id: ItemId,
392         module_id: DefId,
393     ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
394         let tcx = self.cx.tcx;
395         let no_res = || ResolutionFailure::NotResolved {
396             item_id,
397             module_id,
398             partial_res: None,
399             unresolved: path_str.into(),
400         };
401
402         debug!("looking for enum variant {}", path_str);
403         let mut split = path_str.rsplitn(3, "::");
404         let variant_field_name = split
405             .next()
406             .map(|f| Symbol::intern(f))
407             .expect("fold_item should ensure link is non-empty");
408         let variant_name =
409             // we're not sure this is a variant at all, so use the full string
410             // If there's no second component, the link looks like `[path]`.
411             // So there's no partial res and we should say the whole link failed to resolve.
412             split.next().map(|f|  Symbol::intern(f)).ok_or_else(no_res)?;
413         let path = split
414             .next()
415             .map(|f| f.to_owned())
416             // If there's no third component, we saw `[a::b]` before and it failed to resolve.
417             // So there's no partial res.
418             .ok_or_else(no_res)?;
419         let ty_res = self.resolve_path(&path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
420
421         match ty_res {
422             Res::Def(DefKind::Enum, did) => {
423                 if tcx
424                     .inherent_impls(did)
425                     .iter()
426                     .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
427                     .any(|item| item.name == variant_name)
428                 {
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());
432                 }
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)
436                         {
437                             Ok((ty_res, Some(ItemFragment(FragmentKind::VariantField, field.did))))
438                         } else {
439                             Err(ResolutionFailure::NotResolved {
440                                 item_id,
441                                 module_id,
442                                 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
443                                 unresolved: variant_field_name.to_string().into(),
444                             }
445                             .into())
446                         }
447                     }
448                     _ => unreachable!(),
449                 }
450             }
451             _ => Err(ResolutionFailure::NotResolved {
452                 item_id,
453                 module_id,
454                 partial_res: Some(ty_res),
455                 unresolved: variant_name.to_string().into(),
456             }
457             .into()),
458         }
459     }
460
461     /// Given a primitive type, try to resolve an associated item.
462     fn resolve_primitive_associated_item(
463         &self,
464         prim_ty: PrimitiveType,
465         ns: Namespace,
466         item_name: Symbol,
467     ) -> Option<(Res, ItemFragment)> {
468         let tcx = self.cx.tcx;
469
470         prim_ty.impls(tcx).into_iter().find_map(|&impl_| {
471             tcx.associated_items(impl_)
472                 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
473                 .map(|item| {
474                     let fragment = ItemFragment::from_assoc_item(item);
475                     (Res::Primitive(prim_ty), fragment)
476                 })
477         })
478     }
479
480     /// Resolves a string as a macro.
481     ///
482     /// FIXME(jynelson): Can this be unified with `resolve()`?
483     fn resolve_macro(
484         &self,
485         path_str: &'a str,
486         item_id: ItemId,
487         module_id: DefId,
488     ) -> Result<Res, ResolutionFailure<'a>> {
489         self.cx.enter_resolver(|resolver| {
490             // NOTE: this needs 2 separate lookups because `resolve_str_path_error` doesn't take
491             // lexical scope into account (it ignores all macros not defined at the mod-level)
492             debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
493             if let Ok((_, res)) =
494                 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
495             {
496                 // don't resolve builtins like `#[derive]`
497                 if let Ok(res) = res.try_into() {
498                     return Ok(res);
499                 }
500             }
501             if let Some(&res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
502                 return Ok(res.try_into().unwrap());
503             }
504             Err(ResolutionFailure::NotResolved {
505                 item_id,
506                 module_id,
507                 partial_res: None,
508                 unresolved: path_str.into(),
509             })
510         })
511     }
512
513     fn resolve_self_ty(&self, path_str: &str, ns: Namespace, item_id: ItemId) -> Option<Res> {
514         if ns != TypeNS || path_str != "Self" {
515             return None;
516         }
517
518         let tcx = self.cx.tcx;
519         item_id
520             .as_def_id()
521             .map(|def_id| match tcx.def_kind(def_id) {
522                 def_kind @ (DefKind::AssocFn
523                 | DefKind::AssocConst
524                 | DefKind::AssocTy
525                 | DefKind::Variant
526                 | DefKind::Field) => {
527                     let parent_def_id = tcx.parent(def_id).expect("nested item has no parent");
528                     if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant
529                     {
530                         tcx.parent(parent_def_id).expect("variant has no parent")
531                     } else {
532                         parent_def_id
533                     }
534                 }
535                 _ => def_id,
536             })
537             .and_then(|self_id| match tcx.def_kind(self_id) {
538                 DefKind::Impl => self.def_id_to_res(self_id),
539                 def_kind => Some(Res::Def(def_kind, self_id)),
540             })
541     }
542
543     /// Convenience wrapper around `resolve_str_path_error`.
544     ///
545     /// This also handles resolving `true` and `false` as booleans.
546     /// NOTE: `resolve_str_path_error` knows only about paths, not about types.
547     /// Associated items will never be resolved by this function.
548     fn resolve_path(
549         &self,
550         path_str: &str,
551         ns: Namespace,
552         item_id: ItemId,
553         module_id: DefId,
554     ) -> Option<Res> {
555         if let res @ Some(..) = self.resolve_self_ty(path_str, ns, item_id) {
556             return res;
557         }
558
559         let result = self.cx.enter_resolver(|resolver| {
560             resolver
561                 .resolve_str_path_error(DUMMY_SP, path_str, ns, module_id)
562                 .and_then(|(_, res)| res.try_into())
563         });
564         debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
565         match result {
566             // resolver doesn't know about true, false, and types that aren't paths (e.g. `()`)
567             // manually as bool
568             Err(()) => resolve_primitive(path_str, ns),
569             Ok(res) => Some(res),
570         }
571     }
572
573     /// Resolves a string as a path within a particular namespace. Returns an
574     /// optional URL fragment in the case of variants and methods.
575     fn resolve<'path>(
576         &mut self,
577         path_str: &'path str,
578         ns: Namespace,
579         item_id: ItemId,
580         module_id: DefId,
581         user_fragment: &Option<String>,
582     ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'path>> {
583         let (res, rustdoc_fragment) = self.resolve_inner(path_str, ns, item_id, module_id)?;
584         let chosen_fragment = match (user_fragment, rustdoc_fragment) {
585             (Some(_), Some(r_frag)) => {
586                 let diag_res = match r_frag {
587                     ItemFragment(_, did) => Res::Def(self.cx.tcx.def_kind(did), did),
588                 };
589                 let failure = AnchorFailure::RustdocAnchorConflict(diag_res);
590                 return Err(ErrorKind::AnchorFailure(failure));
591             }
592             (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
593             (None, Some(r_frag)) => Some(UrlFragment::Item(r_frag)),
594             (None, None) => None,
595         };
596         Ok((res, chosen_fragment))
597     }
598
599     fn resolve_inner<'path>(
600         &mut self,
601         path_str: &'path str,
602         ns: Namespace,
603         item_id: ItemId,
604         module_id: DefId,
605     ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
606         if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
607             match res {
608                 // FIXME(#76467): make this fallthrough to lookup the associated
609                 // item a separate function.
610                 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
611                 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
612                 Res::Def(DefKind::Variant, _) => {
613                     return handle_variant(self.cx, res);
614                 }
615                 // Not a trait item; just return what we found.
616                 _ => return Ok((res, None)),
617             }
618         }
619
620         // Try looking for methods and associated items.
621         let mut split = path_str.rsplitn(2, "::");
622         // NB: `split`'s first element is always defined, even if the delimiter was not present.
623         // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
624         let item_str = split.next().unwrap();
625         let item_name = Symbol::intern(item_str);
626         let path_root = split
627             .next()
628             .map(|f| f.to_owned())
629             // If there's no `::`, it's not an associated item.
630             // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
631             .ok_or_else(|| {
632                 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
633                 ResolutionFailure::NotResolved {
634                     item_id,
635                     module_id,
636                     partial_res: None,
637                     unresolved: item_str.into(),
638                 }
639             })?;
640
641         // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
642         // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
643         // error instead and special case *only* modules with `#[doc(primitive)]`, not all
644         // primitives.
645         resolve_primitive(&path_root, TypeNS)
646             .or_else(|| self.resolve_path(&path_root, TypeNS, item_id, module_id))
647             .and_then(|ty_res| {
648                 let (res, fragment) =
649                     self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
650
651                 Some(Ok((res, Some(fragment))))
652             })
653             .unwrap_or_else(|| {
654                 if ns == Namespace::ValueNS {
655                     self.variant_field(path_str, item_id, module_id)
656                 } else {
657                     Err(ResolutionFailure::NotResolved {
658                         item_id,
659                         module_id,
660                         partial_res: None,
661                         unresolved: path_root.into(),
662                     }
663                     .into())
664                 }
665             })
666     }
667
668     /// Convert a DefId to a Res, where possible.
669     ///
670     /// This is used for resolving type aliases.
671     fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
672         use PrimitiveType::*;
673         Some(match *self.cx.tcx.type_of(ty_id).kind() {
674             ty::Bool => Res::Primitive(Bool),
675             ty::Char => Res::Primitive(Char),
676             ty::Int(ity) => Res::Primitive(ity.into()),
677             ty::Uint(uty) => Res::Primitive(uty.into()),
678             ty::Float(fty) => Res::Primitive(fty.into()),
679             ty::Str => Res::Primitive(Str),
680             ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
681             ty::Tuple(_) => Res::Primitive(Tuple),
682             ty::Array(..) => Res::Primitive(Array),
683             ty::Slice(_) => Res::Primitive(Slice),
684             ty::RawPtr(_) => Res::Primitive(RawPointer),
685             ty::Ref(..) => Res::Primitive(Reference),
686             ty::FnDef(..) => panic!("type alias to a function definition"),
687             ty::FnPtr(_) => Res::Primitive(Fn),
688             ty::Never => Res::Primitive(Never),
689             ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
690                 Res::Def(self.cx.tcx.def_kind(did), did)
691             }
692             ty::Projection(_)
693             | ty::Closure(..)
694             | ty::Generator(..)
695             | ty::GeneratorWitness(_)
696             | ty::Opaque(..)
697             | ty::Dynamic(..)
698             | ty::Param(_)
699             | ty::Bound(..)
700             | ty::Placeholder(_)
701             | ty::Infer(_)
702             | ty::Error(_) => return None,
703         })
704     }
705
706     /// Convert a PrimitiveType to a Ty, where possible.
707     ///
708     /// This is used for resolving trait impls for primitives
709     fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
710         use PrimitiveType::*;
711         let tcx = self.cx.tcx;
712
713         // FIXME: Only simple types are supported here, see if we can support
714         // other types such as Tuple, Array, Slice, etc.
715         // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
716         Some(tcx.mk_ty(match prim {
717             Bool => ty::Bool,
718             Str => ty::Str,
719             Char => ty::Char,
720             Never => ty::Never,
721             I8 => ty::Int(ty::IntTy::I8),
722             I16 => ty::Int(ty::IntTy::I16),
723             I32 => ty::Int(ty::IntTy::I32),
724             I64 => ty::Int(ty::IntTy::I64),
725             I128 => ty::Int(ty::IntTy::I128),
726             Isize => ty::Int(ty::IntTy::Isize),
727             F32 => ty::Float(ty::FloatTy::F32),
728             F64 => ty::Float(ty::FloatTy::F64),
729             U8 => ty::Uint(ty::UintTy::U8),
730             U16 => ty::Uint(ty::UintTy::U16),
731             U32 => ty::Uint(ty::UintTy::U32),
732             U64 => ty::Uint(ty::UintTy::U64),
733             U128 => ty::Uint(ty::UintTy::U128),
734             Usize => ty::Uint(ty::UintTy::Usize),
735             _ => return None,
736         }))
737     }
738
739     /// Resolve an associated item, returning its containing page's `Res`
740     /// and the fragment targeting the associated item on its page.
741     fn resolve_associated_item(
742         &mut self,
743         root_res: Res,
744         item_name: Symbol,
745         ns: Namespace,
746         module_id: DefId,
747     ) -> Option<(Res, ItemFragment)> {
748         let tcx = self.cx.tcx;
749
750         match root_res {
751             Res::Primitive(prim) => {
752                 self.resolve_primitive_associated_item(prim, ns, item_name).or_else(|| {
753                     let assoc_item = self
754                         .primitive_type_to_ty(prim)
755                         .map(|ty| {
756                             resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
757                         })
758                         .flatten();
759
760                     assoc_item.map(|item| {
761                         let fragment = ItemFragment::from_assoc_item(&item);
762                         (root_res, fragment)
763                     })
764                 })
765             }
766             Res::Def(DefKind::TyAlias, did) => {
767                 // Resolve the link on the type the alias points to.
768                 // FIXME: if the associated item is defined directly on the type alias,
769                 // it will show up on its documentation page, we should link there instead.
770                 let res = self.def_id_to_res(did)?;
771                 self.resolve_associated_item(res, item_name, ns, module_id)
772             }
773             Res::Def(
774                 def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
775                 did,
776             ) => {
777                 debug!("looking for associated item named {} for item {:?}", item_name, did);
778                 // Checks if item_name is a variant of the `SomeItem` enum
779                 if ns == TypeNS && def_kind == DefKind::Enum {
780                     match tcx.type_of(did).kind() {
781                         ty::Adt(adt_def, _) => {
782                             for variant in adt_def.variants() {
783                                 if variant.name == item_name {
784                                     return Some((
785                                         root_res,
786                                         ItemFragment(FragmentKind::Variant, variant.def_id),
787                                     ));
788                                 }
789                             }
790                         }
791                         _ => unreachable!(),
792                     }
793                 }
794
795                 // Checks if item_name belongs to `impl SomeItem`
796                 let assoc_item = tcx
797                     .inherent_impls(did)
798                     .iter()
799                     .flat_map(|&imp| {
800                         tcx.associated_items(imp).find_by_name_and_namespace(
801                             tcx,
802                             Ident::with_dummy_span(item_name),
803                             ns,
804                             imp,
805                         )
806                     })
807                     .copied()
808                     // There should only ever be one associated item that matches from any inherent impl
809                     .next()
810                     // Check if item_name belongs to `impl SomeTrait for SomeItem`
811                     // FIXME(#74563): This gives precedence to `impl SomeItem`:
812                     // Although having both would be ambiguous, use impl version for compatibility's sake.
813                     // To handle that properly resolve() would have to support
814                     // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
815                     .or_else(|| {
816                         resolve_associated_trait_item(
817                             tcx.type_of(did),
818                             module_id,
819                             item_name,
820                             ns,
821                             self.cx,
822                         )
823                     });
824
825                 debug!("got associated item {:?}", assoc_item);
826
827                 if let Some(item) = assoc_item {
828                     let fragment = ItemFragment::from_assoc_item(&item);
829                     return Some((root_res, fragment));
830                 }
831
832                 if ns != Namespace::ValueNS {
833                     return None;
834                 }
835                 debug!("looking for fields named {} for {:?}", item_name, did);
836                 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
837                 // NOTE: it's different from variant_field because it only resolves struct fields,
838                 // not variant fields (2 path segments, not 3).
839                 //
840                 // We need to handle struct (and union) fields in this code because
841                 // syntactically their paths are identical to associated item paths:
842                 // `module::Type::field` and `module::Type::Assoc`.
843                 //
844                 // On the other hand, variant fields can't be mistaken for associated
845                 // items because they look like this: `module::Type::Variant::field`.
846                 //
847                 // Variants themselves don't need to be handled here, even though
848                 // they also look like associated items (`module::Type::Variant`),
849                 // because they are real Rust syntax (unlike the intra-doc links
850                 // field syntax) and are handled by the compiler's resolver.
851                 let def = match tcx.type_of(did).kind() {
852                     ty::Adt(def, _) if !def.is_enum() => def,
853                     _ => return None,
854                 };
855                 let field =
856                     def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?;
857                 Some((root_res, ItemFragment(FragmentKind::StructField, field.did)))
858             }
859             Res::Def(DefKind::Trait, did) => tcx
860                 .associated_items(did)
861                 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
862                 .map(|item| {
863                     let fragment = ItemFragment::from_assoc_item(item);
864                     let res = Res::Def(item.kind.as_def_kind(), item.def_id);
865                     (res, fragment)
866                 }),
867             _ => None,
868         }
869     }
870
871     /// Used for reporting better errors.
872     ///
873     /// Returns whether the link resolved 'fully' in another namespace.
874     /// 'fully' here means that all parts of the link resolved, not just some path segments.
875     /// This returns the `Res` even if it was erroneous for some reason
876     /// (such as having invalid URL fragments or being in the wrong namespace).
877     fn check_full_res(
878         &mut self,
879         ns: Namespace,
880         path_str: &str,
881         item_id: ItemId,
882         module_id: DefId,
883         extra_fragment: &Option<String>,
884     ) -> Option<Res> {
885         // resolve() can't be used for macro namespace
886         let result = match ns {
887             Namespace::MacroNS => self
888                 .resolve_macro(path_str, item_id, module_id)
889                 .map(|res| (res, None))
890                 .map_err(ErrorKind::from),
891             Namespace::TypeNS | Namespace::ValueNS => {
892                 self.resolve(path_str, ns, item_id, module_id, extra_fragment)
893             }
894         };
895
896         let res = match result {
897             Ok((res, frag)) => {
898                 if let Some(UrlFragment::Item(ItemFragment(_, id))) = frag {
899                     Some(Res::Def(self.cx.tcx.def_kind(id), id))
900                 } else {
901                     Some(res)
902                 }
903             }
904             Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
905             Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
906             Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
907         };
908         res
909     }
910 }
911
912 /// Look to see if a resolved item has an associated item named `item_name`.
913 ///
914 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
915 /// find `std::error::Error::source` and return
916 /// `<io::Error as error::Error>::source`.
917 fn resolve_associated_trait_item<'a>(
918     ty: Ty<'a>,
919     module: DefId,
920     item_name: Symbol,
921     ns: Namespace,
922     cx: &mut DocContext<'a>,
923 ) -> Option<ty::AssocItem> {
924     // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
925     // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
926     // meantime, just don't look for these blanket impls.
927
928     // Next consider explicit impls: `impl MyTrait for MyType`
929     // Give precedence to inherent impls.
930     let traits = trait_impls_for(cx, ty, module);
931     debug!("considering traits {:?}", traits);
932     let mut candidates = traits.iter().filter_map(|&(impl_, trait_)| {
933         cx.tcx
934             .associated_items(trait_)
935             .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
936             .map(|trait_assoc| {
937                 trait_assoc_to_impl_assoc_item(cx.tcx, impl_, trait_assoc.def_id)
938                     .unwrap_or(trait_assoc)
939             })
940     });
941     // FIXME(#74563): warn about ambiguity
942     debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
943     candidates.next().copied()
944 }
945
946 /// Find the associated item in the impl `impl_id` that corresponds to the
947 /// trait associated item `trait_assoc_id`.
948 ///
949 /// This function returns `None` if no associated item was found in the impl.
950 /// This can occur when the trait associated item has a default value that is
951 /// not overridden in the impl.
952 ///
953 /// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
954 /// [`TyCtxt::associated_item()`] (with some helpful logging added).
955 #[instrument(level = "debug", skip(tcx))]
956 fn trait_assoc_to_impl_assoc_item<'tcx>(
957     tcx: TyCtxt<'tcx>,
958     impl_id: DefId,
959     trait_assoc_id: DefId,
960 ) -> Option<&'tcx ty::AssocItem> {
961     let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
962     debug!(?trait_to_impl_assoc_map);
963     let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
964     debug!(?impl_assoc_id);
965     let impl_assoc = tcx.associated_item(impl_assoc_id);
966     debug!(?impl_assoc);
967     Some(impl_assoc)
968 }
969
970 /// Given a type, return all trait impls in scope in `module` for that type.
971 /// Returns a set of pairs of `(impl_id, trait_id)`.
972 ///
973 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
974 /// So it is not stable to serialize cross-crate.
975 #[instrument(level = "debug", skip(cx))]
976 fn trait_impls_for<'a>(
977     cx: &mut DocContext<'a>,
978     ty: Ty<'a>,
979     module: DefId,
980 ) -> FxHashSet<(DefId, DefId)> {
981     let tcx = cx.tcx;
982     let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
983         let trait_ = trait_candidate.def_id;
984         trace!("considering explicit impl for trait {:?}", trait_);
985
986         // Look at each trait implementation to see if it's an impl for `did`
987         tcx.find_map_relevant_impl(trait_, ty, |impl_| {
988             let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
989             // Check if these are the same type.
990             let impl_type = trait_ref.self_ty();
991             trace!(
992                 "comparing type {} with kind {:?} against type {:?}",
993                 impl_type,
994                 impl_type.kind(),
995                 ty
996             );
997             // Fast path: if this is a primitive simple `==` will work
998             // NOTE: the `match` is necessary; see #92662.
999             // this allows us to ignore generics because the user input
1000             // may not include the generic placeholders
1001             // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
1002             let saw_impl = impl_type == ty
1003                 || match (impl_type.kind(), ty.kind()) {
1004                     (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
1005                         debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
1006                         impl_def.did() == ty_def.did()
1007                     }
1008                     _ => false,
1009                 };
1010
1011             if saw_impl { Some((impl_, trait_)) } else { None }
1012         })
1013     });
1014     iter.collect()
1015 }
1016
1017 /// Check for resolve collisions between a trait and its derive.
1018 ///
1019 /// These are common and we should just resolve to the trait in that case.
1020 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
1021     matches!(
1022         *ns,
1023         PerNS {
1024             type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
1025             macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
1026             ..
1027         }
1028     )
1029 }
1030
1031 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
1032     fn visit_item(&mut self, item: &Item) {
1033         let parent_node =
1034             item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
1035         if parent_node.is_some() {
1036             trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
1037         }
1038
1039         let inner_docs = item.inner_docs(self.cx.tcx);
1040
1041         if item.is_mod() && inner_docs {
1042             self.mod_ids.push(item.def_id.expect_def_id());
1043         }
1044
1045         // We want to resolve in the lexical scope of the documentation.
1046         // In the presence of re-exports, this is not the same as the module of the item.
1047         // Rather than merging all documentation into one, resolve it one attribute at a time
1048         // so we know which module it came from.
1049         for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
1050             debug!("combined_docs={}", doc);
1051
1052             let (krate, parent_node) = if let Some(id) = parent_module {
1053                 (id.krate, Some(id))
1054             } else {
1055                 (item.def_id.krate(), parent_node)
1056             };
1057             // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1058             // This is a degenerate case and it's not supported by rustdoc.
1059             for md_link in markdown_links(&doc) {
1060                 let link = self.resolve_link(&item, &doc, parent_node, krate, md_link);
1061                 if let Some(link) = link {
1062                     self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
1063                 }
1064             }
1065         }
1066
1067         if item.is_mod() {
1068             if !inner_docs {
1069                 self.mod_ids.push(item.def_id.expect_def_id());
1070             }
1071
1072             self.visit_item_recur(item);
1073             self.mod_ids.pop();
1074         } else {
1075             self.visit_item_recur(item)
1076         }
1077     }
1078 }
1079
1080 enum PreprocessingError<'a> {
1081     Anchor(AnchorFailure),
1082     Disambiguator(Range<usize>, String),
1083     Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
1084 }
1085
1086 impl From<AnchorFailure> for PreprocessingError<'_> {
1087     fn from(err: AnchorFailure) -> Self {
1088         Self::Anchor(err)
1089     }
1090 }
1091
1092 struct PreprocessingInfo {
1093     path_str: String,
1094     disambiguator: Option<Disambiguator>,
1095     extra_fragment: Option<String>,
1096     link_text: String,
1097 }
1098
1099 /// Returns:
1100 /// - `None` if the link should be ignored.
1101 /// - `Some(Err)` if the link should emit an error
1102 /// - `Some(Ok)` if the link is valid
1103 ///
1104 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
1105 fn preprocess_link<'a>(
1106     ori_link: &'a MarkdownLink,
1107 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
1108     // [] is mostly likely not supposed to be a link
1109     if ori_link.link.is_empty() {
1110         return None;
1111     }
1112
1113     // Bail early for real links.
1114     if ori_link.link.contains('/') {
1115         return None;
1116     }
1117
1118     let stripped = ori_link.link.replace('`', "");
1119     let mut parts = stripped.split('#');
1120
1121     let link = parts.next().unwrap();
1122     if link.trim().is_empty() {
1123         // This is an anchor to an element of the current page, nothing to do in here!
1124         return None;
1125     }
1126     let extra_fragment = parts.next();
1127     if parts.next().is_some() {
1128         // A valid link can't have multiple #'s
1129         return Some(Err(AnchorFailure::MultipleAnchors.into()));
1130     }
1131
1132     // Parse and strip the disambiguator from the link, if present.
1133     let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1134         Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1135         Ok(None) => (None, link.trim(), link.trim()),
1136         Err((err_msg, relative_range)) => {
1137             // Only report error if we would not have ignored this link. See issue #83859.
1138             if !should_ignore_link_with_disambiguators(link) {
1139                 let no_backticks_range = range_between_backticks(ori_link);
1140                 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1141                     ..(no_backticks_range.start + relative_range.end);
1142                 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1143             } else {
1144                 return None;
1145             }
1146         }
1147     };
1148
1149     if should_ignore_link(path_str) {
1150         return None;
1151     }
1152
1153     // Strip generics from the path.
1154     let path_str = if path_str.contains(['<', '>'].as_slice()) {
1155         match strip_generics_from_path(path_str) {
1156             Ok(path) => path,
1157             Err(err_kind) => {
1158                 debug!("link has malformed generics: {}", path_str);
1159                 return Some(Err(PreprocessingError::Resolution(
1160                     err_kind,
1161                     path_str.to_owned(),
1162                     disambiguator,
1163                 )));
1164             }
1165         }
1166     } else {
1167         path_str.to_owned()
1168     };
1169
1170     // Sanity check to make sure we don't have any angle brackets after stripping generics.
1171     assert!(!path_str.contains(['<', '>'].as_slice()));
1172
1173     // The link is not an intra-doc link if it still contains spaces after stripping generics.
1174     if path_str.contains(' ') {
1175         return None;
1176     }
1177
1178     Some(Ok(PreprocessingInfo {
1179         path_str,
1180         disambiguator,
1181         extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1182         link_text: link_text.to_owned(),
1183     }))
1184 }
1185
1186 impl LinkCollector<'_, '_> {
1187     /// This is the entry point for resolving an intra-doc link.
1188     ///
1189     /// FIXME(jynelson): this is way too many arguments
1190     fn resolve_link(
1191         &mut self,
1192         item: &Item,
1193         dox: &str,
1194         parent_node: Option<DefId>,
1195         krate: CrateNum,
1196         ori_link: MarkdownLink,
1197     ) -> Option<ItemLink> {
1198         trace!("considering link '{}'", ori_link.link);
1199
1200         let diag_info = DiagnosticInfo {
1201             item,
1202             dox,
1203             ori_link: &ori_link.link,
1204             link_range: ori_link.range.clone(),
1205         };
1206
1207         let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1208             match preprocess_link(&ori_link)? {
1209                 Ok(x) => x,
1210                 Err(err) => {
1211                     match err {
1212                         PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1213                         PreprocessingError::Disambiguator(range, msg) => {
1214                             disambiguator_error(self.cx, diag_info, range, &msg)
1215                         }
1216                         PreprocessingError::Resolution(err, path_str, disambiguator) => {
1217                             resolution_failure(
1218                                 self,
1219                                 diag_info,
1220                                 &path_str,
1221                                 disambiguator,
1222                                 smallvec![err],
1223                             );
1224                         }
1225                     }
1226                     return None;
1227                 }
1228             };
1229         let mut path_str = &*path_str;
1230
1231         let inner_docs = item.inner_docs(self.cx.tcx);
1232
1233         // In order to correctly resolve intra-doc links we need to
1234         // pick a base AST node to work from.  If the documentation for
1235         // this module came from an inner comment (//!) then we anchor
1236         // our name resolution *inside* the module.  If, on the other
1237         // hand it was an outer comment (///) then we anchor the name
1238         // resolution in the parent module on the basis that the names
1239         // used are more likely to be intended to be parent names.  For
1240         // this, we set base_node to None for inner comments since
1241         // we've already pushed this node onto the resolution stack but
1242         // for outer comments we explicitly try and resolve against the
1243         // parent_node first.
1244         let base_node =
1245             if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1246
1247         let Some(mut module_id) = base_node else {
1248             // This is a bug.
1249             debug!("attempting to resolve item without parent module: {}", path_str);
1250             resolution_failure(
1251                 self,
1252                 diag_info,
1253                 path_str,
1254                 disambiguator,
1255                 smallvec![ResolutionFailure::NoParentItem],
1256             );
1257             return None;
1258         };
1259
1260         let resolved_self;
1261         let is_lone_crate = path_str == "crate";
1262         if path_str.starts_with("crate::") || is_lone_crate {
1263             use rustc_span::def_id::CRATE_DEF_INDEX;
1264
1265             // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1266             // But rustdoc wants it to mean the crate this item was originally present in.
1267             // To work around this, remove it and resolve relative to the crate root instead.
1268             // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1269             // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1270             // FIXME(#78696): This doesn't always work.
1271             if is_lone_crate {
1272                 path_str = "self";
1273             } else {
1274                 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1275                 path_str = &resolved_self;
1276             }
1277             module_id = DefId { krate, index: CRATE_DEF_INDEX };
1278         }
1279
1280         let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1281             ResolutionInfo {
1282                 item_id: item.def_id,
1283                 module_id,
1284                 dis: disambiguator,
1285                 path_str: path_str.to_owned(),
1286                 extra_fragment,
1287             },
1288             diag_info.clone(), // this struct should really be Copy, but Range is not :(
1289             matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1290         )?;
1291
1292         // Check for a primitive which might conflict with a module
1293         // Report the ambiguity and require that the user specify which one they meant.
1294         // FIXME: could there ever be a primitive not in the type namespace?
1295         if matches!(
1296             disambiguator,
1297             None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1298         ) && !matches!(res, Res::Primitive(_))
1299         {
1300             if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1301                 // `prim@char`
1302                 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1303                     res = prim;
1304                 } else {
1305                     // `[char]` when a `char` module is in scope
1306                     let candidates = vec![res, prim];
1307                     ambiguity_error(self.cx, diag_info, path_str, candidates);
1308                     return None;
1309                 }
1310             }
1311         }
1312
1313         match res {
1314             Res::Primitive(prim) => {
1315                 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1316                     // We're actually resolving an associated item of a primitive, so we need to
1317                     // verify the disambiguator (if any) matches the type of the associated item.
1318                     // This case should really follow the same flow as the `Res::Def` branch below,
1319                     // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1320                     // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1321                     // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1322                     // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1323                     // for discussion on the matter.
1324                     let kind = self.cx.tcx.def_kind(id);
1325                     self.verify_disambiguator(
1326                         path_str,
1327                         &ori_link,
1328                         kind,
1329                         id,
1330                         disambiguator,
1331                         item,
1332                         &diag_info,
1333                     )?;
1334
1335                     // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1336                     // However I'm not sure how to check that across crates.
1337                     if prim == PrimitiveType::RawPointer
1338                         && item.def_id.is_local()
1339                         && !self.cx.tcx.features().intra_doc_pointers
1340                     {
1341                         self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1342                     }
1343                 } else {
1344                     match disambiguator {
1345                         Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1346                         Some(other) => {
1347                             self.report_disambiguator_mismatch(
1348                                 path_str, &ori_link, other, res, &diag_info,
1349                             );
1350                             return None;
1351                         }
1352                     }
1353                 }
1354
1355                 Some(ItemLink {
1356                     link: ori_link.link,
1357                     link_text,
1358                     did: res.def_id(self.cx.tcx),
1359                     fragment,
1360                 })
1361             }
1362             Res::Def(kind, id) => {
1363                 let (kind_for_dis, id_for_dis) =
1364                     if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1365                         (self.cx.tcx.def_kind(id), id)
1366                     } else {
1367                         (kind, id)
1368                     };
1369                 self.verify_disambiguator(
1370                     path_str,
1371                     &ori_link,
1372                     kind_for_dis,
1373                     id_for_dis,
1374                     disambiguator,
1375                     item,
1376                     &diag_info,
1377                 )?;
1378                 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1379                 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1380             }
1381         }
1382     }
1383
1384     fn verify_disambiguator(
1385         &self,
1386         path_str: &str,
1387         ori_link: &MarkdownLink,
1388         kind: DefKind,
1389         id: DefId,
1390         disambiguator: Option<Disambiguator>,
1391         item: &Item,
1392         diag_info: &DiagnosticInfo<'_>,
1393     ) -> Option<()> {
1394         debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1395
1396         // Disallow e.g. linking to enums with `struct@`
1397         debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1398         match (kind, disambiguator) {
1399                 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1400                 // NOTE: this allows 'method' to mean both normal functions and associated functions
1401                 // This can't cause ambiguity because both are in the same namespace.
1402                 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1403                 // These are namespaces; allow anything in the namespace to match
1404                 | (_, Some(Disambiguator::Namespace(_)))
1405                 // If no disambiguator given, allow anything
1406                 | (_, None)
1407                 // All of these are valid, so do nothing
1408                 => {}
1409                 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1410                 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1411                     self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1412                     return None;
1413                 }
1414             }
1415
1416         // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1417         if let Some((src_id, dst_id)) = id
1418             .as_local()
1419             // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1420             // would presumably panic if a fake `DefIndex` were passed.
1421             .and_then(|dst_id| {
1422                 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1423             })
1424         {
1425             if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1426                 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1427             {
1428                 privacy_error(self.cx, diag_info, path_str);
1429             }
1430         }
1431
1432         Some(())
1433     }
1434
1435     fn report_disambiguator_mismatch(
1436         &self,
1437         path_str: &str,
1438         ori_link: &MarkdownLink,
1439         specified: Disambiguator,
1440         resolved: Res,
1441         diag_info: &DiagnosticInfo<'_>,
1442     ) {
1443         // The resolved item did not match the disambiguator; give a better error than 'not found'
1444         let msg = format!("incompatible link kind for `{}`", path_str);
1445         let callback = |diag: &mut Diagnostic, sp: Option<rustc_span::Span>| {
1446             let note = format!(
1447                 "this link resolved to {} {}, which is not {} {}",
1448                 resolved.article(),
1449                 resolved.descr(),
1450                 specified.article(),
1451                 specified.descr(),
1452             );
1453             if let Some(sp) = sp {
1454                 diag.span_label(sp, &note);
1455             } else {
1456                 diag.note(&note);
1457             }
1458             suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1459         };
1460         report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1461     }
1462
1463     fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1464         let span =
1465             super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1466                 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1467         rustc_session::parse::feature_err(
1468             &self.cx.tcx.sess.parse_sess,
1469             sym::intra_doc_pointers,
1470             span,
1471             "linking to associated items of raw pointers is experimental",
1472         )
1473         .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1474         .emit();
1475     }
1476
1477     fn resolve_with_disambiguator_cached(
1478         &mut self,
1479         key: ResolutionInfo,
1480         diag: DiagnosticInfo<'_>,
1481         cache_resolution_failure: bool,
1482     ) -> Option<(Res, Option<UrlFragment>)> {
1483         if let Some(ref cached) = self.visited_links.get(&key) {
1484             match cached {
1485                 Some(cached) => {
1486                     return Some(cached.res.clone());
1487                 }
1488                 None if cache_resolution_failure => return None,
1489                 None => {
1490                     // Although we hit the cache and found a resolution error, this link isn't
1491                     // supposed to cache those. Run link resolution again to emit the expected
1492                     // resolution error.
1493                 }
1494             }
1495         }
1496
1497         let res = self.resolve_with_disambiguator(&key, diag);
1498
1499         // Cache only if resolved successfully - don't silence duplicate errors
1500         if let Some(res) = res {
1501             // Store result for the actual namespace
1502             self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1503
1504             Some(res)
1505         } else {
1506             if cache_resolution_failure {
1507                 // For reference-style links we only want to report one resolution error
1508                 // so let's cache them as well.
1509                 self.visited_links.insert(key, None);
1510             }
1511
1512             None
1513         }
1514     }
1515
1516     /// After parsing the disambiguator, resolve the main part of the link.
1517     // FIXME(jynelson): wow this is just so much
1518     fn resolve_with_disambiguator(
1519         &mut self,
1520         key: &ResolutionInfo,
1521         diag: DiagnosticInfo<'_>,
1522     ) -> Option<(Res, Option<UrlFragment>)> {
1523         let disambiguator = key.dis;
1524         let path_str = &key.path_str;
1525         let item_id = key.item_id;
1526         let base_node = key.module_id;
1527         let extra_fragment = &key.extra_fragment;
1528
1529         match disambiguator.map(Disambiguator::ns) {
1530             Some(expected_ns @ (ValueNS | TypeNS)) => {
1531                 match self.resolve(path_str, expected_ns, item_id, base_node, extra_fragment) {
1532                     Ok(res) => Some(res),
1533                     Err(ErrorKind::Resolve(box mut kind)) => {
1534                         // We only looked in one namespace. Try to give a better error if possible.
1535                         if kind.full_res().is_none() {
1536                             let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1537                             // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1538                             // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1539                             for new_ns in [other_ns, MacroNS] {
1540                                 if let Some(res) = self.check_full_res(
1541                                     new_ns,
1542                                     path_str,
1543                                     item_id,
1544                                     base_node,
1545                                     extra_fragment,
1546                                 ) {
1547                                     kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1548                                     break;
1549                                 }
1550                             }
1551                         }
1552                         resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1553                         // This could just be a normal link or a broken link
1554                         // we could potentially check if something is
1555                         // "intra-doc-link-like" and warn in that case.
1556                         None
1557                     }
1558                     Err(ErrorKind::AnchorFailure(msg)) => {
1559                         anchor_failure(self.cx, diag, msg);
1560                         None
1561                     }
1562                 }
1563             }
1564             None => {
1565                 // Try everything!
1566                 let mut candidates = PerNS {
1567                     macro_ns: self
1568                         .resolve_macro(path_str, item_id, base_node)
1569                         .map(|res| (res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1570                     type_ns: match self.resolve(
1571                         path_str,
1572                         TypeNS,
1573                         item_id,
1574                         base_node,
1575                         extra_fragment,
1576                     ) {
1577                         Ok(res) => {
1578                             debug!("got res in TypeNS: {:?}", res);
1579                             Ok(res)
1580                         }
1581                         Err(ErrorKind::AnchorFailure(msg)) => {
1582                             anchor_failure(self.cx, diag, msg);
1583                             return None;
1584                         }
1585                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1586                     },
1587                     value_ns: match self.resolve(
1588                         path_str,
1589                         ValueNS,
1590                         item_id,
1591                         base_node,
1592                         extra_fragment,
1593                     ) {
1594                         Ok(res) => Ok(res),
1595                         Err(ErrorKind::AnchorFailure(msg)) => {
1596                             anchor_failure(self.cx, diag, msg);
1597                             return None;
1598                         }
1599                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1600                     }
1601                     .and_then(|(res, fragment)| {
1602                         // Constructors are picked up in the type namespace.
1603                         match res {
1604                             Res::Def(DefKind::Ctor(..), _) => {
1605                                 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1606                             }
1607                             _ => {
1608                                 match (fragment, extra_fragment.clone()) {
1609                                     (Some(fragment), Some(_)) => {
1610                                         // Shouldn't happen but who knows?
1611                                         Ok((res, Some(fragment)))
1612                                     }
1613                                     (fragment, None) => Ok((res, fragment)),
1614                                     (None, fragment) => {
1615                                         Ok((res, fragment.map(UrlFragment::UserWritten)))
1616                                     }
1617                                 }
1618                             }
1619                         }
1620                     }),
1621                 };
1622
1623                 let len = candidates.iter().filter(|res| res.is_ok()).count();
1624
1625                 if len == 0 {
1626                     resolution_failure(
1627                         self,
1628                         diag,
1629                         path_str,
1630                         disambiguator,
1631                         candidates.into_iter().filter_map(|res| res.err()).collect(),
1632                     );
1633                     // this could just be a normal link
1634                     return None;
1635                 }
1636
1637                 if len == 1 {
1638                     Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1639                 } else if len == 2 && is_derive_trait_collision(&candidates) {
1640                     Some(candidates.type_ns.unwrap())
1641                 } else {
1642                     if is_derive_trait_collision(&candidates) {
1643                         candidates.macro_ns = Err(ResolutionFailure::Dummy);
1644                     }
1645                     // If we're reporting an ambiguity, don't mention the namespaces that failed
1646                     let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1647                     ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1648                     None
1649                 }
1650             }
1651             Some(MacroNS) => {
1652                 match self.resolve_macro(path_str, item_id, base_node) {
1653                     Ok(res) => Some((res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1654                     Err(mut kind) => {
1655                         // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1656                         for ns in [TypeNS, ValueNS] {
1657                             if let Some(res) = self.check_full_res(
1658                                 ns,
1659                                 path_str,
1660                                 item_id,
1661                                 base_node,
1662                                 extra_fragment,
1663                             ) {
1664                                 kind =
1665                                     ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1666                                 break;
1667                             }
1668                         }
1669                         resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1670                         None
1671                     }
1672                 }
1673             }
1674         }
1675     }
1676 }
1677
1678 /// Get the section of a link between the backticks,
1679 /// or the whole link if there aren't any backticks.
1680 ///
1681 /// For example:
1682 ///
1683 /// ```text
1684 /// [`Foo`]
1685 ///   ^^^
1686 /// ```
1687 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1688     let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1689     let before_second_backtick_group = ori_link
1690         .link
1691         .bytes()
1692         .skip(after_first_backtick_group)
1693         .position(|b| b == b'`')
1694         .unwrap_or(ori_link.link.len());
1695     (ori_link.range.start + after_first_backtick_group)
1696         ..(ori_link.range.start + before_second_backtick_group)
1697 }
1698
1699 /// Returns true if we should ignore `link` due to it being unlikely
1700 /// that it is an intra-doc link. `link` should still have disambiguators
1701 /// if there were any.
1702 ///
1703 /// The difference between this and [`should_ignore_link()`] is that this
1704 /// check should only be used on links that still have disambiguators.
1705 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1706     link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1707 }
1708
1709 /// Returns true if we should ignore `path_str` due to it being unlikely
1710 /// that it is an intra-doc link.
1711 fn should_ignore_link(path_str: &str) -> bool {
1712     path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1713 }
1714
1715 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1716 /// Disambiguators for a link.
1717 enum Disambiguator {
1718     /// `prim@`
1719     ///
1720     /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1721     Primitive,
1722     /// `struct@` or `f()`
1723     Kind(DefKind),
1724     /// `type@`
1725     Namespace(Namespace),
1726 }
1727
1728 impl Disambiguator {
1729     /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1730     ///
1731     /// This returns `Ok(Some(...))` if a disambiguator was found,
1732     /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1733     /// if there was a problem with the disambiguator.
1734     fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1735         use Disambiguator::{Kind, Namespace as NS, Primitive};
1736
1737         if let Some(idx) = link.find('@') {
1738             let (prefix, rest) = link.split_at(idx);
1739             let d = match prefix {
1740                 "struct" => Kind(DefKind::Struct),
1741                 "enum" => Kind(DefKind::Enum),
1742                 "trait" => Kind(DefKind::Trait),
1743                 "union" => Kind(DefKind::Union),
1744                 "module" | "mod" => Kind(DefKind::Mod),
1745                 "const" | "constant" => Kind(DefKind::Const),
1746                 "static" => Kind(DefKind::Static),
1747                 "function" | "fn" | "method" => Kind(DefKind::Fn),
1748                 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1749                 "type" => NS(Namespace::TypeNS),
1750                 "value" => NS(Namespace::ValueNS),
1751                 "macro" => NS(Namespace::MacroNS),
1752                 "prim" | "primitive" => Primitive,
1753                 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1754             };
1755             Ok(Some((d, &rest[1..], &rest[1..])))
1756         } else {
1757             let suffixes = [
1758                 ("!()", DefKind::Macro(MacroKind::Bang)),
1759                 ("!{}", DefKind::Macro(MacroKind::Bang)),
1760                 ("![]", DefKind::Macro(MacroKind::Bang)),
1761                 ("()", DefKind::Fn),
1762                 ("!", DefKind::Macro(MacroKind::Bang)),
1763             ];
1764             for (suffix, kind) in suffixes {
1765                 if let Some(path_str) = link.strip_suffix(suffix) {
1766                     // Avoid turning `!` or `()` into an empty string
1767                     if !path_str.is_empty() {
1768                         return Ok(Some((Kind(kind), path_str, link)));
1769                     }
1770                 }
1771             }
1772             Ok(None)
1773         }
1774     }
1775
1776     fn ns(self) -> Namespace {
1777         match self {
1778             Self::Namespace(n) => n,
1779             Self::Kind(k) => {
1780                 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1781             }
1782             Self::Primitive => TypeNS,
1783         }
1784     }
1785
1786     fn article(self) -> &'static str {
1787         match self {
1788             Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1789             Self::Kind(k) => k.article(),
1790             Self::Primitive => "a",
1791         }
1792     }
1793
1794     fn descr(self) -> &'static str {
1795         match self {
1796             Self::Namespace(n) => n.descr(),
1797             // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1798             // printing "module" vs "crate" so using the wrong ID is not a huge problem
1799             Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1800             Self::Primitive => "builtin type",
1801         }
1802     }
1803 }
1804
1805 /// A suggestion to show in a diagnostic.
1806 enum Suggestion {
1807     /// `struct@`
1808     Prefix(&'static str),
1809     /// `f()`
1810     Function,
1811     /// `m!`
1812     Macro,
1813     /// `foo` without any disambiguator
1814     RemoveDisambiguator,
1815 }
1816
1817 impl Suggestion {
1818     fn descr(&self) -> Cow<'static, str> {
1819         match self {
1820             Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1821             Self::Function => "add parentheses".into(),
1822             Self::Macro => "add an exclamation mark".into(),
1823             Self::RemoveDisambiguator => "remove the disambiguator".into(),
1824         }
1825     }
1826
1827     fn as_help(&self, path_str: &str) -> String {
1828         // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1829         match self {
1830             Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1831             Self::Function => format!("{}()", path_str),
1832             Self::Macro => format!("{}!", path_str),
1833             Self::RemoveDisambiguator => path_str.into(),
1834         }
1835     }
1836
1837     fn as_help_span(
1838         &self,
1839         path_str: &str,
1840         ori_link: &str,
1841         sp: rustc_span::Span,
1842     ) -> Vec<(rustc_span::Span, String)> {
1843         let inner_sp = match ori_link.find('(') {
1844             Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1845             None => sp,
1846         };
1847         let inner_sp = match ori_link.find('!') {
1848             Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1849             None => inner_sp,
1850         };
1851         let inner_sp = match ori_link.find('@') {
1852             Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1853             None => inner_sp,
1854         };
1855         match self {
1856             Self::Prefix(prefix) => {
1857                 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1858                 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1859                 if sp.hi() != inner_sp.hi() {
1860                     sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1861                 }
1862                 sugg
1863             }
1864             Self::Function => {
1865                 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1866                 if sp.lo() != inner_sp.lo() {
1867                     sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1868                 }
1869                 sugg
1870             }
1871             Self::Macro => {
1872                 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1873                 if sp.lo() != inner_sp.lo() {
1874                     sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1875                 }
1876                 sugg
1877             }
1878             Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1879         }
1880     }
1881 }
1882
1883 /// Reports a diagnostic for an intra-doc link.
1884 ///
1885 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1886 /// the entire documentation block is used for the lint. If a range is provided but the span
1887 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1888 ///
1889 /// The `decorate` callback is invoked in all cases to allow further customization of the
1890 /// diagnostic before emission. If the span of the link was able to be determined, the second
1891 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1892 /// to it.
1893 fn report_diagnostic(
1894     tcx: TyCtxt<'_>,
1895     lint: &'static Lint,
1896     msg: &str,
1897     DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1898     decorate: impl FnOnce(&mut Diagnostic, Option<rustc_span::Span>),
1899 ) {
1900     let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.def_id)
1901     else {
1902         // If non-local, no need to check anything.
1903         info!("ignoring warning from parent crate: {}", msg);
1904         return;
1905     };
1906
1907     let sp = item.attr_span(tcx);
1908
1909     tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1910         let mut diag = lint.build(msg);
1911
1912         let span =
1913             super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1914                 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1915                     && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1916                 {
1917                     sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1918                 } else {
1919                     sp
1920                 }
1921             });
1922
1923         if let Some(sp) = span {
1924             diag.set_span(sp);
1925         } else {
1926             // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1927             //                       ^     ~~~~
1928             //                       |     link_range
1929             //                       last_new_line_offset
1930             let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1931             let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1932
1933             // Print the line containing the `link_range` and manually mark it with '^'s.
1934             diag.note(&format!(
1935                 "the link appears in this line:\n\n{line}\n\
1936                      {indicator: <before$}{indicator:^<found$}",
1937                 line = line,
1938                 indicator = "",
1939                 before = link_range.start - last_new_line_offset,
1940                 found = link_range.len(),
1941             ));
1942         }
1943
1944         decorate(&mut diag, span);
1945
1946         diag.emit();
1947     });
1948 }
1949
1950 /// Reports a link that failed to resolve.
1951 ///
1952 /// This also tries to resolve any intermediate path segments that weren't
1953 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1954 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1955 fn resolution_failure(
1956     collector: &mut LinkCollector<'_, '_>,
1957     diag_info: DiagnosticInfo<'_>,
1958     path_str: &str,
1959     disambiguator: Option<Disambiguator>,
1960     kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1961 ) {
1962     let tcx = collector.cx.tcx;
1963     report_diagnostic(
1964         tcx,
1965         BROKEN_INTRA_DOC_LINKS,
1966         &format!("unresolved link to `{}`", path_str),
1967         &diag_info,
1968         |diag, sp| {
1969             let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1970             let assoc_item_not_allowed = |res: Res| {
1971                 let name = res.name(tcx);
1972                 format!(
1973                     "`{}` is {} {}, not a module or type, and cannot have associated items",
1974                     name,
1975                     res.article(),
1976                     res.descr()
1977                 )
1978             };
1979             // ignore duplicates
1980             let mut variants_seen = SmallVec::<[_; 3]>::new();
1981             for mut failure in kinds {
1982                 let variant = std::mem::discriminant(&failure);
1983                 if variants_seen.contains(&variant) {
1984                     continue;
1985                 }
1986                 variants_seen.push(variant);
1987
1988                 if let ResolutionFailure::NotResolved {
1989                     item_id,
1990                     module_id,
1991                     partial_res,
1992                     unresolved,
1993                 } = &mut failure
1994                 {
1995                     use DefKind::*;
1996
1997                     let item_id = *item_id;
1998                     let module_id = *module_id;
1999                     // FIXME(jynelson): this might conflict with my `Self` fix in #76467
2000                     // FIXME: maybe use itertools `collect_tuple` instead?
2001                     fn split(path: &str) -> Option<(&str, &str)> {
2002                         let mut splitter = path.rsplitn(2, "::");
2003                         splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
2004                     }
2005
2006                     // Check if _any_ parent of the path gets resolved.
2007                     // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
2008                     let mut name = path_str;
2009                     'outer: loop {
2010                         let Some((start, end)) = split(name) else {
2011                             // avoid bug that marked [Quux::Z] as missing Z, not Quux
2012                             if partial_res.is_none() {
2013                                 *unresolved = name.into();
2014                             }
2015                             break;
2016                         };
2017                         name = start;
2018                         for ns in [TypeNS, ValueNS, MacroNS] {
2019                             if let Some(res) =
2020                                 collector.check_full_res(ns, start, item_id, module_id, &None)
2021                             {
2022                                 debug!("found partial_res={:?}", res);
2023                                 *partial_res = Some(res);
2024                                 *unresolved = end.into();
2025                                 break 'outer;
2026                             }
2027                         }
2028                         *unresolved = end.into();
2029                     }
2030
2031                     let last_found_module = match *partial_res {
2032                         Some(Res::Def(DefKind::Mod, id)) => Some(id),
2033                         None => Some(module_id),
2034                         _ => None,
2035                     };
2036                     // See if this was a module: `[path]` or `[std::io::nope]`
2037                     if let Some(module) = last_found_module {
2038                         let note = if partial_res.is_some() {
2039                             // Part of the link resolved; e.g. `std::io::nonexistent`
2040                             let module_name = tcx.item_name(module);
2041                             format!("no item named `{}` in module `{}`", unresolved, module_name)
2042                         } else {
2043                             // None of the link resolved; e.g. `Notimported`
2044                             format!("no item named `{}` in scope", unresolved)
2045                         };
2046                         if let Some(span) = sp {
2047                             diag.span_label(span, &note);
2048                         } else {
2049                             diag.note(&note);
2050                         }
2051
2052                         // If the link has `::` in it, assume it was meant to be an intra-doc link.
2053                         // Otherwise, the `[]` might be unrelated.
2054                         // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
2055                         if !path_str.contains("::") {
2056                             diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
2057                         }
2058
2059                         continue;
2060                     }
2061
2062                     // Otherwise, it must be an associated item or variant
2063                     let res = partial_res.expect("None case was handled by `last_found_module`");
2064                     let name = res.name(tcx);
2065                     let kind = match res {
2066                         Res::Def(kind, _) => Some(kind),
2067                         Res::Primitive(_) => None,
2068                     };
2069                     let path_description = if let Some(kind) = kind {
2070                         match kind {
2071                             Mod | ForeignMod => "inner item",
2072                             Struct => "field or associated item",
2073                             Enum | Union => "variant or associated item",
2074                             Variant
2075                             | Field
2076                             | Closure
2077                             | Generator
2078                             | AssocTy
2079                             | AssocConst
2080                             | AssocFn
2081                             | Fn
2082                             | Macro(_)
2083                             | Const
2084                             | ConstParam
2085                             | ExternCrate
2086                             | Use
2087                             | LifetimeParam
2088                             | Ctor(_, _)
2089                             | AnonConst
2090                             | InlineConst => {
2091                                 let note = assoc_item_not_allowed(res);
2092                                 if let Some(span) = sp {
2093                                     diag.span_label(span, &note);
2094                                 } else {
2095                                     diag.note(&note);
2096                                 }
2097                                 return;
2098                             }
2099                             Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
2100                             | Static => "associated item",
2101                             Impl | GlobalAsm => unreachable!("not a path"),
2102                         }
2103                     } else {
2104                         "associated item"
2105                     };
2106                     let note = format!(
2107                         "the {} `{}` has no {} named `{}`",
2108                         res.descr(),
2109                         name,
2110                         disambiguator.map_or(path_description, |d| d.descr()),
2111                         unresolved,
2112                     );
2113                     if let Some(span) = sp {
2114                         diag.span_label(span, &note);
2115                     } else {
2116                         diag.note(&note);
2117                     }
2118
2119                     continue;
2120                 }
2121                 let note = match failure {
2122                     ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2123                     ResolutionFailure::Dummy => continue,
2124                     ResolutionFailure::WrongNamespace { res, expected_ns } => {
2125                         suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2126
2127                         format!(
2128                             "this link resolves to {}, which is not in the {} namespace",
2129                             item(res),
2130                             expected_ns.descr()
2131                         )
2132                     }
2133                     ResolutionFailure::NoParentItem => {
2134                         // FIXME(eddyb) this doesn't belong here, whatever made
2135                         // the `ResolutionFailure::NoParentItem` should emit an
2136                         // immediate or delayed `span_bug` about the issue.
2137                         tcx.sess.delay_span_bug(
2138                             sp.unwrap_or(DUMMY_SP),
2139                             "intra-doc link missing parent item",
2140                         );
2141
2142                         "BUG: all intra-doc links should have a parent item".to_owned()
2143                     }
2144                     ResolutionFailure::MalformedGenerics(variant) => match variant {
2145                         MalformedGenerics::UnbalancedAngleBrackets => {
2146                             String::from("unbalanced angle brackets")
2147                         }
2148                         MalformedGenerics::MissingType => {
2149                             String::from("missing type for generic parameters")
2150                         }
2151                         MalformedGenerics::HasFullyQualifiedSyntax => {
2152                             diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2153                             String::from("fully-qualified syntax is unsupported")
2154                         }
2155                         MalformedGenerics::InvalidPathSeparator => {
2156                             String::from("has invalid path separator")
2157                         }
2158                         MalformedGenerics::TooManyAngleBrackets => {
2159                             String::from("too many angle brackets")
2160                         }
2161                         MalformedGenerics::EmptyAngleBrackets => {
2162                             String::from("empty angle brackets")
2163                         }
2164                     },
2165                 };
2166                 if let Some(span) = sp {
2167                     diag.span_label(span, &note);
2168                 } else {
2169                     diag.note(&note);
2170                 }
2171             }
2172         },
2173     );
2174 }
2175
2176 /// Report an anchor failure.
2177 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2178     let (msg, anchor_idx) = match failure {
2179         AnchorFailure::MultipleAnchors => {
2180             (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2181         }
2182         AnchorFailure::RustdocAnchorConflict(res) => (
2183             format!(
2184                 "`{}` contains an anchor, but links to {kind}s are already anchored",
2185                 diag_info.ori_link,
2186                 kind = res.descr(),
2187             ),
2188             0,
2189         ),
2190     };
2191
2192     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2193         if let Some(mut sp) = sp {
2194             if let Some((fragment_offset, _)) =
2195                 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2196             {
2197                 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2198             }
2199             diag.span_label(sp, "invalid anchor");
2200         }
2201         if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2202             if let Some(sp) = sp {
2203                 span_bug!(sp, "anchors should be allowed now");
2204             } else {
2205                 bug!("anchors should be allowed now");
2206             }
2207         }
2208     });
2209 }
2210
2211 /// Report an error in the link disambiguator.
2212 fn disambiguator_error(
2213     cx: &DocContext<'_>,
2214     mut diag_info: DiagnosticInfo<'_>,
2215     disambiguator_range: Range<usize>,
2216     msg: &str,
2217 ) {
2218     diag_info.link_range = disambiguator_range;
2219     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2220         let msg = format!(
2221             "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2222             crate::DOC_RUST_LANG_ORG_CHANNEL
2223         );
2224         diag.note(&msg);
2225     });
2226 }
2227
2228 /// Report an ambiguity error, where there were multiple possible resolutions.
2229 fn ambiguity_error(
2230     cx: &DocContext<'_>,
2231     diag_info: DiagnosticInfo<'_>,
2232     path_str: &str,
2233     candidates: Vec<Res>,
2234 ) {
2235     let mut msg = format!("`{}` is ", path_str);
2236
2237     match candidates.as_slice() {
2238         [first_def, second_def] => {
2239             msg += &format!(
2240                 "both {} {} and {} {}",
2241                 first_def.article(),
2242                 first_def.descr(),
2243                 second_def.article(),
2244                 second_def.descr(),
2245             );
2246         }
2247         _ => {
2248             let mut candidates = candidates.iter().peekable();
2249             while let Some(res) = candidates.next() {
2250                 if candidates.peek().is_some() {
2251                     msg += &format!("{} {}, ", res.article(), res.descr());
2252                 } else {
2253                     msg += &format!("and {} {}", res.article(), res.descr());
2254                 }
2255             }
2256         }
2257     }
2258
2259     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2260         if let Some(sp) = sp {
2261             diag.span_label(sp, "ambiguous link");
2262         } else {
2263             diag.note("ambiguous link");
2264         }
2265
2266         for res in candidates {
2267             suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2268         }
2269     });
2270 }
2271
2272 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2273 /// disambiguator.
2274 fn suggest_disambiguator(
2275     res: Res,
2276     diag: &mut Diagnostic,
2277     path_str: &str,
2278     ori_link: &str,
2279     sp: Option<rustc_span::Span>,
2280 ) {
2281     let suggestion = res.disambiguator_suggestion();
2282     let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2283
2284     if let Some(sp) = sp {
2285         let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2286         if spans.len() > 1 {
2287             diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2288         } else {
2289             let (sp, suggestion_text) = spans.pop().unwrap();
2290             diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2291         }
2292     } else {
2293         diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2294     }
2295 }
2296
2297 /// Report a link from a public item to a private one.
2298 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2299     let sym;
2300     let item_name = match diag_info.item.name {
2301         Some(name) => {
2302             sym = name;
2303             sym.as_str()
2304         }
2305         None => "<unknown>",
2306     };
2307     let msg =
2308         format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2309
2310     report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2311         if let Some(sp) = sp {
2312             diag.span_label(sp, "this item is private");
2313         }
2314
2315         let note_msg = if cx.render_options.document_private {
2316             "this link resolves only because you passed `--document-private-items`, but will break without"
2317         } else {
2318             "this link will resolve properly if you pass `--document-private-items`"
2319         };
2320         diag.note(note_msg);
2321     });
2322 }
2323
2324 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2325 fn handle_variant(
2326     cx: &DocContext<'_>,
2327     res: Res,
2328 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'static>> {
2329     cx.tcx
2330         .parent(res.def_id(cx.tcx))
2331         .map(|parent| {
2332             let parent_def = Res::Def(DefKind::Enum, parent);
2333             let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2334             (parent_def, Some(ItemFragment(FragmentKind::Variant, variant.def_id)))
2335         })
2336         .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2337 }
2338
2339 /// Resolve a primitive type or value.
2340 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2341     if ns != TypeNS {
2342         return None;
2343     }
2344     use PrimitiveType::*;
2345     let prim = match path_str {
2346         "isize" => Isize,
2347         "i8" => I8,
2348         "i16" => I16,
2349         "i32" => I32,
2350         "i64" => I64,
2351         "i128" => I128,
2352         "usize" => Usize,
2353         "u8" => U8,
2354         "u16" => U16,
2355         "u32" => U32,
2356         "u64" => U64,
2357         "u128" => U128,
2358         "f32" => F32,
2359         "f64" => F64,
2360         "char" => Char,
2361         "bool" | "true" | "false" => Bool,
2362         "str" | "&str" => Str,
2363         // See #80181 for why these don't have symbols associated.
2364         "slice" => Slice,
2365         "array" => Array,
2366         "tuple" => Tuple,
2367         "unit" => Unit,
2368         "pointer" | "*const" | "*mut" => RawPointer,
2369         "reference" | "&" | "&mut" => Reference,
2370         "fn" => Fn,
2371         "never" | "!" => Never,
2372         _ => return None,
2373     };
2374     debug!("resolved primitives {:?}", prim);
2375     Some(Res::Primitive(prim))
2376 }
2377
2378 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2379     let mut stripped_segments = vec![];
2380     let mut path = path_str.chars().peekable();
2381     let mut segment = Vec::new();
2382
2383     while let Some(chr) = path.next() {
2384         match chr {
2385             ':' => {
2386                 if path.next_if_eq(&':').is_some() {
2387                     let stripped_segment =
2388                         strip_generics_from_path_segment(mem::take(&mut segment))?;
2389                     if !stripped_segment.is_empty() {
2390                         stripped_segments.push(stripped_segment);
2391                     }
2392                 } else {
2393                     return Err(ResolutionFailure::MalformedGenerics(
2394                         MalformedGenerics::InvalidPathSeparator,
2395                     ));
2396                 }
2397             }
2398             '<' => {
2399                 segment.push(chr);
2400
2401                 match path.next() {
2402                     Some('<') => {
2403                         return Err(ResolutionFailure::MalformedGenerics(
2404                             MalformedGenerics::TooManyAngleBrackets,
2405                         ));
2406                     }
2407                     Some('>') => {
2408                         return Err(ResolutionFailure::MalformedGenerics(
2409                             MalformedGenerics::EmptyAngleBrackets,
2410                         ));
2411                     }
2412                     Some(chr) => {
2413                         segment.push(chr);
2414
2415                         while let Some(chr) = path.next_if(|c| *c != '>') {
2416                             segment.push(chr);
2417                         }
2418                     }
2419                     None => break,
2420                 }
2421             }
2422             _ => segment.push(chr),
2423         }
2424         trace!("raw segment: {:?}", segment);
2425     }
2426
2427     if !segment.is_empty() {
2428         let stripped_segment = strip_generics_from_path_segment(segment)?;
2429         if !stripped_segment.is_empty() {
2430             stripped_segments.push(stripped_segment);
2431         }
2432     }
2433
2434     debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2435
2436     let stripped_path = stripped_segments.join("::");
2437
2438     if !stripped_path.is_empty() {
2439         Ok(stripped_path)
2440     } else {
2441         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2442     }
2443 }
2444
2445 fn strip_generics_from_path_segment(
2446     segment: Vec<char>,
2447 ) -> Result<String, ResolutionFailure<'static>> {
2448     let mut stripped_segment = String::new();
2449     let mut param_depth = 0;
2450
2451     let mut latest_generics_chunk = String::new();
2452
2453     for c in segment {
2454         if c == '<' {
2455             param_depth += 1;
2456             latest_generics_chunk.clear();
2457         } else if c == '>' {
2458             param_depth -= 1;
2459             if latest_generics_chunk.contains(" as ") {
2460                 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2461                 // Give a helpful error message instead of completely ignoring the angle brackets.
2462                 return Err(ResolutionFailure::MalformedGenerics(
2463                     MalformedGenerics::HasFullyQualifiedSyntax,
2464                 ));
2465             }
2466         } else {
2467             if param_depth == 0 {
2468                 stripped_segment.push(c);
2469             } else {
2470                 latest_generics_chunk.push(c);
2471             }
2472         }
2473     }
2474
2475     if param_depth == 0 {
2476         Ok(stripped_segment)
2477     } else {
2478         // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2479         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))
2480     }
2481 }