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