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