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