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