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