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