]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_intra_doc_links.rs
Auto merge of #80623 - flip1995:clippyup, r=Manishearth
[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         let mut attrs = item.attrs.doc_strings.iter().peekable();
895         while let Some(attr) = attrs.next() {
896             // `collapse_docs` does not have the behavior we want:
897             // we want `///` and `#[doc]` to count as the same attribute,
898             // but currently it will treat them as separate.
899             // As a workaround, combine all attributes with the same parent module into the same attribute.
900             let mut combined_docs = attr.doc.clone();
901             loop {
902                 match attrs.peek() {
903                     Some(next) if next.parent_module == attr.parent_module => {
904                         combined_docs.push('\n');
905                         combined_docs.push_str(&attrs.next().unwrap().doc);
906                     }
907                     _ => break,
908                 }
909             }
910             debug!("combined_docs={}", combined_docs);
911
912             let (krate, parent_node) = if let Some(id) = attr.parent_module {
913                 trace!("docs {:?} came from {:?}", attr.doc, id);
914                 (id.krate, Some(id))
915             } else {
916                 trace!("no parent found for {:?}", attr.doc);
917                 (item.def_id.krate, parent_node)
918             };
919             // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
920             // This is a degenerate case and it's not supported by rustdoc.
921             for (ori_link, link_range) in markdown_links(&combined_docs) {
922                 let link = self.resolve_link(
923                     &item,
924                     &combined_docs,
925                     &self_name,
926                     parent_node,
927                     krate,
928                     ori_link,
929                     link_range,
930                 );
931                 if let Some(link) = link {
932                     item.attrs.links.push(link);
933                 }
934             }
935         }
936
937         Some(if item.is_mod() {
938             if !item.attrs.inner_docs {
939                 self.mod_ids.push(item.def_id);
940             }
941
942             let ret = self.fold_item_recur(item);
943             self.mod_ids.pop();
944             ret
945         } else {
946             self.fold_item_recur(item)
947         })
948     }
949 }
950
951 impl LinkCollector<'_, '_> {
952     /// This is the entry point for resolving an intra-doc link.
953     ///
954     /// FIXME(jynelson): this is way too many arguments
955     fn resolve_link(
956         &mut self,
957         item: &Item,
958         dox: &str,
959         self_name: &Option<String>,
960         parent_node: Option<DefId>,
961         krate: CrateNum,
962         ori_link: String,
963         link_range: Range<usize>,
964     ) -> Option<ItemLink> {
965         trace!("considering link '{}'", ori_link);
966
967         // Bail early for real links.
968         if ori_link.contains('/') {
969             return None;
970         }
971
972         // [] is mostly likely not supposed to be a link
973         if ori_link.is_empty() {
974             return None;
975         }
976
977         let cx = self.cx;
978         let link = ori_link.replace("`", "");
979         let parts = link.split('#').collect::<Vec<_>>();
980         let (link, extra_fragment) = if parts.len() > 2 {
981             // A valid link can't have multiple #'s
982             anchor_failure(cx, &item, &link, dox, link_range, AnchorFailure::MultipleAnchors);
983             return None;
984         } else if parts.len() == 2 {
985             if parts[0].trim().is_empty() {
986                 // This is an anchor to an element of the current page, nothing to do in here!
987                 return None;
988             }
989             (parts[0], Some(parts[1].to_owned()))
990         } else {
991             (parts[0], None)
992         };
993
994         // Parse and strip the disambiguator from the link, if present.
995         let (mut path_str, disambiguator) = if let Ok((d, path)) = Disambiguator::from_str(&link) {
996             (path.trim(), Some(d))
997         } else {
998             (link.trim(), None)
999         };
1000
1001         if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch))) {
1002             return None;
1003         }
1004
1005         // We stripped `()` and `!` when parsing the disambiguator.
1006         // Add them back to be displayed, but not prefix disambiguators.
1007         let link_text =
1008             disambiguator.map(|d| d.display_for(path_str)).unwrap_or_else(|| path_str.to_owned());
1009
1010         // In order to correctly resolve intra-doc-links we need to
1011         // pick a base AST node to work from.  If the documentation for
1012         // this module came from an inner comment (//!) then we anchor
1013         // our name resolution *inside* the module.  If, on the other
1014         // hand it was an outer comment (///) then we anchor the name
1015         // resolution in the parent module on the basis that the names
1016         // used are more likely to be intended to be parent names.  For
1017         // this, we set base_node to None for inner comments since
1018         // we've already pushed this node onto the resolution stack but
1019         // for outer comments we explicitly try and resolve against the
1020         // parent_node first.
1021         let base_node = if item.is_mod() && item.attrs.inner_docs {
1022             self.mod_ids.last().copied()
1023         } else {
1024             parent_node
1025         };
1026
1027         let mut module_id = if let Some(id) = base_node {
1028             id
1029         } else {
1030             // This is a bug.
1031             debug!("attempting to resolve item without parent module: {}", path_str);
1032             resolution_failure(
1033                 self,
1034                 &item,
1035                 path_str,
1036                 disambiguator,
1037                 dox,
1038                 link_range,
1039                 smallvec![ResolutionFailure::NoParentItem],
1040             );
1041             return None;
1042         };
1043
1044         let resolved_self;
1045         // replace `Self` with suitable item's parent name
1046         if path_str.starts_with("Self::") {
1047             if let Some(ref name) = self_name {
1048                 resolved_self = format!("{}::{}", name, &path_str[6..]);
1049                 path_str = &resolved_self;
1050             }
1051         } else if path_str.starts_with("crate::") {
1052             use rustc_span::def_id::CRATE_DEF_INDEX;
1053
1054             // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1055             // But rustdoc wants it to mean the crate this item was originally present in.
1056             // To work around this, remove it and resolve relative to the crate root instead.
1057             // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1058             // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1059             // FIXME(#78696): This doesn't always work.
1060             resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1061             path_str = &resolved_self;
1062             module_id = DefId { krate, index: CRATE_DEF_INDEX };
1063         }
1064
1065         // Strip generics from the path.
1066         let stripped_path_string;
1067         if path_str.contains(['<', '>'].as_slice()) {
1068             stripped_path_string = match strip_generics_from_path(path_str) {
1069                 Ok(path) => path,
1070                 Err(err_kind) => {
1071                     debug!("link has malformed generics: {}", path_str);
1072                     resolution_failure(
1073                         self,
1074                         &item,
1075                         path_str,
1076                         disambiguator,
1077                         dox,
1078                         link_range,
1079                         smallvec![err_kind],
1080                     );
1081                     return None;
1082                 }
1083             };
1084             path_str = &stripped_path_string;
1085         }
1086         // Sanity check to make sure we don't have any angle brackets after stripping generics.
1087         assert!(!path_str.contains(['<', '>'].as_slice()));
1088
1089         // The link is not an intra-doc link if it still contains spaces after stripping generics.
1090         if path_str.contains(' ') {
1091             return None;
1092         }
1093
1094         let key = ResolutionInfo {
1095             module_id,
1096             dis: disambiguator,
1097             path_str: path_str.to_owned(),
1098             extra_fragment,
1099         };
1100         let diag =
1101             DiagnosticInfo { item, dox, ori_link: &ori_link, link_range: link_range.clone() };
1102         let (mut res, mut fragment) = self.resolve_with_disambiguator_cached(key, diag)?;
1103
1104         // Check for a primitive which might conflict with a module
1105         // Report the ambiguity and require that the user specify which one they meant.
1106         // FIXME: could there ever be a primitive not in the type namespace?
1107         if matches!(
1108             disambiguator,
1109             None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1110         ) && !matches!(res, Res::Primitive(_))
1111         {
1112             if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1113                 // `prim@char`
1114                 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1115                     if fragment.is_some() {
1116                         anchor_failure(
1117                             cx,
1118                             &item,
1119                             path_str,
1120                             dox,
1121                             link_range,
1122                             AnchorFailure::RustdocAnchorConflict(prim),
1123                         );
1124                         return None;
1125                     }
1126                     res = prim;
1127                     fragment = Some(prim.name(self.cx.tcx));
1128                 } else {
1129                     // `[char]` when a `char` module is in scope
1130                     let candidates = vec![res, prim];
1131                     ambiguity_error(cx, &item, path_str, dox, link_range, candidates);
1132                     return None;
1133                 }
1134             }
1135         }
1136
1137         let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
1138             // The resolved item did not match the disambiguator; give a better error than 'not found'
1139             let msg = format!("incompatible link kind for `{}`", path_str);
1140             let callback = |diag: &mut DiagnosticBuilder<'_>, sp| {
1141                 let note = format!(
1142                     "this link resolved to {} {}, which is not {} {}",
1143                     resolved.article(),
1144                     resolved.descr(),
1145                     specified.article(),
1146                     specified.descr()
1147                 );
1148                 diag.note(&note);
1149                 suggest_disambiguator(resolved, diag, path_str, dox, sp, &link_range);
1150             };
1151             report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, &item, dox, &link_range, callback);
1152         };
1153         match res {
1154             Res::Primitive(_) => match disambiguator {
1155                 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
1156                     Some(ItemLink { link: ori_link, link_text, did: None, fragment })
1157                 }
1158                 Some(other) => {
1159                     report_mismatch(other, Disambiguator::Primitive);
1160                     None
1161                 }
1162             },
1163             Res::Def(kind, id) => {
1164                 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
1165
1166                 // Disallow e.g. linking to enums with `struct@`
1167                 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1168                 match (self.kind_side_channel.take().map(|(kind, _)| kind).unwrap_or(kind), disambiguator) {
1169                     | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1170                     // NOTE: this allows 'method' to mean both normal functions and associated functions
1171                     // This can't cause ambiguity because both are in the same namespace.
1172                     | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1173                     // These are namespaces; allow anything in the namespace to match
1174                     | (_, Some(Disambiguator::Namespace(_)))
1175                     // If no disambiguator given, allow anything
1176                     | (_, None)
1177                     // All of these are valid, so do nothing
1178                     => {}
1179                     (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1180                     (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1181                         report_mismatch(specified, Disambiguator::Kind(kind));
1182                         return None;
1183                     }
1184                 }
1185
1186                 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1187                 if let Some((src_id, dst_id)) = id
1188                     .as_local()
1189                     .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
1190                 {
1191                     use rustc_hir::def_id::LOCAL_CRATE;
1192
1193                     let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
1194                     let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
1195
1196                     if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
1197                         && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
1198                     {
1199                         privacy_error(cx, &item, &path_str, dox, link_range);
1200                     }
1201                 }
1202                 let id = clean::register_res(cx, rustc_hir::def::Res::Def(kind, id));
1203                 Some(ItemLink { link: ori_link, link_text, did: Some(id), fragment })
1204             }
1205         }
1206     }
1207
1208     fn resolve_with_disambiguator_cached(
1209         &mut self,
1210         key: ResolutionInfo,
1211         diag: DiagnosticInfo<'_>,
1212     ) -> Option<(Res, Option<String>)> {
1213         // Try to look up both the result and the corresponding side channel value
1214         if let Some(ref cached) = self.visited_links.get(&key) {
1215             self.kind_side_channel.set(cached.side_channel);
1216             return Some(cached.res.clone());
1217         }
1218
1219         let res = self.resolve_with_disambiguator(&key, diag);
1220
1221         // Cache only if resolved successfully - don't silence duplicate errors
1222         if let Some(res) = &res {
1223             // Store result for the actual namespace
1224             self.visited_links.insert(
1225                 key,
1226                 CachedLink {
1227                     res: res.clone(),
1228                     side_channel: self.kind_side_channel.clone().into_inner(),
1229                 },
1230             );
1231         }
1232
1233         res
1234     }
1235
1236     /// After parsing the disambiguator, resolve the main part of the link.
1237     // FIXME(jynelson): wow this is just so much
1238     fn resolve_with_disambiguator(
1239         &self,
1240         key: &ResolutionInfo,
1241         diag: DiagnosticInfo<'_>,
1242     ) -> Option<(Res, Option<String>)> {
1243         let disambiguator = key.dis;
1244         let path_str = &key.path_str;
1245         let base_node = key.module_id;
1246         let extra_fragment = &key.extra_fragment;
1247
1248         match disambiguator.map(Disambiguator::ns) {
1249             Some(ns @ (ValueNS | TypeNS)) => {
1250                 match self.resolve(path_str, ns, base_node, extra_fragment) {
1251                     Ok(res) => Some(res),
1252                     Err(ErrorKind::Resolve(box mut kind)) => {
1253                         // We only looked in one namespace. Try to give a better error if possible.
1254                         if kind.full_res().is_none() {
1255                             let other_ns = if ns == ValueNS { TypeNS } else { ValueNS };
1256                             // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1257                             // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1258                             for &new_ns in &[other_ns, MacroNS] {
1259                                 if let Some(res) =
1260                                     self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1261                                 {
1262                                     kind = ResolutionFailure::WrongNamespace(res, ns);
1263                                     break;
1264                                 }
1265                             }
1266                         }
1267                         resolution_failure(
1268                             self,
1269                             diag.item,
1270                             path_str,
1271                             disambiguator,
1272                             diag.dox,
1273                             diag.link_range,
1274                             smallvec![kind],
1275                         );
1276                         // This could just be a normal link or a broken link
1277                         // we could potentially check if something is
1278                         // "intra-doc-link-like" and warn in that case.
1279                         None
1280                     }
1281                     Err(ErrorKind::AnchorFailure(msg)) => {
1282                         anchor_failure(
1283                             self.cx,
1284                             diag.item,
1285                             diag.ori_link,
1286                             diag.dox,
1287                             diag.link_range,
1288                             msg,
1289                         );
1290                         None
1291                     }
1292                 }
1293             }
1294             None => {
1295                 // Try everything!
1296                 let mut candidates = PerNS {
1297                     macro_ns: self
1298                         .resolve_macro(path_str, base_node)
1299                         .map(|res| (res, extra_fragment.clone())),
1300                     type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1301                         Ok(res) => {
1302                             debug!("got res in TypeNS: {:?}", res);
1303                             Ok(res)
1304                         }
1305                         Err(ErrorKind::AnchorFailure(msg)) => {
1306                             anchor_failure(
1307                                 self.cx,
1308                                 diag.item,
1309                                 diag.ori_link,
1310                                 diag.dox,
1311                                 diag.link_range,
1312                                 msg,
1313                             );
1314                             return None;
1315                         }
1316                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1317                     },
1318                     value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1319                         Ok(res) => Ok(res),
1320                         Err(ErrorKind::AnchorFailure(msg)) => {
1321                             anchor_failure(
1322                                 self.cx,
1323                                 diag.item,
1324                                 diag.ori_link,
1325                                 diag.dox,
1326                                 diag.link_range,
1327                                 msg,
1328                             );
1329                             return None;
1330                         }
1331                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1332                     }
1333                     .and_then(|(res, fragment)| {
1334                         // Constructors are picked up in the type namespace.
1335                         match res {
1336                             Res::Def(DefKind::Ctor(..), _) => {
1337                                 Err(ResolutionFailure::WrongNamespace(res, TypeNS))
1338                             }
1339                             _ => {
1340                                 match (fragment, extra_fragment.clone()) {
1341                                     (Some(fragment), Some(_)) => {
1342                                         // Shouldn't happen but who knows?
1343                                         Ok((res, Some(fragment)))
1344                                     }
1345                                     (fragment, None) | (None, fragment) => Ok((res, fragment)),
1346                                 }
1347                             }
1348                         }
1349                     }),
1350                 };
1351
1352                 let len = candidates.iter().filter(|res| res.is_ok()).count();
1353
1354                 if len == 0 {
1355                     resolution_failure(
1356                         self,
1357                         diag.item,
1358                         path_str,
1359                         disambiguator,
1360                         diag.dox,
1361                         diag.link_range,
1362                         candidates.into_iter().filter_map(|res| res.err()).collect(),
1363                     );
1364                     // this could just be a normal link
1365                     return None;
1366                 }
1367
1368                 if len == 1 {
1369                     Some(candidates.into_iter().filter_map(|res| res.ok()).next().unwrap())
1370                 } else if len == 2 && is_derive_trait_collision(&candidates) {
1371                     Some(candidates.type_ns.unwrap())
1372                 } else {
1373                     if is_derive_trait_collision(&candidates) {
1374                         candidates.macro_ns = Err(ResolutionFailure::Dummy);
1375                     }
1376                     // If we're reporting an ambiguity, don't mention the namespaces that failed
1377                     let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1378                     ambiguity_error(
1379                         self.cx,
1380                         diag.item,
1381                         path_str,
1382                         diag.dox,
1383                         diag.link_range,
1384                         candidates.present_items().collect(),
1385                     );
1386                     None
1387                 }
1388             }
1389             Some(MacroNS) => {
1390                 match self.resolve_macro(path_str, base_node) {
1391                     Ok(res) => Some((res, extra_fragment.clone())),
1392                     Err(mut kind) => {
1393                         // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1394                         for &ns in &[TypeNS, ValueNS] {
1395                             if let Some(res) =
1396                                 self.check_full_res(ns, path_str, base_node, extra_fragment)
1397                             {
1398                                 kind = ResolutionFailure::WrongNamespace(res, MacroNS);
1399                                 break;
1400                             }
1401                         }
1402                         resolution_failure(
1403                             self,
1404                             diag.item,
1405                             path_str,
1406                             disambiguator,
1407                             diag.dox,
1408                             diag.link_range,
1409                             smallvec![kind],
1410                         );
1411                         None
1412                     }
1413                 }
1414             }
1415         }
1416     }
1417 }
1418
1419 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1420 /// Disambiguators for a link.
1421 enum Disambiguator {
1422     /// `prim@`
1423     ///
1424     /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1425     Primitive,
1426     /// `struct@` or `f()`
1427     Kind(DefKind),
1428     /// `type@`
1429     Namespace(Namespace),
1430 }
1431
1432 impl Disambiguator {
1433     /// The text that should be displayed when the path is rendered as HTML.
1434     ///
1435     /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1436     fn display_for(&self, path: &str) -> String {
1437         match self {
1438             // FIXME: this will have different output if the user had `m!()` originally.
1439             Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1440             Self::Kind(DefKind::Fn) => format!("{}()", path),
1441             _ => path.to_owned(),
1442         }
1443     }
1444
1445     /// Given a link, parse and return `(disambiguator, path_str)`
1446     fn from_str(link: &str) -> Result<(Self, &str), ()> {
1447         use Disambiguator::{Kind, Namespace as NS, Primitive};
1448
1449         let find_suffix = || {
1450             let suffixes = [
1451                 ("!()", DefKind::Macro(MacroKind::Bang)),
1452                 ("()", DefKind::Fn),
1453                 ("!", DefKind::Macro(MacroKind::Bang)),
1454             ];
1455             for &(suffix, kind) in &suffixes {
1456                 if let Some(link) = link.strip_suffix(suffix) {
1457                     // Avoid turning `!` or `()` into an empty string
1458                     if !link.is_empty() {
1459                         return Ok((Kind(kind), link));
1460                     }
1461                 }
1462             }
1463             Err(())
1464         };
1465
1466         if let Some(idx) = link.find('@') {
1467             let (prefix, rest) = link.split_at(idx);
1468             let d = match prefix {
1469                 "struct" => Kind(DefKind::Struct),
1470                 "enum" => Kind(DefKind::Enum),
1471                 "trait" => Kind(DefKind::Trait),
1472                 "union" => Kind(DefKind::Union),
1473                 "module" | "mod" => Kind(DefKind::Mod),
1474                 "const" | "constant" => Kind(DefKind::Const),
1475                 "static" => Kind(DefKind::Static),
1476                 "function" | "fn" | "method" => Kind(DefKind::Fn),
1477                 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1478                 "type" => NS(Namespace::TypeNS),
1479                 "value" => NS(Namespace::ValueNS),
1480                 "macro" => NS(Namespace::MacroNS),
1481                 "prim" | "primitive" => Primitive,
1482                 _ => return find_suffix(),
1483             };
1484             Ok((d, &rest[1..]))
1485         } else {
1486             find_suffix()
1487         }
1488     }
1489
1490     fn from_res(res: Res) -> Self {
1491         match res {
1492             Res::Def(kind, _) => Disambiguator::Kind(kind),
1493             Res::Primitive(_) => Disambiguator::Primitive,
1494         }
1495     }
1496
1497     /// Used for error reporting.
1498     fn suggestion(self) -> Suggestion {
1499         let kind = match self {
1500             Disambiguator::Primitive => return Suggestion::Prefix("prim"),
1501             Disambiguator::Kind(kind) => kind,
1502             Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1503         };
1504         if kind == DefKind::Macro(MacroKind::Bang) {
1505             return Suggestion::Macro;
1506         } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1507             return Suggestion::Function;
1508         }
1509
1510         let prefix = match kind {
1511             DefKind::Struct => "struct",
1512             DefKind::Enum => "enum",
1513             DefKind::Trait => "trait",
1514             DefKind::Union => "union",
1515             DefKind::Mod => "mod",
1516             DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1517                 "const"
1518             }
1519             DefKind::Static => "static",
1520             DefKind::Macro(MacroKind::Derive) => "derive",
1521             // Now handle things that don't have a specific disambiguator
1522             _ => match kind
1523                 .ns()
1524                 .expect("tried to calculate a disambiguator for a def without a namespace?")
1525             {
1526                 Namespace::TypeNS => "type",
1527                 Namespace::ValueNS => "value",
1528                 Namespace::MacroNS => "macro",
1529             },
1530         };
1531
1532         Suggestion::Prefix(prefix)
1533     }
1534
1535     fn ns(self) -> Namespace {
1536         match self {
1537             Self::Namespace(n) => n,
1538             Self::Kind(k) => {
1539                 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1540             }
1541             Self::Primitive => TypeNS,
1542         }
1543     }
1544
1545     fn article(self) -> &'static str {
1546         match self {
1547             Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1548             Self::Kind(k) => k.article(),
1549             Self::Primitive => "a",
1550         }
1551     }
1552
1553     fn descr(self) -> &'static str {
1554         match self {
1555             Self::Namespace(n) => n.descr(),
1556             // HACK(jynelson): by looking at the source I saw the DefId we pass
1557             // for `expected.descr()` doesn't matter, since it's not a crate
1558             Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1559             Self::Primitive => "builtin type",
1560         }
1561     }
1562 }
1563
1564 /// A suggestion to show in a diagnostic.
1565 enum Suggestion {
1566     /// `struct@`
1567     Prefix(&'static str),
1568     /// `f()`
1569     Function,
1570     /// `m!`
1571     Macro,
1572 }
1573
1574 impl Suggestion {
1575     fn descr(&self) -> Cow<'static, str> {
1576         match self {
1577             Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1578             Self::Function => "add parentheses".into(),
1579             Self::Macro => "add an exclamation mark".into(),
1580         }
1581     }
1582
1583     fn as_help(&self, path_str: &str) -> String {
1584         // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1585         match self {
1586             Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1587             Self::Function => format!("{}()", path_str),
1588             Self::Macro => format!("{}!", path_str),
1589         }
1590     }
1591 }
1592
1593 /// Reports a diagnostic for an intra-doc link.
1594 ///
1595 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1596 /// the entire documentation block is used for the lint. If a range is provided but the span
1597 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1598 ///
1599 /// The `decorate` callback is invoked in all cases to allow further customization of the
1600 /// diagnostic before emission. If the span of the link was able to be determined, the second
1601 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1602 /// to it.
1603 fn report_diagnostic(
1604     cx: &DocContext<'_>,
1605     lint: &'static Lint,
1606     msg: &str,
1607     item: &Item,
1608     dox: &str,
1609     link_range: &Range<usize>,
1610     decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1611 ) {
1612     let hir_id = match cx.as_local_hir_id(item.def_id) {
1613         Some(hir_id) => hir_id,
1614         None => {
1615             // If non-local, no need to check anything.
1616             info!("ignoring warning from parent crate: {}", msg);
1617             return;
1618         }
1619     };
1620
1621     let attrs = &item.attrs;
1622     let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1623
1624     cx.tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1625         let mut diag = lint.build(msg);
1626
1627         let span = super::source_span_for_markdown_range(cx, dox, link_range, attrs);
1628
1629         if let Some(sp) = span {
1630             diag.set_span(sp);
1631         } else {
1632             // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1633             //                       ^     ~~~~
1634             //                       |     link_range
1635             //                       last_new_line_offset
1636             let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1637             let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1638
1639             // Print the line containing the `link_range` and manually mark it with '^'s.
1640             diag.note(&format!(
1641                 "the link appears in this line:\n\n{line}\n\
1642                      {indicator: <before$}{indicator:^<found$}",
1643                 line = line,
1644                 indicator = "",
1645                 before = link_range.start - last_new_line_offset,
1646                 found = link_range.len(),
1647             ));
1648         }
1649
1650         decorate(&mut diag, span);
1651
1652         diag.emit();
1653     });
1654 }
1655
1656 /// Reports a link that failed to resolve.
1657 ///
1658 /// This also tries to resolve any intermediate path segments that weren't
1659 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1660 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1661 fn resolution_failure(
1662     collector: &LinkCollector<'_, '_>,
1663     item: &Item,
1664     path_str: &str,
1665     disambiguator: Option<Disambiguator>,
1666     dox: &str,
1667     link_range: Range<usize>,
1668     kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1669 ) {
1670     let tcx = collector.cx.tcx;
1671     report_diagnostic(
1672         collector.cx,
1673         BROKEN_INTRA_DOC_LINKS,
1674         &format!("unresolved link to `{}`", path_str),
1675         item,
1676         dox,
1677         &link_range,
1678         |diag, sp| {
1679             let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1680             let assoc_item_not_allowed = |res: Res| {
1681                 let name = res.name(tcx);
1682                 format!(
1683                     "`{}` is {} {}, not a module or type, and cannot have associated items",
1684                     name,
1685                     res.article(),
1686                     res.descr()
1687                 )
1688             };
1689             // ignore duplicates
1690             let mut variants_seen = SmallVec::<[_; 3]>::new();
1691             for mut failure in kinds {
1692                 let variant = std::mem::discriminant(&failure);
1693                 if variants_seen.contains(&variant) {
1694                     continue;
1695                 }
1696                 variants_seen.push(variant);
1697
1698                 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1699                     &mut failure
1700                 {
1701                     use DefKind::*;
1702
1703                     let module_id = *module_id;
1704                     // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1705                     // FIXME: maybe use itertools `collect_tuple` instead?
1706                     fn split(path: &str) -> Option<(&str, &str)> {
1707                         let mut splitter = path.rsplitn(2, "::");
1708                         splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1709                     }
1710
1711                     // Check if _any_ parent of the path gets resolved.
1712                     // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1713                     let mut name = path_str;
1714                     'outer: loop {
1715                         let (start, end) = if let Some(x) = split(name) {
1716                             x
1717                         } else {
1718                             // avoid bug that marked [Quux::Z] as missing Z, not Quux
1719                             if partial_res.is_none() {
1720                                 *unresolved = name.into();
1721                             }
1722                             break;
1723                         };
1724                         name = start;
1725                         for &ns in &[TypeNS, ValueNS, MacroNS] {
1726                             if let Some(res) =
1727                                 collector.check_full_res(ns, &start, module_id, &None)
1728                             {
1729                                 debug!("found partial_res={:?}", res);
1730                                 *partial_res = Some(res);
1731                                 *unresolved = end.into();
1732                                 break 'outer;
1733                             }
1734                         }
1735                         *unresolved = end.into();
1736                     }
1737
1738                     let last_found_module = match *partial_res {
1739                         Some(Res::Def(DefKind::Mod, id)) => Some(id),
1740                         None => Some(module_id),
1741                         _ => None,
1742                     };
1743                     // See if this was a module: `[path]` or `[std::io::nope]`
1744                     if let Some(module) = last_found_module {
1745                         let note = if partial_res.is_some() {
1746                             // Part of the link resolved; e.g. `std::io::nonexistent`
1747                             let module_name = tcx.item_name(module);
1748                             format!("no item named `{}` in module `{}`", unresolved, module_name)
1749                         } else {
1750                             // None of the link resolved; e.g. `Notimported`
1751                             format!("no item named `{}` in scope", unresolved)
1752                         };
1753                         if let Some(span) = sp {
1754                             diag.span_label(span, &note);
1755                         } else {
1756                             diag.note(&note);
1757                         }
1758
1759                         // If the link has `::` in it, assume it was meant to be an intra-doc link.
1760                         // Otherwise, the `[]` might be unrelated.
1761                         // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
1762                         if !path_str.contains("::") {
1763                             diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1764                         }
1765
1766                         continue;
1767                     }
1768
1769                     // Otherwise, it must be an associated item or variant
1770                     let res = partial_res.expect("None case was handled by `last_found_module`");
1771                     let name = res.name(tcx);
1772                     let kind = match res {
1773                         Res::Def(kind, _) => Some(kind),
1774                         Res::Primitive(_) => None,
1775                     };
1776                     let path_description = if let Some(kind) = kind {
1777                         match kind {
1778                             Mod | ForeignMod => "inner item",
1779                             Struct => "field or associated item",
1780                             Enum | Union => "variant or associated item",
1781                             Variant
1782                             | Field
1783                             | Closure
1784                             | Generator
1785                             | AssocTy
1786                             | AssocConst
1787                             | AssocFn
1788                             | Fn
1789                             | Macro(_)
1790                             | Const
1791                             | ConstParam
1792                             | ExternCrate
1793                             | Use
1794                             | LifetimeParam
1795                             | Ctor(_, _)
1796                             | AnonConst => {
1797                                 let note = assoc_item_not_allowed(res);
1798                                 if let Some(span) = sp {
1799                                     diag.span_label(span, &note);
1800                                 } else {
1801                                     diag.note(&note);
1802                                 }
1803                                 return;
1804                             }
1805                             Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
1806                             | Static => "associated item",
1807                             Impl | GlobalAsm => unreachable!("not a path"),
1808                         }
1809                     } else {
1810                         "associated item"
1811                     };
1812                     let note = format!(
1813                         "the {} `{}` has no {} named `{}`",
1814                         res.descr(),
1815                         name,
1816                         disambiguator.map_or(path_description, |d| d.descr()),
1817                         unresolved,
1818                     );
1819                     if let Some(span) = sp {
1820                         diag.span_label(span, &note);
1821                     } else {
1822                         diag.note(&note);
1823                     }
1824
1825                     continue;
1826                 }
1827                 let note = match failure {
1828                     ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
1829                     ResolutionFailure::Dummy => continue,
1830                     ResolutionFailure::WrongNamespace(res, expected_ns) => {
1831                         if let Res::Def(kind, _) = res {
1832                             let disambiguator = Disambiguator::Kind(kind);
1833                             suggest_disambiguator(
1834                                 disambiguator,
1835                                 diag,
1836                                 path_str,
1837                                 dox,
1838                                 sp,
1839                                 &link_range,
1840                             )
1841                         }
1842
1843                         format!(
1844                             "this link resolves to {}, which is not in the {} namespace",
1845                             item(res),
1846                             expected_ns.descr()
1847                         )
1848                     }
1849                     ResolutionFailure::NoParentItem => {
1850                         diag.level = rustc_errors::Level::Bug;
1851                         "all intra doc links should have a parent item".to_owned()
1852                     }
1853                     ResolutionFailure::MalformedGenerics(variant) => match variant {
1854                         MalformedGenerics::UnbalancedAngleBrackets => {
1855                             String::from("unbalanced angle brackets")
1856                         }
1857                         MalformedGenerics::MissingType => {
1858                             String::from("missing type for generic parameters")
1859                         }
1860                         MalformedGenerics::HasFullyQualifiedSyntax => {
1861                             diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
1862                             String::from("fully-qualified syntax is unsupported")
1863                         }
1864                         MalformedGenerics::InvalidPathSeparator => {
1865                             String::from("has invalid path separator")
1866                         }
1867                         MalformedGenerics::TooManyAngleBrackets => {
1868                             String::from("too many angle brackets")
1869                         }
1870                         MalformedGenerics::EmptyAngleBrackets => {
1871                             String::from("empty angle brackets")
1872                         }
1873                     },
1874                 };
1875                 if let Some(span) = sp {
1876                     diag.span_label(span, &note);
1877                 } else {
1878                     diag.note(&note);
1879                 }
1880             }
1881         },
1882     );
1883 }
1884
1885 /// Report an anchor failure.
1886 fn anchor_failure(
1887     cx: &DocContext<'_>,
1888     item: &Item,
1889     path_str: &str,
1890     dox: &str,
1891     link_range: Range<usize>,
1892     failure: AnchorFailure,
1893 ) {
1894     let msg = match failure {
1895         AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1896         AnchorFailure::RustdocAnchorConflict(res) => format!(
1897             "`{}` contains an anchor, but links to {kind}s are already anchored",
1898             path_str,
1899             kind = res.descr(),
1900         ),
1901     };
1902
1903     report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1904         if let Some(sp) = sp {
1905             diag.span_label(sp, "contains invalid anchor");
1906         }
1907     });
1908 }
1909
1910 /// Report an ambiguity error, where there were multiple possible resolutions.
1911 fn ambiguity_error(
1912     cx: &DocContext<'_>,
1913     item: &Item,
1914     path_str: &str,
1915     dox: &str,
1916     link_range: Range<usize>,
1917     candidates: Vec<Res>,
1918 ) {
1919     let mut msg = format!("`{}` is ", path_str);
1920
1921     match candidates.as_slice() {
1922         [first_def, second_def] => {
1923             msg += &format!(
1924                 "both {} {} and {} {}",
1925                 first_def.article(),
1926                 first_def.descr(),
1927                 second_def.article(),
1928                 second_def.descr(),
1929             );
1930         }
1931         _ => {
1932             let mut candidates = candidates.iter().peekable();
1933             while let Some(res) = candidates.next() {
1934                 if candidates.peek().is_some() {
1935                     msg += &format!("{} {}, ", res.article(), res.descr());
1936                 } else {
1937                     msg += &format!("and {} {}", res.article(), res.descr());
1938                 }
1939             }
1940         }
1941     }
1942
1943     report_diagnostic(cx, BROKEN_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
1944         if let Some(sp) = sp {
1945             diag.span_label(sp, "ambiguous link");
1946         } else {
1947             diag.note("ambiguous link");
1948         }
1949
1950         for res in candidates {
1951             let disambiguator = Disambiguator::from_res(res);
1952             suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1953         }
1954     });
1955 }
1956
1957 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
1958 /// disambiguator.
1959 fn suggest_disambiguator(
1960     disambiguator: Disambiguator,
1961     diag: &mut DiagnosticBuilder<'_>,
1962     path_str: &str,
1963     dox: &str,
1964     sp: Option<rustc_span::Span>,
1965     link_range: &Range<usize>,
1966 ) {
1967     let suggestion = disambiguator.suggestion();
1968     let help = format!("to link to the {}, {}", disambiguator.descr(), suggestion.descr());
1969
1970     if let Some(sp) = sp {
1971         let msg = if dox.bytes().nth(link_range.start) == Some(b'`') {
1972             format!("`{}`", suggestion.as_help(path_str))
1973         } else {
1974             suggestion.as_help(path_str)
1975         };
1976
1977         diag.span_suggestion(sp, &help, msg, Applicability::MaybeIncorrect);
1978     } else {
1979         diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
1980     }
1981 }
1982
1983 /// Report a link from a public item to a private one.
1984 fn privacy_error(
1985     cx: &DocContext<'_>,
1986     item: &Item,
1987     path_str: &str,
1988     dox: &str,
1989     link_range: Range<usize>,
1990 ) {
1991     let sym;
1992     let item_name = match item.name {
1993         Some(name) => {
1994             sym = name.as_str();
1995             &*sym
1996         }
1997         None => "<unknown>",
1998     };
1999     let msg =
2000         format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2001
2002     report_diagnostic(cx, PRIVATE_INTRA_DOC_LINKS, &msg, item, dox, &link_range, |diag, sp| {
2003         if let Some(sp) = sp {
2004             diag.span_label(sp, "this item is private");
2005         }
2006
2007         let note_msg = if cx.render_options.document_private {
2008             "this link resolves only because you passed `--document-private-items`, but will break without"
2009         } else {
2010             "this link will resolve properly if you pass `--document-private-items`"
2011         };
2012         diag.note(note_msg);
2013     });
2014 }
2015
2016 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2017 fn handle_variant(
2018     cx: &DocContext<'_>,
2019     res: Res,
2020     extra_fragment: &Option<String>,
2021 ) -> Result<(Res, Option<String>), ErrorKind<'static>> {
2022     use rustc_middle::ty::DefIdTree;
2023
2024     if extra_fragment.is_some() {
2025         return Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res)));
2026     }
2027     cx.tcx
2028         .parent(res.def_id())
2029         .map(|parent| {
2030             let parent_def = Res::Def(DefKind::Enum, parent);
2031             let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2032             (parent_def, Some(format!("variant.{}", variant.ident.name)))
2033         })
2034         .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2035 }
2036
2037 /// Resolve a primitive type or value.
2038 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2039     if ns != TypeNS {
2040         return None;
2041     }
2042     use PrimitiveType::*;
2043     let prim = match path_str {
2044         "isize" => Isize,
2045         "i8" => I8,
2046         "i16" => I16,
2047         "i32" => I32,
2048         "i64" => I64,
2049         "i128" => I128,
2050         "usize" => Usize,
2051         "u8" => U8,
2052         "u16" => U16,
2053         "u32" => U32,
2054         "u64" => U64,
2055         "u128" => U128,
2056         "f32" => F32,
2057         "f64" => F64,
2058         "char" => Char,
2059         "bool" | "true" | "false" => Bool,
2060         "str" => Str,
2061         // See #80181 for why these don't have symbols associated.
2062         "slice" => Slice,
2063         "array" => Array,
2064         "tuple" => Tuple,
2065         "unit" => Unit,
2066         "pointer" | "*" | "*const" | "*mut" => RawPointer,
2067         "reference" | "&" | "&mut" => Reference,
2068         "fn" => Fn,
2069         "never" | "!" => Never,
2070         _ => return None,
2071     };
2072     debug!("resolved primitives {:?}", prim);
2073     Some(Res::Primitive(prim))
2074 }
2075
2076 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2077     let mut stripped_segments = vec![];
2078     let mut path = path_str.chars().peekable();
2079     let mut segment = Vec::new();
2080
2081     while let Some(chr) = path.next() {
2082         match chr {
2083             ':' => {
2084                 if path.next_if_eq(&':').is_some() {
2085                     let stripped_segment =
2086                         strip_generics_from_path_segment(mem::take(&mut segment))?;
2087                     if !stripped_segment.is_empty() {
2088                         stripped_segments.push(stripped_segment);
2089                     }
2090                 } else {
2091                     return Err(ResolutionFailure::MalformedGenerics(
2092                         MalformedGenerics::InvalidPathSeparator,
2093                     ));
2094                 }
2095             }
2096             '<' => {
2097                 segment.push(chr);
2098
2099                 match path.next() {
2100                     Some('<') => {
2101                         return Err(ResolutionFailure::MalformedGenerics(
2102                             MalformedGenerics::TooManyAngleBrackets,
2103                         ));
2104                     }
2105                     Some('>') => {
2106                         return Err(ResolutionFailure::MalformedGenerics(
2107                             MalformedGenerics::EmptyAngleBrackets,
2108                         ));
2109                     }
2110                     Some(chr) => {
2111                         segment.push(chr);
2112
2113                         while let Some(chr) = path.next_if(|c| *c != '>') {
2114                             segment.push(chr);
2115                         }
2116                     }
2117                     None => break,
2118                 }
2119             }
2120             _ => segment.push(chr),
2121         }
2122         trace!("raw segment: {:?}", segment);
2123     }
2124
2125     if !segment.is_empty() {
2126         let stripped_segment = strip_generics_from_path_segment(segment)?;
2127         if !stripped_segment.is_empty() {
2128             stripped_segments.push(stripped_segment);
2129         }
2130     }
2131
2132     debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2133
2134     let stripped_path = stripped_segments.join("::");
2135
2136     if !stripped_path.is_empty() {
2137         Ok(stripped_path)
2138     } else {
2139         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2140     }
2141 }
2142
2143 fn strip_generics_from_path_segment(
2144     segment: Vec<char>,
2145 ) -> Result<String, ResolutionFailure<'static>> {
2146     let mut stripped_segment = String::new();
2147     let mut param_depth = 0;
2148
2149     let mut latest_generics_chunk = String::new();
2150
2151     for c in segment {
2152         if c == '<' {
2153             param_depth += 1;
2154             latest_generics_chunk.clear();
2155         } else if c == '>' {
2156             param_depth -= 1;
2157             if latest_generics_chunk.contains(" as ") {
2158                 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2159                 // Give a helpful error message instead of completely ignoring the angle brackets.
2160                 return Err(ResolutionFailure::MalformedGenerics(
2161                     MalformedGenerics::HasFullyQualifiedSyntax,
2162                 ));
2163             }
2164         } else {
2165             if param_depth == 0 {
2166                 stripped_segment.push(c);
2167             } else {
2168                 latest_generics_chunk.push(c);
2169             }
2170         }
2171     }
2172
2173     if param_depth == 0 {
2174         Ok(stripped_segment)
2175     } else {
2176         // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2177         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))
2178     }
2179 }