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