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