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