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