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