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