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