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