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