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