Skip to main content

rustdoc/passes/
collect_intra_doc_links.rs

1//! Resolves intra-doc links ([RFC 1946]).
2//!
3//! [RFC 1946]: https://rust-lang.github.io/rfcs/1946-intra-rustdoc-links.html
4
5use std::borrow::Cow;
6use std::fmt::Display;
7use std::mem;
8use std::ops::Range;
9
10use rustc_ast::util::comments::may_have_doc_links;
11use rustc_attr_ir::{Attribute, AttributeKind, find_attr};
12use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
13use rustc_data_structures::intern::Interned;
14use rustc_errors::{Applicability, Diag, DiagMessage};
15use rustc_hir::def::Namespace::*;
16use rustc_hir::def::{DefKind, MacroKinds, Namespace, PerNS};
17use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE};
18use rustc_hir::{Mutability, Safety};
19use rustc_lint::Lint;
20use rustc_middle::ty;
21use rustc_middle::ty::{Ty, TyCtxt};
22use rustc_resolve::rustdoc::pulldown_cmark::LinkType;
23use rustc_resolve::rustdoc::{
24    DocStrings, MalformedGenerics, has_primitive_or_keyword_or_attribute_docs_hir,
25    prepare_to_doc_link_resolution, source_span_for_markdown_range, strip_generics_from_path,
26};
27use rustc_span::def_id::ModId;
28use rustc_span::edit_distance::find_best_match_for_name;
29use rustc_span::symbol::{Ident, Symbol, sym};
30use rustc_span::{BytePos, bug, span_bug};
31use rustc_structures::CrateType;
32use smallvec::{SmallVec, smallvec};
33use tracing::{debug, info, instrument, trace};
34
35use crate::clean::utils::find_nearest_parent_module;
36use crate::clean::{self, Crate, Item, ItemId, ItemLink, PrimitiveType, reexport_chain};
37use crate::core::DocContext;
38use crate::html::markdown::{MarkdownLink, MarkdownLinkRange, MarkdownLinks, markdown_links};
39use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
40use crate::visit::DocVisitor;
41
42pub(super) fn collect_intra_doc_links(
43    krate: Crate,
44    cx: &mut DocContext<'_>,
45) -> (Crate, LinkCollection) {
46    let mut collector = LinkCollector { cx, links: LinkCollection::default() };
47    collector.visit_crate(&krate);
48    (krate, collector.links)
49}
50
51pub(super) fn resolve_ambiguous_links(links: LinkCollection, cx: &mut DocContext<'_>) {
52    LinkCollector { cx, links }.resolve_ambiguities();
53}
54
55fn filter_assoc_items_by_name_and_namespace(
56    tcx: TyCtxt<'_>,
57    assoc_items_of: DefId,
58    ident: Ident,
59    ns: Namespace,
60) -> impl Iterator<Item = &ty::AssocItem> {
61    tcx.associated_items(assoc_items_of).filter_by_name_unhygienic(ident.name).filter(move |item| {
62        item.namespace() == ns && tcx.hygienic_eq(ident, item.ident(tcx), assoc_items_of)
63    })
64}
65
66#[derive(Copy, Clone, Debug, Hash, PartialEq)]
67pub(crate) enum Res {
68    Def(DefKind, DefId),
69    Primitive(PrimitiveType),
70}
71
72type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
73
74impl Res {
75    fn descr(self) -> &'static str {
76        match self {
77            Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
78            Res::Primitive(_) => "primitive type",
79        }
80    }
81
82    fn article(self) -> &'static str {
83        match self {
84            Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
85            Res::Primitive(_) => "a",
86        }
87    }
88
89    fn name(self, tcx: TyCtxt<'_>) -> Symbol {
90        match self {
91            Res::Def(_, id) => tcx.item_name(id),
92            Res::Primitive(prim) => prim.as_sym(),
93        }
94    }
95
96    fn def_id(self, tcx: TyCtxt<'_>) -> Option<DefId> {
97        match self {
98            Res::Def(_, id) => Some(id),
99            Res::Primitive(prim) => PrimitiveType::primitive_locations(tcx).get(&prim).copied(),
100        }
101    }
102
103    fn from_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Res {
104        Res::Def(tcx.def_kind(def_id), def_id)
105    }
106
107    /// Used for error reporting.
108    fn disambiguator_suggestion(self) -> Suggestion {
109        let kind = match self {
110            Res::Primitive(_) => return Suggestion::Prefix("prim"),
111            Res::Def(kind, _) => kind,
112        };
113
114        let prefix = match kind {
115            DefKind::Fn | DefKind::AssocFn => return Suggestion::Function,
116            // FIXME: handle macros with multiple kinds, and attribute/derive macros that aren't
117            // proc macros
118            DefKind::Macro(MacroKinds::ATTR) => "attribute",
119            DefKind::Macro(MacroKinds::DERIVE) => "derive",
120            DefKind::Macro(_) => return Suggestion::Macro,
121            DefKind::Struct => "struct",
122            DefKind::Enum => "enum",
123            DefKind::Trait => "trait",
124            DefKind::Union => "union",
125            DefKind::Mod => "mod",
126            DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
127                "const"
128            }
129            DefKind::Static { .. } => "static",
130            DefKind::Field => "field",
131            DefKind::Variant | DefKind::Ctor(..) => "variant",
132            DefKind::TyAlias => "tyalias",
133            // Now handle things that don't have a specific disambiguator
134            _ => match kind
135                .ns()
136                .expect("tried to calculate a disambiguator for a def without a namespace?")
137            {
138                Namespace::TypeNS => "type",
139                Namespace::ValueNS => "value",
140                Namespace::MacroNS => "macro",
141            },
142        };
143
144        Suggestion::Prefix(prefix)
145    }
146}
147
148impl TryFrom<ResolveRes> for Res {
149    type Error = ();
150
151    fn try_from(res: ResolveRes) -> Result<Self, ()> {
152        use rustc_hir::def::Res::*;
153        match res {
154            Def(kind, id) => Ok(Res::Def(kind, id)),
155            PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
156            // e.g. `#[derive]`
157            ToolMod | NonMacroAttr(..) | Err => Result::Err(()),
158            other => bug!("unrecognized res {other:?}"),
159        }
160    }
161}
162
163/// The link failed to resolve. [`resolution_failure`] should look to see if there's
164/// a more helpful error that can be given.
165#[derive(Debug)]
166struct UnresolvedPath<'a> {
167    /// Item on which the link is resolved, used for resolving `Self`.
168    item_id: DefId,
169    /// The scope the link was resolved in.
170    module_id: ModId,
171    /// If part of the link resolved, this has the `Res`.
172    ///
173    /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
174    partial_res: Option<Res>,
175    /// The remaining unresolved path segments.
176    ///
177    /// In `[std::io::Error::x]`, `x` would be unresolved.
178    unresolved: Cow<'a, str>,
179}
180
181#[derive(Debug)]
182enum ResolutionFailure<'a> {
183    /// This resolved, but with the wrong namespace.
184    WrongNamespace {
185        /// What the link resolved to.
186        res: Res,
187        /// The expected namespace for the resolution, determined from the link's disambiguator.
188        ///
189        /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
190        /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
191        expected_ns: Namespace,
192    },
193    NotResolved(UnresolvedPath<'a>),
194}
195
196#[derive(Clone, Debug, Hash, PartialEq, Eq)]
197pub(crate) enum UrlFragment {
198    Item(DefId),
199    /// A part of a page that isn't a rust item.
200    ///
201    /// Eg: `[Vector Examples](std::vec::Vec#examples)`
202    UserWritten(String),
203}
204
205#[derive(Clone, Debug, Hash, PartialEq, Eq)]
206pub(crate) struct ResolutionInfo {
207    item_id: DefId,
208    module_id: ModId,
209    dis: Option<Disambiguator>,
210    path_str: Box<str>,
211    extra_fragment: Option<String>,
212}
213
214#[derive(Clone)]
215pub(crate) struct DiagnosticInfo<'a> {
216    item: &'a Item,
217    dox: &'a str,
218    ori_link: &'a str,
219    link_range: MarkdownLinkRange,
220    link_kind: LinkType,
221}
222
223pub(crate) struct OwnedDiagnosticInfo {
224    item: Item,
225    dox: String,
226    ori_link: String,
227    link_range: MarkdownLinkRange,
228    link_kind: LinkType,
229}
230
231impl From<DiagnosticInfo<'_>> for OwnedDiagnosticInfo {
232    fn from(f: DiagnosticInfo<'_>) -> Self {
233        Self {
234            item: f.item.clone(),
235            dox: f.dox.to_string(),
236            ori_link: f.ori_link.to_string(),
237            link_range: f.link_range.clone(),
238            link_kind: f.link_kind,
239        }
240    }
241}
242
243impl OwnedDiagnosticInfo {
244    pub(crate) fn as_info(&self) -> DiagnosticInfo<'_> {
245        DiagnosticInfo {
246            item: &self.item,
247            ori_link: &self.ori_link,
248            dox: &self.dox,
249            link_range: self.link_range.clone(),
250            link_kind: self.link_kind,
251        }
252    }
253}
254
255struct LinkCollector<'a, 'tcx> {
256    cx: &'a mut DocContext<'tcx>,
257    links: LinkCollection,
258}
259
260#[derive(Default)]
261pub(super) struct LinkCollection {
262    /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
263    /// The link will be `None` if it could not be resolved (i.e. the error was cached).
264    visited: FxHashMap<ResolutionInfo, Option<(Res, Option<UrlFragment>)>>,
265    /// According to `rustc_resolve`, these links are ambiguous.
266    ///
267    /// However, we cannot link to an item that has been stripped from the documentation. If all
268    /// but one of the "possibilities" are stripped, then there is no real ambiguity. To determine
269    /// if an ambiguity is real, we delay resolving them until after `Cache::populate`, then filter
270    /// every item that doesn't have a cached path.
271    ///
272    /// We could get correct results by simply delaying everything. This would have fewer happy
273    /// codepaths, but we want to distinguish different kinds of error conditions, and this is easy
274    /// to do by resolving links as soon as possible.
275    ambiguous: FxIndexMap<(ItemId, String), Vec<AmbiguousLinks>>,
276}
277
278pub(crate) struct AmbiguousLinks {
279    link_text: Box<str>,
280    diag_info: OwnedDiagnosticInfo,
281    resolved: Vec<(Res, Option<UrlFragment>)>,
282}
283
284impl<'tcx> LinkCollector<'_, 'tcx> {
285    /// Given a full link, parse it as an [enum struct variant].
286    ///
287    /// In particular, this will return an error whenever there aren't three
288    /// full path segments left in the link.
289    ///
290    /// [enum struct variant]: rustc_hir::VariantData::Struct
291    fn variant_field<'path>(
292        &self,
293        path_str: &'path str,
294        item_id: DefId,
295        module_id: ModId,
296    ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
297        let tcx = self.cx.tcx;
298        let no_res = || UnresolvedPath {
299            item_id,
300            module_id,
301            partial_res: None,
302            unresolved: path_str.into(),
303        };
304
305        debug!("looking for enum variant {path_str}");
306        let mut split = path_str.rsplitn(3, "::");
307        let variant_field_name = Symbol::intern(split.next().unwrap());
308        // We're not sure this is a variant at all, so use the full string.
309        // If there's no second component, the link looks like `[path]`.
310        // So there's no partial res and we should say the whole link failed to resolve.
311        let variant_name = Symbol::intern(split.next().ok_or_else(no_res)?);
312
313        // If there's no third component, we saw `[a::b]` before and it failed to resolve.
314        // So there's no partial res.
315        let path = split.next().ok_or_else(no_res)?;
316        let ty_res = self.resolve_path(path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
317
318        match ty_res {
319            Res::Def(DefKind::Enum | DefKind::TyAlias, did) => {
320                match tcx.type_of(did).instantiate_identity().skip_norm_wip().kind() {
321                    ty::Adt(def, _) if def.is_enum() => {
322                        if let Some(variant) =
323                            def.variants().iter().find(|v| v.name == variant_name)
324                            && let Some(field) =
325                                variant.fields.iter().find(|f| f.name == variant_field_name)
326                        {
327                            Ok((ty_res, field.did))
328                        } else {
329                            Err(UnresolvedPath {
330                                item_id,
331                                module_id,
332                                partial_res: Some(Res::Def(DefKind::Enum, def.did())),
333                                unresolved: variant_field_name.to_string().into(),
334                            })
335                        }
336                    }
337                    _ => Err(UnresolvedPath {
338                        item_id,
339                        module_id,
340                        partial_res: Some(Res::Def(DefKind::TyAlias, did)),
341                        unresolved: variant_name.to_string().into(),
342                    }),
343                }
344            }
345            _ => Err(UnresolvedPath {
346                item_id,
347                module_id,
348                partial_res: Some(ty_res),
349                unresolved: variant_name.to_string().into(),
350            }),
351        }
352    }
353
354    /// Convenience wrapper around `doc_link_resolutions`.
355    ///
356    /// This also handles resolving `true` and `false` as booleans.
357    /// NOTE: `doc_link_resolutions` knows only about paths, not about types.
358    /// Associated items will never be resolved by this function.
359    fn resolve_path(
360        &self,
361        path_str: &str,
362        ns: Namespace,
363        item_id: DefId,
364        module_id: ModId,
365    ) -> Option<Res> {
366        if let res @ Some(..) = resolve_self_ty(self.cx.tcx, path_str, ns, item_id) {
367            return res;
368        }
369
370        // Resolver doesn't know about true, false, and types that aren't paths (e.g. `()`).
371        let result = self
372            .cx
373            .tcx
374            .doc_link_resolutions(module_id)
375            .get(&(Symbol::intern(path_str), ns))
376            .copied()
377            // NOTE: do not remove this panic! Missing links should be recorded as `Res::Err`; if
378            // `doc_link_resolutions` is missing a `path_str`, that means that there are valid links
379            // that are being missed. To fix the ICE, change
380            // `rustc_resolve::rustdoc::attrs_to_preprocessed_links` to cache the link.
381            .unwrap_or_else(|| {
382                span_bug!(
383                    self.cx.tcx.def_span(item_id),
384                    "no resolution for {path_str:?} {ns:?} {module_id:?}",
385                )
386            })
387            .and_then(|res| res.try_into().ok())
388            .or_else(|| resolve_primitive(path_str, ns));
389        debug!("{path_str} resolved to {result:?} in namespace {ns:?}");
390        result
391    }
392
393    /// Resolves a string as a path within a particular namespace. Returns an
394    /// optional URL fragment in the case of variants and methods.
395    fn resolve<'path>(
396        &self,
397        path_str: &'path str,
398        ns: Namespace,
399        disambiguator: Option<Disambiguator>,
400        item_id: DefId,
401        module_id: ModId,
402    ) -> Result<Vec<(Res, Option<DefId>)>, UnresolvedPath<'path>> {
403        let tcx = self.cx.tcx;
404
405        if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
406            return Ok(match res {
407                Res::Def(
408                    DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Variant,
409                    def_id,
410                ) => {
411                    vec![(Res::from_def_id(self.cx.tcx, self.cx.tcx.parent(def_id)), Some(def_id))]
412                }
413                _ => vec![(res, None)],
414            });
415        } else if ns == MacroNS {
416            return Err(UnresolvedPath {
417                item_id,
418                module_id,
419                partial_res: None,
420                unresolved: path_str.into(),
421            });
422        }
423
424        // Try looking for methods and associated items.
425        // NB: `path_root` could be empty when resolving in the root namespace (e.g. `::std`).
426        let (path_root, item_str) = match path_str.rsplit_once("::") {
427            Some(res @ (_path_root, item_str)) if !item_str.is_empty() => res,
428            _ => {
429                // If there's no `::`, or the `::` is at the end (e.g. `String::`) it's not an
430                // associated item. So we can be sure that `rustc_resolve` was accurate when it
431                // said it wasn't resolved.
432                debug!("`::` missing or at end, assuming {path_str} was not in scope");
433                return Err(UnresolvedPath {
434                    item_id,
435                    module_id,
436                    partial_res: None,
437                    unresolved: path_str.into(),
438                });
439            }
440        };
441        let item_name = Symbol::intern(item_str);
442
443        // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
444        // links to primitives when `#[rustc_doc_primitive]` is present. It should give an ambiguity
445        // error instead and special case *only* modules with `#[rustc_doc_primitive]`, not all
446        // primitives.
447        match resolve_primitive(path_root, TypeNS)
448            .or_else(|| self.resolve_path(path_root, TypeNS, item_id, module_id))
449            .map(|ty_res| {
450                resolve_associated_item(tcx, ty_res, item_name, ns, disambiguator, module_id)
451                    .into_iter()
452                    .map(|(res, def_id)| (res, Some(def_id)))
453                    .collect::<Vec<_>>()
454            }) {
455            Some(r) if !r.is_empty() => Ok(r),
456            _ => {
457                if ns == Namespace::ValueNS {
458                    self.variant_field(path_str, item_id, module_id)
459                        .map(|(res, def_id)| vec![(res, Some(def_id))])
460                } else {
461                    Err(UnresolvedPath {
462                        item_id,
463                        module_id,
464                        partial_res: None,
465                        unresolved: path_root.into(),
466                    })
467                }
468            }
469        }
470    }
471}
472
473fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
474    assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
475}
476
477/// Given a primitive type, try to resolve an associated item.
478fn resolve_primitive_inherent_assoc_item<'tcx>(
479    tcx: TyCtxt<'tcx>,
480    prim_ty: PrimitiveType,
481    ns: Namespace,
482    item_ident: Ident,
483) -> Vec<(Res, DefId)> {
484    prim_ty
485        .impls(tcx)
486        .flat_map(|impl_| {
487            filter_assoc_items_by_name_and_namespace(tcx, impl_, item_ident, ns)
488                .map(|item| (Res::Primitive(prim_ty), item.def_id))
489        })
490        .collect::<Vec<_>>()
491}
492
493fn resolve_self_ty<'tcx>(
494    tcx: TyCtxt<'tcx>,
495    path_str: &str,
496    ns: Namespace,
497    item_id: DefId,
498) -> Option<Res> {
499    if ns != TypeNS || path_str != "Self" {
500        return None;
501    }
502
503    let self_id = match tcx.def_kind(item_id) {
504        def_kind @ (DefKind::AssocFn
505        | DefKind::AssocConst
506        | DefKind::AssocTy
507        | DefKind::Variant
508        | DefKind::Field) => {
509            let parent_def_id = tcx.parent(item_id);
510            if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant {
511                tcx.parent(parent_def_id)
512            } else {
513                parent_def_id
514            }
515        }
516        _ => item_id,
517    };
518
519    match tcx.def_kind(self_id) {
520        DefKind::Impl { .. } => {
521            ty_to_res(tcx, tcx.type_of(self_id).instantiate_identity().skip_norm_wip())
522        }
523        DefKind::Use => None,
524        def_kind => Some(Res::Def(def_kind, self_id)),
525    }
526}
527
528/// Convert a Ty to a Res, where possible.
529///
530/// This is used for resolving type aliases.
531fn ty_to_res<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Res> {
532    use PrimitiveType::*;
533    Some(match *ty.kind() {
534        ty::Bool => Res::Primitive(Bool),
535        ty::Char => Res::Primitive(Char),
536        ty::Int(ity) => Res::Primitive(ity.into()),
537        ty::Uint(uty) => Res::Primitive(uty.into()),
538        ty::Float(fty) => Res::Primitive(fty.into()),
539        ty::Str => Res::Primitive(Str),
540        ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
541        ty::Tuple(_) => Res::Primitive(Tuple),
542        ty::Pat(..) => Res::Primitive(Pat),
543        ty::Array(..) => Res::Primitive(Array),
544        ty::Slice(_) => Res::Primitive(Slice),
545        ty::RawPtr(_, _) => Res::Primitive(RawPointer),
546        ty::Ref(..) => Res::Primitive(Reference),
547        ty::FnDef(..) => panic!("type alias to a function definition"),
548        ty::FnPtr(..) => Res::Primitive(Fn),
549        ty::Never => Res::Primitive(Never),
550        ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _)
551        | ty::View(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _, _)
552        | ty::Foreign(did) => Res::from_def_id(tcx, did),
553        ty::Alias(_, ..)
554        | ty::Closure(..)
555        | ty::CoroutineClosure(..)
556        | ty::Coroutine(..)
557        | ty::CoroutineWitness(..)
558        | ty::Dynamic(..)
559        | ty::UnsafeBinder(_)
560        | ty::Param(_)
561        | ty::Bound(..)
562        | ty::Placeholder(_)
563        | ty::Infer(_)
564        | ty::Error(_) => return None,
565    })
566}
567
568/// Convert a PrimitiveType to a Ty, where possible.
569///
570/// This is used for resolving trait impls for primitives
571fn primitive_type_to_ty<'tcx>(tcx: TyCtxt<'tcx>, prim: PrimitiveType) -> Option<Ty<'tcx>> {
572    use PrimitiveType::*;
573
574    // FIXME: Only simple types are supported here, see if we can support
575    // other types such as Tuple, Array, Slice, etc.
576    // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
577    Some(match prim {
578        Bool => tcx.types.bool,
579        Str => tcx.types.str_,
580        Char => tcx.types.char,
581        Never => tcx.types.never,
582        I8 => tcx.types.i8,
583        I16 => tcx.types.i16,
584        I32 => tcx.types.i32,
585        I64 => tcx.types.i64,
586        I128 => tcx.types.i128,
587        Isize => tcx.types.isize,
588        F16 => tcx.types.f16,
589        F32 => tcx.types.f32,
590        F64 => tcx.types.f64,
591        F128 => tcx.types.f128,
592        U8 => tcx.types.u8,
593        U16 => tcx.types.u16,
594        U32 => tcx.types.u32,
595        U64 => tcx.types.u64,
596        U128 => tcx.types.u128,
597        Usize => tcx.types.usize,
598        _ => return None,
599    })
600}
601
602/// Resolve an associated item, returning its containing page's `Res`
603/// and the fragment targeting the associated item on its page.
604fn resolve_associated_item<'tcx>(
605    tcx: TyCtxt<'tcx>,
606    root_res: Res,
607    item_name: Symbol,
608    ns: Namespace,
609    disambiguator: Option<Disambiguator>,
610    module_id: ModId,
611) -> Vec<(Res, DefId)> {
612    let item_ident = Ident::with_dummy_span(item_name);
613
614    match root_res {
615        Res::Def(DefKind::TyAlias, alias_did) => {
616            // Resolve the link on the type the alias points to.
617            // FIXME: if the associated item is defined directly on the type alias,
618            // it will show up on its documentation page, we should link there instead.
619            let Some(aliased_res) =
620                ty_to_res(tcx, tcx.type_of(alias_did).instantiate_identity().skip_norm_wip())
621            else {
622                return vec![];
623            };
624            let aliased_items =
625                resolve_associated_item(tcx, aliased_res, item_name, ns, disambiguator, module_id);
626            aliased_items
627                .into_iter()
628                .map(|(res, assoc_did)| {
629                    if is_assoc_item_on_alias_page(tcx, assoc_did) {
630                        (root_res, assoc_did)
631                    } else {
632                        (res, assoc_did)
633                    }
634                })
635                .collect()
636        }
637        Res::Primitive(prim) => resolve_assoc_on_primitive(tcx, prim, ns, item_ident, module_id),
638        Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, did) => {
639            resolve_assoc_on_adt(tcx, did, item_ident, ns, disambiguator, module_id)
640        }
641        Res::Def(DefKind::ForeignTy, did) => {
642            resolve_assoc_on_simple_type(tcx, did, item_ident, ns, module_id)
643        }
644        Res::Def(DefKind::Trait, did) => filter_assoc_items_by_name_and_namespace(
645            tcx,
646            did,
647            Ident::with_dummy_span(item_name),
648            ns,
649        )
650        .map(|item| (root_res, item.def_id))
651        .collect::<Vec<_>>(),
652        _ => Vec::new(),
653    }
654}
655
656// FIXME: make this fully complete by also including ALL inherent impls
657// and trait impls BUT ONLY if on alias directly
658fn is_assoc_item_on_alias_page<'tcx>(tcx: TyCtxt<'tcx>, assoc_did: DefId) -> bool {
659    match tcx.def_kind(assoc_did) {
660        // Variants and fields always have docs on the alias page.
661        DefKind::Variant | DefKind::Field => true,
662        _ => false,
663    }
664}
665
666fn resolve_assoc_on_primitive<'tcx>(
667    tcx: TyCtxt<'tcx>,
668    prim: PrimitiveType,
669    ns: Namespace,
670    item_ident: Ident,
671    module_id: ModId,
672) -> Vec<(Res, DefId)> {
673    let root_res = Res::Primitive(prim);
674    let items = resolve_primitive_inherent_assoc_item(tcx, prim, ns, item_ident);
675    if !items.is_empty() {
676        items
677    // Inherent associated items take precedence over items that come from trait impls.
678    } else {
679        primitive_type_to_ty(tcx, prim)
680            .map(|ty| {
681                resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
682                    .iter()
683                    .map(|item| (root_res, item.def_id))
684                    .collect::<Vec<_>>()
685            })
686            .unwrap_or_default()
687    }
688}
689
690fn resolve_assoc_on_adt<'tcx>(
691    tcx: TyCtxt<'tcx>,
692    adt_def_id: DefId,
693    item_ident: Ident,
694    ns: Namespace,
695    disambiguator: Option<Disambiguator>,
696    module_id: ModId,
697) -> Vec<(Res, DefId)> {
698    debug!("looking for associated item named {item_ident} for item {adt_def_id:?}");
699    let root_res = Res::from_def_id(tcx, adt_def_id);
700    let adt_ty = tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
701    let adt_def = adt_ty.ty_adt_def().expect("must be ADT");
702    // Checks if item_name is a variant of the `SomeItem` enum
703    if ns == TypeNS && adt_def.is_enum() {
704        for variant in adt_def.variants() {
705            if variant.name == item_ident.name {
706                return vec![(root_res, variant.def_id)];
707            }
708        }
709    }
710
711    if let Some(Disambiguator::Kind(DefKind::Field)) = disambiguator
712        && (adt_def.is_struct() || adt_def.is_union())
713    {
714        return resolve_structfield(adt_def, item_ident.name)
715            .into_iter()
716            .map(|did| (root_res, did))
717            .collect();
718    }
719
720    let assoc_items = resolve_assoc_on_simple_type(tcx, adt_def_id, item_ident, ns, module_id);
721    if !assoc_items.is_empty() {
722        return assoc_items;
723    }
724
725    if ns == Namespace::ValueNS && (adt_def.is_struct() || adt_def.is_union()) {
726        return resolve_structfield(adt_def, item_ident.name)
727            .into_iter()
728            .map(|did| (root_res, did))
729            .collect();
730    }
731
732    vec![]
733}
734
735/// "Simple" i.e. an ADT, foreign type, etc. -- not a type alias, primitive type, or other trickier type.
736fn resolve_assoc_on_simple_type<'tcx>(
737    tcx: TyCtxt<'tcx>,
738    ty_def_id: DefId,
739    item_ident: Ident,
740    ns: Namespace,
741    module_id: ModId,
742) -> Vec<(Res, DefId)> {
743    let root_res = Res::from_def_id(tcx, ty_def_id);
744    // Checks if item_name belongs to `impl SomeItem`
745    let inherent_assoc_items: Vec<_> = tcx
746        .inherent_impls(ty_def_id)
747        .iter()
748        .flat_map(|&imp| filter_assoc_items_by_name_and_namespace(tcx, imp, item_ident, ns))
749        .map(|item| (root_res, item.def_id))
750        .collect();
751    debug!("got inherent assoc items {inherent_assoc_items:?}");
752    if !inherent_assoc_items.is_empty() {
753        return inherent_assoc_items;
754    }
755
756    // Check if item_name belongs to `impl SomeTrait for SomeItem`
757    // FIXME(#74563): This gives precedence to `impl SomeItem`:
758    // Although having both would be ambiguous, use impl version for compatibility's sake.
759    // To handle that properly resolve() would have to support
760    // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
761    let ty = tcx.type_of(ty_def_id).instantiate_identity().skip_norm_wip();
762    let trait_assoc_items = resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
763        .into_iter()
764        .map(|item| (root_res, item.def_id))
765        .collect::<Vec<_>>();
766    debug!("got trait assoc items {trait_assoc_items:?}");
767    trait_assoc_items
768}
769
770fn resolve_structfield<'tcx>(adt_def: ty::AdtDef<'tcx>, item_name: Symbol) -> Option<DefId> {
771    debug!("looking for fields named {item_name} for {adt_def:?}");
772    adt_def
773        .non_enum_variant()
774        .fields
775        .iter()
776        .find(|field| field.name == item_name)
777        .map(|field| field.did)
778}
779
780/// Look to see if a resolved item has an associated item named `item_name`.
781///
782/// Given `[std::io::Error::source]`, where `source` is unresolved, this would
783/// find `std::error::Error::source` and return
784/// `<io::Error as error::Error>::source`.
785fn resolve_associated_trait_item<'tcx>(
786    ty: Ty<'tcx>,
787    module: ModId,
788    item_ident: Ident,
789    ns: Namespace,
790    tcx: TyCtxt<'tcx>,
791) -> Vec<ty::AssocItem> {
792    // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
793    // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
794    // meantime, just don't look for these blanket impls.
795
796    // Next consider explicit impls: `impl MyTrait for MyType`
797    // Give precedence to inherent impls.
798    let traits = trait_impls_for(tcx, ty, module);
799    debug!("considering traits {traits:?}");
800    let candidates = traits
801        .iter()
802        .flat_map(|&(impl_, trait_)| {
803            filter_assoc_items_by_name_and_namespace(tcx, trait_, item_ident, ns).map(
804                move |trait_assoc| {
805                    trait_assoc_to_impl_assoc_item(tcx, impl_, trait_assoc.def_id)
806                        .unwrap_or(*trait_assoc)
807                },
808            )
809        })
810        .collect::<Vec<_>>();
811    // FIXME(#74563): warn about ambiguity
812    debug!("the candidates were {candidates:?}");
813    candidates
814}
815
816/// Find the associated item in the impl `impl_id` that corresponds to the
817/// trait associated item `trait_assoc_id`.
818///
819/// This function returns `None` if no associated item was found in the impl.
820/// This can occur when the trait associated item has a default value that is
821/// not overridden in the impl.
822///
823/// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
824/// [`TyCtxt::associated_item()`] (with some helpful logging added).
825#[instrument(level = "debug", skip(tcx), ret)]
826fn trait_assoc_to_impl_assoc_item<'tcx>(
827    tcx: TyCtxt<'tcx>,
828    impl_id: DefId,
829    trait_assoc_id: DefId,
830) -> Option<ty::AssocItem> {
831    let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
832    debug!(?trait_to_impl_assoc_map);
833    let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
834    debug!(?impl_assoc_id);
835    Some(tcx.associated_item(impl_assoc_id))
836}
837
838/// Given a type, return all trait impls in scope in `module` for that type.
839/// Returns a set of pairs of `(impl_id, trait_id)`.
840///
841/// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
842/// So it is not stable to serialize cross-crate.
843#[instrument(level = "debug", skip(tcx))]
844fn trait_impls_for<'tcx>(
845    tcx: TyCtxt<'tcx>,
846    ty: Ty<'tcx>,
847    module: ModId,
848) -> FxIndexSet<(DefId, DefId)> {
849    let mut impls = FxIndexSet::default();
850
851    for &trait_ in tcx.doc_link_traits_in_scope(module) {
852        tcx.for_each_relevant_impl(trait_, ty, |impl_| {
853            let trait_ref = tcx.impl_trait_ref(impl_);
854            // Check if these are the same type.
855            let impl_type = trait_ref.skip_binder().self_ty();
856            trace!(
857                "comparing type {impl_type} with kind {kind:?} against type {ty:?}",
858                kind = impl_type.kind(),
859            );
860            // Fast path: if this is a primitive simple `==` will work
861            // NOTE: the `match` is necessary; see #92662.
862            // this allows us to ignore generics because the user input
863            // may not include the generic placeholders
864            // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
865            let saw_impl = impl_type == ty
866                || match (impl_type.kind(), ty.kind()) {
867                    (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
868                        debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
869                        impl_def.did() == ty_def.did()
870                    }
871                    _ => false,
872                };
873
874            if saw_impl {
875                impls.insert((impl_, trait_));
876            }
877        });
878    }
879
880    impls
881}
882
883/// Check for resolve collisions between a trait and its derive.
884///
885/// These are common and we should just resolve to the trait in that case.
886fn is_derive_trait_collision<T>(ns: &PerNS<Result<Vec<(Res, T)>, ResolutionFailure<'_>>>) -> bool {
887    if let (Ok(type_ns), Ok(macro_ns)) = (&ns.type_ns, &ns.macro_ns) {
888        type_ns.iter().any(|(res, _)| matches!(res, Res::Def(DefKind::Trait, _)))
889            && macro_ns.iter().any(|(res, _)| {
890                matches!(
891                    res,
892                    Res::Def(DefKind::Macro(kinds), _) if kinds.contains(MacroKinds::DERIVE)
893                )
894            })
895    } else {
896        false
897    }
898}
899
900impl DocVisitor<'_> for LinkCollector<'_, '_> {
901    fn visit_item(&mut self, item: &Item) {
902        self.resolve_links(item);
903        self.visit_item_recur(item)
904    }
905}
906
907enum PreprocessingError {
908    /// User error: `[std#x#y]` is not valid
909    MultipleAnchors,
910    Disambiguator(MarkdownLinkRange, String),
911    MalformedGenerics(MalformedGenerics, String),
912}
913
914impl PreprocessingError {
915    fn report(&self, cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
916        match self {
917            PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info),
918            PreprocessingError::Disambiguator(range, msg) => {
919                disambiguator_error(cx, diag_info, range.clone(), msg.clone())
920            }
921            PreprocessingError::MalformedGenerics(err, path_str) => {
922                report_malformed_generics(cx, diag_info, *err, path_str)
923            }
924        }
925    }
926}
927
928#[derive(Clone)]
929struct PreprocessingInfo {
930    path_str: Box<str>,
931    disambiguator: Option<Disambiguator>,
932    extra_fragment: Option<String>,
933    link_text: Box<str>,
934}
935
936// Not a typedef to avoid leaking several private structures from this module.
937pub(crate) struct PreprocessedMarkdownLink(
938    Result<PreprocessingInfo, PreprocessingError>,
939    MarkdownLink,
940);
941
942/// Returns:
943/// - `None` if the link should be ignored.
944/// - `Some(Err(_))` if the link should emit an error
945/// - `Some(Ok(_))` if the link is valid
946///
947/// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
948fn preprocess_link(
949    ori_link: &MarkdownLink,
950    dox: &str,
951) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
952    // IMPORTANT: To be kept in sync with the corresponding function in `rustc_resolve::rustdoc`.
953    // Namely, whenever this function returns a successful result for a given input,
954    // the rustc counterpart *MUST* return a link that's equal to `PreprocessingInfo.path_str`!
955
956    // certain link kinds cannot have their path be urls,
957    // so they should not be ignored, no matter how much they look like urls.
958    // e.g. [https://example.com/] is not a link to example.com.
959    let can_be_url = !matches!(
960        ori_link.kind,
961        LinkType::ShortcutUnknown | LinkType::CollapsedUnknown | LinkType::ReferenceUnknown
962    );
963
964    // [] is mostly likely not supposed to be a link
965    if ori_link.link.is_empty() {
966        return None;
967    }
968
969    // Bail early for real links.
970    if can_be_url && ori_link.link.contains('/') {
971        return None;
972    }
973
974    let stripped = ori_link.link.replace('`', "");
975    let mut parts = stripped.split('#');
976
977    let link = parts.next().unwrap();
978    let link = link.trim();
979    if link.is_empty() {
980        // This is an anchor to an element of the current page, nothing to do in here!
981        return None;
982    }
983    let extra_fragment = parts.next();
984    if parts.next().is_some() {
985        // A valid link can't have multiple #'s
986        return Some(Err(PreprocessingError::MultipleAnchors));
987    }
988
989    // Parse and strip the disambiguator from the link, if present.
990    let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
991        Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
992        Ok(None) => (None, link, link),
993        Err((err_msg, relative_range)) => {
994            // Only report error if we would not have ignored this link. See issue #83859.
995            if !(can_be_url && should_ignore_link_with_disambiguators(link)) {
996                let disambiguator_range = match range_between_backticks(&ori_link.range, dox) {
997                    MarkdownLinkRange::Destination(no_backticks_range) => {
998                        MarkdownLinkRange::Destination(
999                            (no_backticks_range.start + relative_range.start)
1000                                ..(no_backticks_range.start + relative_range.end),
1001                        )
1002                    }
1003                    mdlr @ MarkdownLinkRange::WholeLink(_) => mdlr,
1004                };
1005                return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1006            } else {
1007                return None;
1008            }
1009        }
1010    };
1011
1012    let is_shortcut_style = ori_link.kind == LinkType::ShortcutUnknown;
1013    // If there's no backticks, be lenient and revert to the old behavior.
1014    // This is to prevent churn by linting on stuff that isn't meant to be a link.
1015    // only shortcut links have simple enough syntax that they
1016    // are likely to be written accidentally, collapsed and reference links
1017    // need 4 metachars, and reference links will not usually use
1018    // backticks in the reference name.
1019    // therefore, only shortcut syntax gets the lenient behavior.
1020    //
1021    // here's a truth table for how link kinds that cannot be urls are handled:
1022    //
1023    // |-------------------------------------------------------|
1024    // |              |  is shortcut link  | not shortcut link |
1025    // |--------------|--------------------|-------------------|
1026    // | has backtick |    never ignore    |    never ignore   |
1027    // | no backtick  | ignore if url-like |    never ignore   |
1028    // |-------------------------------------------------------|
1029    let ignore_urllike = can_be_url || (is_shortcut_style && !ori_link.link.contains('`'));
1030    if ignore_urllike && should_ignore_link(path_str) {
1031        return None;
1032    }
1033    // If we have an intra-doc link starting with `!` (which isn't `[!]` because this is the never type), we ignore it
1034    // as it is never valid.
1035    //
1036    // The case is common enough because of cases like `#[doc = include_str!("../README.md")]` which often
1037    // uses GitHub-flavored Markdown (GFM) admonitions, such as `[!NOTE]`.
1038    if is_shortcut_style
1039        && let Some(suffix) = ori_link.link.strip_prefix('!')
1040        && !suffix.is_empty()
1041        && suffix.chars().all(|c| c.is_ascii_alphabetic())
1042    {
1043        return None;
1044    }
1045
1046    // Strip generics from the path.
1047    let path_str = match strip_generics_from_path(path_str) {
1048        Ok(path) => path,
1049        Err(err) => {
1050            debug!("link has malformed generics: {path_str}");
1051            return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
1052        }
1053    };
1054
1055    // Sanity check to make sure we don't have any angle brackets after stripping generics.
1056    assert!(!path_str.contains(['<', '>'].as_slice()));
1057
1058    // The link is not an intra-doc link if it still contains spaces after stripping generics.
1059    if path_str.contains(' ') {
1060        return None;
1061    }
1062
1063    Some(Ok(PreprocessingInfo {
1064        path_str,
1065        disambiguator,
1066        extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1067        link_text: Box::<str>::from(link_text),
1068    }))
1069}
1070
1071fn preprocessed_markdown_links(s: &str) -> MarkdownLinks<PreprocessedMarkdownLink> {
1072    markdown_links(s, |link| {
1073        preprocess_link(&link, s).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1074    })
1075}
1076
1077/// Compare lowercase labels so case differences are less likely to hide a typo,
1078/// but return the original candidate to preserve its spelling in suggestions.
1079fn find_best_match_for_reference_label(candidates: &[Symbol], lookup: Symbol) -> Option<Symbol> {
1080    let normalize = |name: Symbol| Symbol::intern(&name.as_str().to_lowercase());
1081
1082    let normalized_lookup = normalize(lookup);
1083    let normalized_candidates =
1084        candidates.iter().map(|&candidate| normalize(candidate)).collect::<Vec<_>>();
1085
1086    let best = find_best_match_for_name(&normalized_candidates, normalized_lookup, None)?;
1087
1088    let index = normalized_candidates.iter().position(|&candidate| candidate == best)?;
1089
1090    Some(candidates[index])
1091}
1092
1093/// Returns a source span for replacing a Markdown reference label.
1094/// Returns `None` when the source or replacement is unsuitable for a direct edit.
1095fn reference_label_suggestion_span(
1096    tcx: TyCtxt<'_>,
1097    diag_info: &DiagnosticInfo<'_>,
1098    replacement: &str,
1099) -> Option<rustc_span::Span> {
1100    let MarkdownLinkRange::Destination(label_range) = &diag_info.link_range else {
1101        return None;
1102    };
1103
1104    if replacement.chars().any(|ch| matches!(ch, '[' | ']' | '\\' | '\n' | '\r')) {
1105        return None;
1106    }
1107
1108    let (label_span, _) = source_span_for_markdown_range(
1109        tcx,
1110        diag_info.dox,
1111        label_range,
1112        &diag_info.item.attrs.doc_strings,
1113    )?;
1114
1115    let source_map = tcx.sess.source_map();
1116    if label_span.in_external_macro(source_map) || source_map.is_imported(label_span) {
1117        return None;
1118    }
1119
1120    let original_label = diag_info.dox.get(label_range.clone())?;
1121    let source = source_map.span_to_snippet(label_span).ok()?;
1122
1123    (source.as_str() == original_label).then_some(label_span)
1124}
1125
1126impl LinkCollector<'_, '_> {
1127    #[instrument(level = "debug", skip_all)]
1128    fn resolve_links(&mut self, item: &Item) {
1129        let tcx = self.cx.tcx;
1130        let document_private = self.cx.document_private();
1131        let effective_visibilities = tcx.effective_visibilities(());
1132        let should_skip_link_resolution = |item_id: DefId| {
1133            !document_private
1134                && item_id
1135                    .as_local()
1136                    .is_some_and(|local_def_id| !effective_visibilities.is_exported(local_def_id))
1137                && !has_primitive_or_keyword_or_attribute_docs_hir(&item.attrs.other_attrs)
1138        };
1139
1140        if let Some(def_id) = item.item_id.as_def_id()
1141            && should_skip_link_resolution(def_id)
1142        {
1143            // Skip link resolution for non-exported items.
1144            return;
1145        }
1146
1147        let mut try_insert_links_inner = |item_id, module_id, doc: &str| {
1148            let markdown_links = preprocessed_markdown_links(doc);
1149
1150            for md_link in &markdown_links.links {
1151                let link = self.resolve_link(
1152                    doc,
1153                    item,
1154                    item_id,
1155                    module_id,
1156                    md_link,
1157                    &markdown_links.reference_labels,
1158                );
1159
1160                if let Some(link) = link {
1161                    self.cx
1162                        .cache
1163                        .intra_doc_links
1164                        .entry(item.item_or_reexport_id())
1165                        .or_default()
1166                        .insert(link);
1167                }
1168            }
1169        };
1170
1171        let mut try_insert_links = |item_id, docs: &DocStrings| {
1172            if should_skip_link_resolution(item_id) {
1173                return;
1174            }
1175            match tcx.def_kind(item_id) {
1176                DefKind::Mod => {
1177                    if !docs.outer.is_empty() {
1178                        try_insert_links_inner(
1179                            item_id,
1180                            find_nearest_parent_module(tcx, item_id).unwrap(),
1181                            &docs.outer,
1182                        );
1183                    }
1184                    if !docs.inner.is_empty() {
1185                        try_insert_links_inner(item_id, ModId::new_unchecked(item_id), &docs.inner);
1186                    }
1187                }
1188                _ => {
1189                    // It's the same handling for non-module items.
1190                    let module_id = find_nearest_parent_module(tcx, item_id).unwrap();
1191                    try_insert_links_inner(
1192                        item_id,
1193                        module_id,
1194                        &format!("{}{}", docs.outer, docs.inner),
1195                    );
1196                }
1197            }
1198        };
1199
1200        // We want to resolve in the lexical scope of the documentation.
1201        // In the presence of re-exports, this is not the same as the module of the item.
1202        // Rather than merging all documentation into one, resolve it one attribute at a time
1203        // so we know which module it came from.
1204        for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
1205            if !may_have_doc_links(&doc.inner) && !may_have_doc_links(&doc.outer) {
1206                continue;
1207            }
1208
1209            debug!("combined_docs=outer: {} inner: {}", doc.outer, doc.inner);
1210            // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1211            // This is a degenerate case and it's not supported by rustdoc.
1212            let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
1213            try_insert_links(item_id, &doc)
1214        }
1215
1216        // Also resolve links in the note text of `#[deprecated]`.
1217        for attr in &item.attrs.other_attrs {
1218            let Attribute::Parsed(AttributeKind::Deprecated {
1219                span: depr_span,
1220                deprecation,
1221                is_inner,
1222            }) = attr
1223            else {
1224                continue;
1225            };
1226            let Some(note_sym) = deprecation.note else { continue };
1227            let note = note_sym.as_str();
1228
1229            if !may_have_doc_links(note) {
1230                continue;
1231            }
1232
1233            debug!("deprecated_note={note}");
1234            // When resolving an intra-doc link inside a deprecation note that is on an inlined
1235            // `use` statement, we need to use the `def_id` of the `use` statement, not the
1236            // inlined item.
1237            // <https://github.com/rust-lang/rust/pull/151120>
1238            let item_id = if let Some(inline_stmt_id) = item.inline_stmt_id {
1239                let target_def_id = item.item_id.expect_def_id();
1240                reexport_chain(tcx, inline_stmt_id, target_def_id)
1241                    .iter()
1242                    .flat_map(|reexport| reexport.id())
1243                    .find(|&reexport_def_id| {
1244                        find_attr!(
1245                            tcx,
1246                            reexport_def_id,
1247                            Deprecated { span, .. } if span == depr_span
1248                        )
1249                    })
1250                    .unwrap_or(target_def_id)
1251            } else {
1252                item.item_id.expect_def_id()
1253            };
1254            let attr = if *is_inner {
1255                DocStrings { outer: String::new(), inner: note.to_owned() }
1256            } else {
1257                DocStrings { outer: note.to_owned(), inner: String::new() }
1258            };
1259            try_insert_links(item_id, &attr);
1260        }
1261    }
1262
1263    pub(crate) fn save_link(&mut self, item_id: ItemId, link: ItemLink) {
1264        self.cx.cache.intra_doc_links.entry(item_id).or_default().insert(link);
1265    }
1266
1267    /// This is the entry point for resolving an intra-doc link.
1268    fn resolve_link(
1269        &mut self,
1270        dox: &str,
1271        item: &Item,
1272        item_id: DefId,
1273        module_id: ModId,
1274        PreprocessedMarkdownLink(pp_link, ori_link): &PreprocessedMarkdownLink,
1275        refdef_labels: &[String],
1276    ) -> Option<ItemLink> {
1277        trace!("considering link '{}'", ori_link.link);
1278
1279        let diag_info = DiagnosticInfo {
1280            item,
1281            dox,
1282            ori_link: &ori_link.link,
1283            link_range: ori_link.range.clone(),
1284            link_kind: ori_link.kind,
1285        };
1286        let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1287            pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1288        let disambiguator = *disambiguator;
1289        // A missing Markdown definition might indicate a misspelled label.
1290        // The link might still resolve to a Rust item, so don't diagnose it yet.
1291        let refdef_labels = match ori_link.kind {
1292            LinkType::ShortcutUnknown | LinkType::CollapsedUnknown | LinkType::ReferenceUnknown => {
1293                Some(refdef_labels)
1294            }
1295            _ => None,
1296        };
1297
1298        let mut resolved = self.resolve_with_disambiguator_cached(
1299            ResolutionInfo {
1300                item_id,
1301                module_id,
1302                dis: disambiguator,
1303                path_str: path_str.clone(),
1304                extra_fragment: extra_fragment.clone(),
1305            },
1306            diag_info.clone(), // this struct should really be Copy, but Range is not :(
1307            // For reference-style links we want to report only one error so unsuccessful
1308            // resolutions are cached, for other links we want to report an error every
1309            // time so they are not cached.
1310            matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1311            // Borrowed labels, available if Rust-item resolution fails.
1312            refdef_labels,
1313        )?;
1314
1315        if resolved.len() > 1 {
1316            let links = AmbiguousLinks {
1317                link_text: link_text.clone(),
1318                diag_info: diag_info.into(),
1319                resolved,
1320            };
1321
1322            self.links
1323                .ambiguous
1324                .entry((item.item_id, path_str.to_string()))
1325                .or_default()
1326                .push(links);
1327            None
1328        } else if let Some((res, fragment)) = resolved.pop() {
1329            self.compute_link(res, fragment, path_str, disambiguator, diag_info, link_text)
1330        } else {
1331            None
1332        }
1333    }
1334
1335    /// Returns `true` if a link could be generated from the given intra-doc information.
1336    ///
1337    /// This is a very light version of `format::href_with_jump_to_def_path_depth` since we're only interested
1338    /// about whether we can generate a link to an item or not.
1339    ///
1340    /// * If `original_did` is local, then we check if the item is reexported or public.
1341    /// * If `original_did` is not local, then we check if the crate it comes from is a direct
1342    ///   public dependency.
1343    fn validate_link(&self, original_did: DefId) -> bool {
1344        let tcx = self.cx.tcx;
1345        let def_kind = tcx.def_kind(original_did);
1346        let did = match def_kind {
1347            DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
1348                // documented on their parent's page
1349                tcx.parent(original_did)
1350            }
1351            // If this a constructor, we get the parent (either a struct or a variant) and then
1352            // generate the link for this item.
1353            DefKind::Ctor(..) => return self.validate_link(tcx.parent(original_did)),
1354            DefKind::ExternCrate => {
1355                // Link to the crate itself, not the `extern crate` item.
1356                if let Some(local_did) = original_did.as_local() {
1357                    tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
1358                } else {
1359                    original_did
1360                }
1361            }
1362            _ => original_did,
1363        };
1364
1365        let cache = &self.cx.cache;
1366        if !original_did.is_local()
1367            && !cache.effective_visibilities.is_directly_public(tcx, did)
1368            && !cache.document_private
1369            && !cache.primitive_locations.values().any(|&id| id == did)
1370        {
1371            return false;
1372        }
1373
1374        cache.paths.get(&did).is_some()
1375            || cache.external_paths.contains_key(&did)
1376            || !did.is_local()
1377    }
1378
1379    fn resolve_ambiguities(&mut self) {
1380        let mut ambiguous_links = mem::take(&mut self.links.ambiguous);
1381        for ((item_id, path_str), info_items) in ambiguous_links.iter_mut() {
1382            for info in info_items {
1383                info.resolved.retain(|(res, _)| match res {
1384                    Res::Def(_, def_id) => self.validate_link(*def_id),
1385                    // Primitive types are always valid.
1386                    Res::Primitive(_) => true,
1387                });
1388                let diag_info = info.diag_info.as_info();
1389                match info.resolved.len() {
1390                    1 => {
1391                        let (res, fragment) = info.resolved.pop().unwrap();
1392                        if let Some(link) = self.compute_link(
1393                            res,
1394                            fragment,
1395                            path_str,
1396                            None,
1397                            diag_info,
1398                            &info.link_text,
1399                        ) {
1400                            self.save_link(*item_id, link);
1401                        }
1402                    }
1403                    0 => {
1404                        report_diagnostic(
1405                            self.cx.tcx,
1406                            BROKEN_INTRA_DOC_LINKS,
1407                            format!("all items matching `{path_str}` are private or doc(hidden)"),
1408                            &diag_info,
1409                            |diag, sp, _| {
1410                                if let Some(sp) = sp {
1411                                    diag.span_label(sp, "unresolved link");
1412                                } else {
1413                                    diag.note("unresolved link");
1414                                }
1415                            },
1416                        );
1417                    }
1418                    _ => {
1419                        let candidates = info
1420                            .resolved
1421                            .iter()
1422                            .map(|(res, fragment)| {
1423                                let def_id = if let Some(UrlFragment::Item(def_id)) = fragment {
1424                                    Some(*def_id)
1425                                } else {
1426                                    None
1427                                };
1428                                (*res, def_id)
1429                            })
1430                            .collect::<Vec<_>>();
1431                        ambiguity_error(self.cx, &diag_info, path_str, &candidates, true);
1432                    }
1433                }
1434            }
1435        }
1436    }
1437
1438    fn compute_link(
1439        &mut self,
1440        mut res: Res,
1441        fragment: Option<UrlFragment>,
1442        path_str: &str,
1443        disambiguator: Option<Disambiguator>,
1444        diag_info: DiagnosticInfo<'_>,
1445        link_text: &Box<str>,
1446    ) -> Option<ItemLink> {
1447        // Check for a primitive which might conflict with a module
1448        // Report the ambiguity and require that the user specify which one they meant.
1449        // FIXME: could there ever be a primitive not in the type namespace?
1450        if matches!(
1451            disambiguator,
1452            None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1453        ) && !matches!(res, Res::Primitive(_))
1454            && let Some(prim) = resolve_primitive(path_str, TypeNS)
1455        {
1456            // `prim@char`
1457            if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1458                res = prim;
1459            } else {
1460                // `[char]` when a `char` module is in scope
1461                let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)];
1462                ambiguity_error(self.cx, &diag_info, path_str, candidates, true);
1463                return None;
1464            }
1465        }
1466
1467        match res {
1468            Res::Primitive(_) => {
1469                if let Some(UrlFragment::Item(id)) = fragment {
1470                    // We're actually resolving an associated item of a primitive, so we need to
1471                    // verify the disambiguator (if any) matches the type of the associated item.
1472                    // This case should really follow the same flow as the `Res::Def` branch below,
1473                    // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1474                    // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1475                    // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1476                    // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1477                    // for discussion on the matter.
1478                    let kind = self.cx.tcx.def_kind(id);
1479                    self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1480                } else {
1481                    match disambiguator {
1482                        Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1483                        Some(other) => {
1484                            self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1485                            return None;
1486                        }
1487                    }
1488                }
1489
1490                res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1491                    link: Box::<str>::from(diag_info.ori_link),
1492                    link_text: link_text.clone(),
1493                    page_id,
1494                    fragment,
1495                })
1496            }
1497            Res::Def(kind, id) => {
1498                let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1499                    (self.cx.tcx.def_kind(id), id)
1500                } else {
1501                    (kind, id)
1502                };
1503                self.verify_disambiguator(
1504                    path_str,
1505                    kind_for_dis,
1506                    id_for_dis,
1507                    disambiguator,
1508                    &diag_info,
1509                )?;
1510
1511                let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1512                Some(ItemLink {
1513                    link: Box::<str>::from(diag_info.ori_link),
1514                    link_text: link_text.clone(),
1515                    page_id,
1516                    fragment,
1517                })
1518            }
1519        }
1520    }
1521
1522    fn verify_disambiguator(
1523        &self,
1524        path_str: &str,
1525        kind: DefKind,
1526        id: DefId,
1527        disambiguator: Option<Disambiguator>,
1528        diag_info: &DiagnosticInfo<'_>,
1529    ) -> Option<()> {
1530        debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1531
1532        // Disallow e.g. linking to enums with `struct@`
1533        debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1534        match (kind, disambiguator) {
1535                | (
1536                    DefKind::Const
1537                    | DefKind::ConstParam
1538                    | DefKind::AssocConst
1539                    | DefKind::AnonConst,
1540                    Some(Disambiguator::Kind(DefKind::Const)),
1541                )
1542                // NOTE: this allows 'method' to mean both normal functions and associated functions
1543                // This can't cause ambiguity because both are in the same namespace.
1544                | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1545                // These are namespaces; allow anything in the namespace to match
1546                | (_, Some(Disambiguator::Namespace(_)))
1547                // If no disambiguator given, allow anything
1548                | (_, None)
1549                // All of these are valid, so do nothing
1550                => {}
1551                (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1552                (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1553                    self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1554                    return None;
1555                }
1556            }
1557
1558        // item can be non-local e.g. when using `#[rustc_doc_primitive = "pointer"]`
1559        if let Some(dst_id) = id.as_local()
1560            && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1561            && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1562            && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1563        {
1564            privacy_error(self.cx, diag_info, path_str);
1565        }
1566
1567        Some(())
1568    }
1569
1570    fn report_disambiguator_mismatch(
1571        &self,
1572        path_str: &str,
1573        specified: Disambiguator,
1574        resolved: Res,
1575        diag_info: &DiagnosticInfo<'_>,
1576    ) {
1577        // The resolved item did not match the disambiguator; give a better error than 'not found'
1578        let msg = format!("incompatible link kind for `{path_str}`");
1579        let callback = |diag: &mut Diag<'_>, sp: Option<rustc_span::Span>, link_range| {
1580            let note = format!(
1581                "this link resolved to {} {}, which is not {} {}",
1582                resolved.article(),
1583                resolved.descr(),
1584                specified.article(),
1585                specified.descr(),
1586            );
1587            if let Some(sp) = sp {
1588                diag.span_label(sp, note);
1589            } else {
1590                diag.note(note);
1591            }
1592            suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1593        };
1594        report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1595    }
1596
1597    fn report_rawptr_assoc_feature_gate(
1598        &self,
1599        dox: &str,
1600        ori_link: &MarkdownLinkRange,
1601        item: &Item,
1602    ) {
1603        let span = match source_span_for_markdown_range(
1604            self.cx.tcx,
1605            dox,
1606            ori_link.inner_range(),
1607            &item.attrs.doc_strings,
1608        ) {
1609            Some((sp, _)) => sp,
1610            None => item.attr_span(self.cx.tcx),
1611        };
1612        rustc_session::diagnostics::feature_err(
1613            self.cx.tcx.sess,
1614            sym::intra_doc_pointers,
1615            span,
1616            "linking to associated items of raw pointers is experimental",
1617        )
1618        .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1619        .emit();
1620    }
1621
1622    fn resolve_with_disambiguator_cached(
1623        &mut self,
1624        key: ResolutionInfo,
1625        diag: DiagnosticInfo<'_>,
1626        // If errors are cached then they are only reported on first occurrence
1627        // which we want in some cases but not in others.
1628        cache_errors: bool,
1629        refdef_labels: Option<&[String]>,
1630    ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1631        if let Some(res) = self.links.visited.get(&key)
1632            && (res.is_some() || cache_errors)
1633        {
1634            return res.clone().map(|r| vec![r]);
1635        }
1636
1637        let mut candidates = self.resolve_with_disambiguator(&key, diag.clone(), refdef_labels);
1638
1639        // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1640        // However I'm not sure how to check that across crates.
1641        if let Some(candidate) = candidates.first()
1642            && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1643            && key.path_str.contains("::")
1644        // We only want to check this if this is an associated item.
1645        {
1646            if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1647                self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1648                return None;
1649            } else {
1650                candidates = vec![*candidate];
1651            }
1652        }
1653
1654        // If there are multiple items with the same "kind" (for example, both "associated types")
1655        // and after removing duplicated kinds, only one remains, the `ambiguity_error` function
1656        // won't emit an error. So at this point, we can just take the first candidate as it was
1657        // the first retrieved and use it to generate the link.
1658        if let [candidate, _candidate2, ..] = *candidates
1659            && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1660        {
1661            candidates = vec![candidate];
1662        }
1663
1664        let mut out = Vec::with_capacity(candidates.len());
1665        for (res, def_id) in candidates {
1666            let fragment = match (&key.extra_fragment, def_id) {
1667                (Some(_), Some(def_id)) => {
1668                    report_anchor_conflict(self.cx, diag, def_id);
1669                    return None;
1670                }
1671                (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1672                (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1673                (None, None) => None,
1674            };
1675            out.push((res, fragment));
1676        }
1677        if let [r] = out.as_slice() {
1678            self.links.visited.insert(key, Some(r.clone()));
1679        } else if cache_errors {
1680            self.links.visited.insert(key, None);
1681        }
1682        Some(out)
1683    }
1684
1685    /// After parsing the disambiguator, resolve the main part of the link.
1686    fn resolve_with_disambiguator(
1687        &mut self,
1688        key: &ResolutionInfo,
1689        diag: DiagnosticInfo<'_>,
1690        refdef_labels: Option<&[String]>,
1691    ) -> Vec<(Res, Option<DefId>)> {
1692        let disambiguator = key.dis;
1693        let path_str = &key.path_str;
1694        let item_id = key.item_id;
1695        let module_id = key.module_id;
1696
1697        match disambiguator.map(Disambiguator::ns) {
1698            Some(expected_ns) => {
1699                match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1700                    Ok(candidates) => candidates,
1701                    Err(err) => {
1702                        // We only looked in one namespace. Try to give a better error if possible.
1703                        // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`.
1704                        // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach.
1705                        let mut err = ResolutionFailure::NotResolved(err);
1706                        for other_ns in [TypeNS, ValueNS, MacroNS] {
1707                            if other_ns != expected_ns
1708                                && let Ok(&[res, ..]) = self
1709                                    .resolve(path_str, other_ns, None, item_id, module_id)
1710                                    .as_deref()
1711                            {
1712                                err = ResolutionFailure::WrongNamespace {
1713                                    res: full_res(self.cx.tcx, res),
1714                                    expected_ns,
1715                                };
1716                                break;
1717                            }
1718                        }
1719                        resolution_failure(
1720                            self,
1721                            diag,
1722                            path_str,
1723                            disambiguator,
1724                            smallvec![err],
1725                            refdef_labels,
1726                        );
1727                        vec![]
1728                    }
1729                }
1730            }
1731            None => {
1732                // Try everything!
1733                let candidate = |ns| {
1734                    self.resolve(path_str, ns, None, item_id, module_id)
1735                        .map_err(ResolutionFailure::NotResolved)
1736                };
1737
1738                let candidates = PerNS {
1739                    macro_ns: candidate(MacroNS),
1740                    type_ns: candidate(TypeNS),
1741                    value_ns: candidate(ValueNS).and_then(|v_res| {
1742                        for (res, _) in v_res.iter() {
1743                            // Constructors are picked up in the type namespace.
1744                            if let Res::Def(DefKind::Ctor(..), _) = res {
1745                                return Err(ResolutionFailure::WrongNamespace {
1746                                    res: *res,
1747                                    expected_ns: TypeNS,
1748                                });
1749                            }
1750                        }
1751                        Ok(v_res)
1752                    }),
1753                };
1754
1755                let len = candidates
1756                    .iter()
1757                    .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1758
1759                if len == 0 {
1760                    resolution_failure(
1761                        self,
1762                        diag,
1763                        path_str,
1764                        disambiguator,
1765                        candidates.into_iter().filter_map(|res| res.err()).collect(),
1766                        refdef_labels,
1767                    );
1768                    vec![]
1769                } else if len == 1 {
1770                    candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1771                } else {
1772                    let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1773                    if len == 2 && has_derive_trait_collision {
1774                        candidates.type_ns.unwrap()
1775                    } else {
1776                        // If we're reporting an ambiguity, don't mention the namespaces that failed
1777                        let mut candidates = candidates.map(|candidate| candidate.ok());
1778                        // If there a collision between a trait and a derive, we ignore the derive.
1779                        if has_derive_trait_collision {
1780                            candidates.macro_ns = None;
1781                        }
1782                        candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1783                    }
1784                }
1785            }
1786        }
1787    }
1788}
1789
1790/// Get the section of a link between the backticks,
1791/// or the whole link if there aren't any backticks.
1792///
1793/// For example:
1794///
1795/// ```text
1796/// [`Foo`]
1797///   ^^^
1798/// ```
1799///
1800/// This function does nothing if `ori_link.range` is a `MarkdownLinkRange::WholeLink`.
1801fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1802    let range = match ori_link_range {
1803        mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1804        MarkdownLinkRange::Destination(inner) => inner.clone(),
1805    };
1806    let ori_link_text = &dox[range.clone()];
1807    let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1808    let before_second_backtick_group = ori_link_text
1809        .bytes()
1810        .skip(after_first_backtick_group)
1811        .position(|b| b == b'`')
1812        .unwrap_or(ori_link_text.len());
1813    MarkdownLinkRange::Destination(
1814        (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1815    )
1816}
1817
1818/// Returns true if we should ignore `link` due to it being unlikely
1819/// that it is an intra-doc link. `link` should still have disambiguators
1820/// if there were any.
1821///
1822/// The difference between this and [`should_ignore_link()`] is that this
1823/// check should only be used on links that still have disambiguators.
1824fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1825    link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1826}
1827
1828/// Returns true if we should ignore `path_str` due to it being unlikely
1829/// that it is an intra-doc link.
1830fn should_ignore_link(path_str: &str) -> bool {
1831    path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1832}
1833
1834#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1835/// Disambiguators for a link.
1836enum Disambiguator {
1837    /// `prim@`
1838    ///
1839    /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1840    Primitive,
1841    /// `struct@` or `f()`
1842    Kind(DefKind),
1843    /// `type@`
1844    Namespace(Namespace),
1845}
1846
1847impl Disambiguator {
1848    /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1849    ///
1850    /// This returns `Ok(Some(...))` if a disambiguator was found,
1851    /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1852    /// if there was a problem with the disambiguator.
1853    fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1854        use Disambiguator::{Kind, Namespace as NS, Primitive};
1855
1856        let suffixes = [
1857            // If you update this list, please also update the relevant rustdoc book section!
1858            ("!()", DefKind::Macro(MacroKinds::BANG)),
1859            ("!{}", DefKind::Macro(MacroKinds::BANG)),
1860            ("![]", DefKind::Macro(MacroKinds::BANG)),
1861            ("()", DefKind::Fn),
1862            ("!", DefKind::Macro(MacroKinds::BANG)),
1863        ];
1864
1865        if let Some(idx) = link.find('@') {
1866            let (prefix, rest) = link.split_at(idx);
1867            let d = match prefix {
1868                // If you update this list, please also update the relevant rustdoc book section!
1869                "struct" => Kind(DefKind::Struct),
1870                "enum" => Kind(DefKind::Enum),
1871                "trait" => Kind(DefKind::Trait),
1872                "union" => Kind(DefKind::Union),
1873                "module" | "mod" => Kind(DefKind::Mod),
1874                "const" | "constant" => Kind(DefKind::Const),
1875                "static" => Kind(DefKind::Static {
1876                    mutability: Mutability::Not,
1877                    nested: false,
1878                    safety: Safety::Safe,
1879                }),
1880                "function" | "fn" | "method" => Kind(DefKind::Fn),
1881                "derive" => Kind(DefKind::Macro(MacroKinds::DERIVE)),
1882                "field" => Kind(DefKind::Field),
1883                "variant" => Kind(DefKind::Variant),
1884                "type" => NS(Namespace::TypeNS),
1885                "value" => NS(Namespace::ValueNS),
1886                "macro" => NS(Namespace::MacroNS),
1887                "prim" | "primitive" => Primitive,
1888                "tyalias" | "typealias" => Kind(DefKind::TyAlias),
1889                _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1890            };
1891
1892            for (suffix, kind) in suffixes {
1893                if let Some(path_str) = rest.strip_suffix(suffix) {
1894                    if d.ns() != Kind(kind).ns() {
1895                        return Err((
1896                            format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1897                            0..idx,
1898                        ));
1899                    } else if path_str.len() > 1 {
1900                        // path_str != "@"
1901                        return Ok(Some((d, &path_str[1..], &rest[1..])));
1902                    }
1903                }
1904            }
1905
1906            Ok(Some((d, &rest[1..], &rest[1..])))
1907        } else {
1908            for (suffix, kind) in suffixes {
1909                // Avoid turning `!` or `()` into an empty string
1910                if let Some(path_str) = link.strip_suffix(suffix)
1911                    && !path_str.is_empty()
1912                {
1913                    return Ok(Some((Kind(kind), path_str, link)));
1914                }
1915            }
1916            Ok(None)
1917        }
1918    }
1919
1920    fn ns(self) -> Namespace {
1921        match self {
1922            Self::Namespace(n) => n,
1923            // for purposes of link resolution, fields are in the value namespace.
1924            Self::Kind(DefKind::Field) => ValueNS,
1925            Self::Kind(k) => {
1926                k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1927            }
1928            Self::Primitive => TypeNS,
1929        }
1930    }
1931
1932    fn article(self) -> &'static str {
1933        match self {
1934            Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1935            Self::Kind(k) => k.article(),
1936            Self::Primitive => "a",
1937        }
1938    }
1939
1940    fn descr(self) -> &'static str {
1941        match self {
1942            Self::Namespace(n) => n.descr(),
1943            // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1944            // printing "module" vs "crate" so using the wrong ID is not a huge problem
1945            Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1946            Self::Primitive => "builtin type",
1947        }
1948    }
1949}
1950
1951/// A suggestion to show in a diagnostic.
1952enum Suggestion {
1953    /// `struct@`
1954    Prefix(&'static str),
1955    /// `f()`
1956    Function,
1957    /// `m!`
1958    Macro,
1959}
1960
1961impl Suggestion {
1962    fn descr(&self) -> Cow<'static, str> {
1963        match self {
1964            Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1965            Self::Function => "add parentheses".into(),
1966            Self::Macro => "add an exclamation mark".into(),
1967        }
1968    }
1969
1970    fn as_help(&self, path_str: &str) -> String {
1971        // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1972        match self {
1973            Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1974            Self::Function => format!("{path_str}()"),
1975            Self::Macro => format!("{path_str}!"),
1976        }
1977    }
1978
1979    fn as_help_span(
1980        &self,
1981        ori_link: &str,
1982        sp: rustc_span::Span,
1983    ) -> Vec<(rustc_span::Span, String)> {
1984        let inner_sp = match ori_link.find('(') {
1985            Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1986                sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1987            }
1988            Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1989            None => sp,
1990        };
1991        let inner_sp = match ori_link.find('!') {
1992            Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1993                sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1994            }
1995            Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1996            None => inner_sp,
1997        };
1998        let inner_sp = match ori_link.find('@') {
1999            Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
2000                sp.with_hi(sp.lo() + BytePos((index - 1) as _))
2001            }
2002            Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
2003            None => inner_sp,
2004        };
2005        match self {
2006            Self::Prefix(prefix) => {
2007                // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
2008                let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
2009                if sp.hi() != inner_sp.hi() {
2010                    sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
2011                }
2012                sugg
2013            }
2014            Self::Function => {
2015                let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
2016                if sp.lo() != inner_sp.lo() {
2017                    sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
2018                }
2019                sugg
2020            }
2021            Self::Macro => {
2022                let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
2023                if sp.lo() != inner_sp.lo() {
2024                    sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
2025                }
2026                sugg
2027            }
2028        }
2029    }
2030}
2031
2032/// Reports a diagnostic for an intra-doc link.
2033///
2034/// If no link range is provided, or the source span of the link cannot be determined, the span of
2035/// the entire documentation block is used for the lint. If a range is provided but the span
2036/// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
2037///
2038/// The `decorate` callback is invoked in all cases to allow further customization of the
2039/// diagnostic before emission. If the span of the link was able to be determined, the second
2040/// parameter of the callback will contain it, and the primary span of the diagnostic will be set
2041/// to it.
2042fn report_diagnostic(
2043    tcx: TyCtxt<'_>,
2044    lint: &'static Lint,
2045    msg: impl Into<DiagMessage> + Display,
2046    DiagnosticInfo { item, dox, link_range, .. }: &DiagnosticInfo<'_>,
2047    decorate: impl FnOnce(&mut Diag<'_>, Option<rustc_span::Span>, MarkdownLinkRange),
2048) {
2049    let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
2050        // If non-local, no need to check anything.
2051        info!("ignoring warning from parent crate: {msg}");
2052        return;
2053    };
2054
2055    let sp = item.attr_span(tcx);
2056
2057    tcx.emit_node_span_lint(
2058        lint,
2059        hir_id,
2060        sp,
2061        rustc_errors::DiagDecorator(|lint| {
2062            lint.primary_message(msg);
2063
2064            let (span, link_range) = match link_range {
2065                MarkdownLinkRange::Destination(md_range) => {
2066                    let mut md_range = md_range.clone();
2067                    let sp = source_span_for_markdown_range(
2068                        tcx,
2069                        dox,
2070                        &md_range,
2071                        &item.attrs.doc_strings,
2072                    )
2073                    .map(|(mut sp, _)| {
2074                        while dox.as_bytes().get(md_range.start) == Some(&b' ')
2075                            || dox.as_bytes().get(md_range.start) == Some(&b'`')
2076                        {
2077                            md_range.start += 1;
2078                            sp = sp.with_lo(sp.lo() + BytePos(1));
2079                        }
2080                        while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
2081                            || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
2082                        {
2083                            md_range.end -= 1;
2084                            sp = sp.with_hi(sp.hi() - BytePos(1));
2085                        }
2086                        sp
2087                    });
2088                    (sp, MarkdownLinkRange::Destination(md_range))
2089                }
2090                MarkdownLinkRange::WholeLink(md_range) => (
2091                    source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
2092                        .map(|(sp, _)| sp),
2093                    link_range.clone(),
2094                ),
2095            };
2096
2097            if let Some(sp) = span {
2098                lint.span(sp);
2099            } else {
2100                // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
2101                //                       ^     ~~~~
2102                //                       |     link_range
2103                //                       last_new_line_offset
2104                let md_range = link_range.inner_range().clone();
2105                let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
2106                let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
2107
2108                // Print the line containing the `md_range` and manually mark it with '^'s.
2109                lint.note(format!(
2110                    "the link appears in this line:\n\n{line}\n\
2111                     {indicator: <before$}{indicator:^<found$}",
2112                    indicator = "",
2113                    before = md_range.start - last_new_line_offset,
2114                    found = md_range.len(),
2115                ));
2116            }
2117
2118            decorate(lint, span, link_range);
2119        }),
2120    );
2121}
2122
2123fn suggest_path_name_typo(
2124    collector: &LinkCollector<'_, '_>,
2125    diag: &mut Diag<'_>,
2126    span: Option<rustc_span::Span>,
2127    link_range: &MarkdownLinkRange,
2128    dox: &str,
2129    module: ModId,
2130    unresolved: &str,
2131    has_partial_res: bool,
2132    disambiguator: Option<Disambiguator>,
2133) -> bool {
2134    if unresolved.chars().count() <= 1 {
2135        // There are too many false positives for single character typos.
2136        return false;
2137    }
2138
2139    let tcx = collector.cx.tcx;
2140    let lookup = Symbol::intern(unresolved);
2141    let children = if let Some(local_module) = module.as_local() {
2142        tcx.module_children_local(local_module.to_local_def_id())
2143    } else {
2144        tcx.module_children(module.to_def_id())
2145    };
2146    let candidates = children
2147        .iter()
2148        .filter(|child| {
2149            disambiguator.is_none_or(|disambiguator| child.res.matches_ns(disambiguator.ns()))
2150        })
2151        .map(|child| child.ident.name)
2152        .filter(|&name| name != lookup)
2153        .collect::<Vec<_>>();
2154
2155    let Some(candidate) = find_best_match_for_name(&candidates, lookup, None) else {
2156        // No plausible correction was found.
2157        return false;
2158    };
2159
2160    let msg = format!("there's a similarly named item `{candidate}`");
2161    if let (Some(span), MarkdownLinkRange::Destination(range)) = (span, link_range) {
2162        let link = &dox[range.clone()];
2163        // A partial resolution means that the unresolved name follows a resolved parent path.
2164        let start = if has_partial_res { link.rfind(unresolved) } else { link.find(unresolved) };
2165        if let Some(start) = start {
2166            let mut suggestion = link.to_owned();
2167            suggestion.replace_range(start..start + unresolved.len(), candidate.as_str());
2168            diag.span_suggestion_verbose(span, msg, suggestion, Applicability::MaybeIncorrect);
2169
2170            // A replacement suggestion was emitted.
2171            return true;
2172        }
2173    }
2174
2175    // We found a candidate but could not construct a precise replacement.
2176    // Textual typo advice still counts as useful advice.
2177    diag.help(msg);
2178    true
2179}
2180
2181/// Reports a link that failed to resolve.
2182///
2183/// This also tries to resolve any intermediate path segments that weren't
2184/// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
2185/// `std::io::Error::x`, this will resolve `std::io::Error`.
2186fn resolution_failure(
2187    collector: &LinkCollector<'_, '_>,
2188    diag_info: DiagnosticInfo<'_>,
2189    path_str: &str,
2190    disambiguator: Option<Disambiguator>,
2191    kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
2192    refdef_labels: Option<&[String]>,
2193) {
2194    let tcx = collector.cx.tcx;
2195    report_diagnostic(
2196        tcx,
2197        BROKEN_INTRA_DOC_LINKS,
2198        format!("unresolved link to `{path_str}`"),
2199        &diag_info,
2200        |diag, sp, link_range| {
2201            let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
2202            let assoc_item_not_allowed = |res: Res| {
2203                let name = res.name(tcx);
2204                format!(
2205                    "`{name}` is {} {}, not a module or type, and cannot have associated items",
2206                    res.article(),
2207                    res.descr()
2208                )
2209            };
2210            // ignore duplicates
2211            let mut variants_seen =
2212                SmallVec::<[_; const { mem::variant_count::<ResolutionFailure<'_>>() }]>::new();
2213            for mut failure in kinds {
2214                let variant = mem::discriminant(&failure);
2215                if variants_seen.contains(&variant) {
2216                    continue;
2217                }
2218                variants_seen.push(variant);
2219
2220                if let ResolutionFailure::NotResolved(UnresolvedPath {
2221                    item_id,
2222                    module_id,
2223                    partial_res,
2224                    unresolved,
2225                }) = &mut failure
2226                {
2227                    use DefKind::*;
2228
2229                    let reference_candidate = refdef_labels.and_then(|labels| {
2230                        // Match the original link label, rather than the path produced by
2231                        // Rust-specific preprocessing.
2232                        let label = diag_info.ori_link;
2233
2234                        if labels.is_empty() || label.is_empty() {
2235                            return None;
2236                        }
2237
2238                        let lookup = Symbol::intern(label);
2239                        let candidates = labels
2240                            .iter()
2241                            .map(|reference_label| Symbol::intern(reference_label))
2242                            .collect::<Vec<_>>();
2243
2244                        find_best_match_for_reference_label(&candidates, lookup)
2245                    });
2246
2247                    // Both a replacement and plain help count as reference-label advice.
2248                    // Suppress the Rust-item typo and bracket-escaping fallbacks after either.
2249                    let refdef_label_was_suggested = reference_candidate.is_some_and(|candidate| {
2250                        let replacement = candidate.as_str();
2251                        let message =
2252                            format!("there is a similarly named reference label `{replacement}`");
2253
2254                        if let Some(span) =
2255                            reference_label_suggestion_span(tcx, &diag_info, replacement)
2256                        {
2257                            diag.span_suggestion_verbose(
2258                                span,
2259                                message,
2260                                replacement,
2261                                Applicability::MaybeIncorrect,
2262                            );
2263                        } else {
2264                            diag.help(message);
2265                        }
2266
2267                        true
2268                    });
2269
2270                    let item_id = *item_id;
2271                    let module_id = *module_id;
2272
2273                    // Check if _any_ parent of the path gets resolved.
2274                    // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
2275                    // Also check if `path_str` is an invalid path.
2276
2277                    // Examples of `path_str` that are invalid:
2278                    // - "std::::path", during splitting this would yield an empty segment
2279                    // - "std:::path", this would eventually yield "std:"
2280                    let mut path_is_invalid = false;
2281                    let is_invalid_segment =
2282                        |segment: &str| segment.is_empty() || segment.contains(':');
2283
2284                    let mut name = path_str;
2285                    'outer: loop {
2286                        // FIXME(jynelson): this might conflict with my `Self` fix in #76467
2287                        let Some((start, end)) = name.rsplit_once("::") else {
2288                            // `name` is now the first path segment, which didn't resolve.
2289                            // avoid bug that marked [Quux::Z] as missing Z, not Quux
2290                            if is_invalid_segment(name) {
2291                                path_is_invalid = true;
2292                                break;
2293                            }
2294                            if partial_res.is_none() {
2295                                *unresolved = name.into();
2296                                // If `partial_res` somehow had a value, we preserve the original `unresolved`.
2297                            }
2298                            break;
2299                        };
2300                        if is_invalid_segment(end) {
2301                            // If any segment is invalid, stop and say so, instead of saying
2302                            // "no item named ...", which would look nonsensical.
2303                            path_is_invalid = true;
2304                            break;
2305                        }
2306                        for ns in [TypeNS, ValueNS, MacroNS] {
2307                            if let Ok(v_res) =
2308                                collector.resolve(start, ns, None, item_id, module_id)
2309                            {
2310                                debug!("found partial_res={v_res:?}");
2311                                if let Some(&res) = v_res.first() {
2312                                    *partial_res = Some(full_res(tcx, res));
2313                                    *unresolved = end.into();
2314                                    break 'outer;
2315                                }
2316                            }
2317                        }
2318                        if start.is_empty() && partial_res.is_none() {
2319                            // `start` being empty means `path_str` was written like "::path::to::item".
2320                            // In this case, `end` is the first path segment that we should report.
2321                            *unresolved = end.into();
2322                            break;
2323                        }
2324                        name = start;
2325                    }
2326
2327                    let last_found_module = match *partial_res {
2328                        Some(Res::Def(DefKind::Mod, id)) => Some(ModId::new_unchecked(id)),
2329                        None => Some(module_id),
2330                        _ => None,
2331                    };
2332                    // See if this was a module: `[path]` or `[std::io::nope]`
2333                    if let Some(module) = last_found_module {
2334                        let note = if path_is_invalid {
2335                            "invalid path separator".into()
2336                        } else if partial_res.is_some() {
2337                            // Part of the link resolved; e.g. `std::io::nonexistent`
2338                            let module_name = tcx.item_name(module);
2339                            format!("no item named `{unresolved}` in module `{module_name}`")
2340                        } else {
2341                            // None of the link resolved; e.g. `Notimported`
2342                            format!("no item named `{unresolved}` in scope")
2343                        };
2344                        if let Some(span) = sp {
2345                            diag.span_label(span, note);
2346                        } else {
2347                            diag.note(note);
2348                        }
2349
2350                        // Prefer a concrete correction over generic advice about external links.
2351                        let suggested_item = !path_is_invalid
2352                            && !refdef_label_was_suggested
2353                            && suggest_path_name_typo(
2354                                collector,
2355                                diag,
2356                                sp,
2357                                &link_range,
2358                                diag_info.dox,
2359                                module,
2360                                unresolved,
2361                                partial_res.is_some(),
2362                                disambiguator,
2363                            );
2364
2365                        if !path_str.contains("::") {
2366                            if disambiguator.is_none_or(|d| d.ns() == MacroNS)
2367                                && collector
2368                                    .cx
2369                                    .tcx
2370                                    .resolutions(())
2371                                    .all_macro_rules
2372                                    .contains(&Symbol::intern(path_str))
2373                            {
2374                                diag.note(format!(
2375                                    "`macro_rules` named `{path_str}` exists in this crate, \
2376                                     but it is not in scope at this link's location"
2377                                ));
2378                            } else if !refdef_label_was_suggested {
2379                                // If the link has `::` in it, assume it was meant to be an
2380                                // intra-doc link. Otherwise, the `[]` might be unrelated.
2381                                diag.help(
2382                                    "to escape `[` and `]` characters, \
2383                                           add '\\' before them like `\\[` or `\\]`",
2384                                );
2385
2386                                // Use the original Markdown label in the reference-definition example.
2387                                let label = diag_info.ori_link;
2388
2389                                // Keep this as fallback advice for missing references, rather than
2390                                // competing with a typo correction or a more specific Rust-path error.
2391                                if !suggested_item
2392                                    && !path_is_invalid
2393                                    && partial_res.is_none()
2394                                    && disambiguator.is_none()
2395                                    && matches!(
2396                                        diag_info.link_kind,
2397                                        LinkType::ShortcutUnknown
2398                                            | LinkType::CollapsedUnknown
2399                                            | LinkType::ReferenceUnknown
2400                                    )
2401                                    && !label.contains(['[', ']', '\\', '\n', '\r'])
2402                                {
2403                                    // We cannot know the destination, so offer help rather than an edit.
2404                                    diag.help(format!(
2405                                        "if you intended to link to external documentation, \
2406                                         add a link reference definition: `[{label}]: https://...`"
2407                                    ));
2408                                }
2409                            }
2410                        }
2411
2412                        continue;
2413                    }
2414
2415                    // Otherwise, it must be an associated item or variant
2416                    let res = partial_res.expect("None case was handled by `last_found_module`");
2417                    let kind_did = match res {
2418                        Res::Def(kind, did) => Some((kind, did)),
2419                        Res::Primitive(_) => None,
2420                    };
2421                    let is_struct_variant = |did| {
2422                        if let ty::Adt(def, _) =
2423                            tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
2424                            && def.is_enum()
2425                            && let Some(variant) =
2426                                def.variants().iter().find(|v| v.name == res.name(tcx))
2427                        {
2428                            // ctor is `None` if variant is a struct
2429                            variant.ctor.is_none()
2430                        } else {
2431                            false
2432                        }
2433                    };
2434                    let path_description = if let Some((kind, did)) = kind_did {
2435                        match kind {
2436                            Mod | ForeignMod => "inner item",
2437                            Struct => "field or associated item",
2438                            Enum | Union => "variant or associated item",
2439                            Variant if is_struct_variant(did) => {
2440                                let variant = res.name(tcx);
2441                                let note = format!("variant `{variant}` has no such field");
2442                                if let Some(span) = sp {
2443                                    diag.span_label(span, note);
2444                                } else {
2445                                    diag.note(note);
2446                                }
2447                                return;
2448                            }
2449                            Variant
2450                            | Field
2451                            | Closure
2452                            | AssocTy
2453                            | AssocConst { .. }
2454                            | AssocFn
2455                            | Fn
2456                            | Macro(_)
2457                            | Const { .. }
2458                            | ConstParam
2459                            | ExternCrate
2460                            | Use
2461                            | LifetimeParam
2462                            | Ctor(_, _)
2463                            | AnonConst => {
2464                                let note = assoc_item_not_allowed(res);
2465                                if let Some(span) = sp {
2466                                    diag.span_label(span, note);
2467                                } else {
2468                                    diag.note(note);
2469                                }
2470                                return;
2471                            }
2472                            Trait
2473                            | TyAlias
2474                            | ForeignTy
2475                            | OpaqueTy
2476                            | TraitAlias
2477                            | TyParam
2478                            | Static { .. } => "associated item",
2479                            Impl { .. }
2480                            | GlobalAsm
2481                            | SyntheticCoroutineBody
2482                            | TestBinderConstraints => {
2483                                unreachable!("not a path")
2484                            }
2485                        }
2486                    } else {
2487                        "associated item"
2488                    };
2489                    let name = res.name(tcx);
2490                    let note = format!(
2491                        "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2492                        res = res.descr(),
2493                        disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2494                    );
2495                    if let Some(span) = sp {
2496                        diag.span_label(span, note);
2497                    } else {
2498                        diag.note(note);
2499                    }
2500
2501                    continue;
2502                }
2503                let note = match failure {
2504                    ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2505                    ResolutionFailure::WrongNamespace { res, expected_ns } => {
2506                        suggest_disambiguator(
2507                            res,
2508                            diag,
2509                            path_str,
2510                            link_range.clone(),
2511                            sp,
2512                            &diag_info,
2513                        );
2514
2515                        if let Some(disambiguator) = disambiguator
2516                            && !matches!(disambiguator, Disambiguator::Namespace(..))
2517                        {
2518                            format!(
2519                                "this link resolves to {}, which is not {} {}",
2520                                item(res),
2521                                disambiguator.article(),
2522                                disambiguator.descr()
2523                            )
2524                        } else {
2525                            format!(
2526                                "this link resolves to {}, which is not in the {} namespace",
2527                                item(res),
2528                                expected_ns.descr()
2529                            )
2530                        }
2531                    }
2532                };
2533                if let Some(span) = sp {
2534                    diag.span_label(span, note);
2535                } else {
2536                    diag.note(note);
2537                }
2538            }
2539        },
2540    );
2541}
2542
2543fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2544    let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2545    anchor_failure(cx, diag_info, msg, 1)
2546}
2547
2548fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2549    let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2550    let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2551    anchor_failure(cx, diag_info, msg, 0)
2552}
2553
2554/// Report an anchor failure.
2555fn anchor_failure(
2556    cx: &DocContext<'_>,
2557    diag_info: DiagnosticInfo<'_>,
2558    msg: String,
2559    anchor_idx: usize,
2560) {
2561    report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2562        if let Some(mut sp) = sp {
2563            if let Some((fragment_offset, _)) =
2564                diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2565            {
2566                sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2567            }
2568            diag.span_label(sp, "invalid anchor");
2569        }
2570    });
2571}
2572
2573/// Report an error in the link disambiguator.
2574fn disambiguator_error(
2575    cx: &DocContext<'_>,
2576    mut diag_info: DiagnosticInfo<'_>,
2577    disambiguator_range: MarkdownLinkRange,
2578    msg: impl Into<DiagMessage> + Display,
2579) {
2580    diag_info.link_range = disambiguator_range;
2581    report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2582        let msg = format!(
2583            "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2584            crate::DOC_RUST_LANG_ORG_VERSION
2585        );
2586        diag.note(msg);
2587    });
2588}
2589
2590fn report_malformed_generics(
2591    cx: &DocContext<'_>,
2592    diag_info: DiagnosticInfo<'_>,
2593    err: MalformedGenerics,
2594    path_str: &str,
2595) {
2596    report_diagnostic(
2597        cx.tcx,
2598        BROKEN_INTRA_DOC_LINKS,
2599        format!("unresolved link to `{path_str}`"),
2600        &diag_info,
2601        |diag, sp, _link_range| {
2602            let note = match err {
2603                MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2604                MalformedGenerics::MissingType => "missing type for generic parameters",
2605                MalformedGenerics::HasFullyQualifiedSyntax => {
2606                    diag.note(
2607                        "see https://github.com/rust-lang/rust/issues/74563 for more information",
2608                    );
2609                    "fully-qualified syntax is unsupported"
2610                }
2611                MalformedGenerics::InvalidPathSeparator => "invalid path separator",
2612                MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2613                MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2614            };
2615            if let Some(span) = sp {
2616                diag.span_label(span, note);
2617            } else {
2618                diag.note(note);
2619            }
2620        },
2621    );
2622}
2623
2624/// Report an ambiguity error, where there were multiple possible resolutions.
2625///
2626/// If all `candidates` have the same kind, it's not possible to disambiguate so in this case,
2627/// the function won't emit an error and will return `false`. Otherwise, it'll emit the error and
2628/// return `true`.
2629fn ambiguity_error(
2630    cx: &DocContext<'_>,
2631    diag_info: &DiagnosticInfo<'_>,
2632    path_str: &str,
2633    candidates: &[(Res, Option<DefId>)],
2634    emit_error: bool,
2635) -> bool {
2636    let mut descrs = FxHashSet::default();
2637    // proc macro can exist in multiple namespaces at once, so we need to compare `DefIds`
2638    //  to remove the candidate in the fn namespace.
2639    let mut possible_proc_macro_id = None;
2640    let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro];
2641    let mut kinds = candidates
2642        .iter()
2643        .map(|(res, def_id)| {
2644            let r =
2645                if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2646            if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2647                possible_proc_macro_id = Some(id);
2648            }
2649            r
2650        })
2651        .collect::<Vec<_>>();
2652    // In order to properly dedup proc macros, we have to do it in two passes:
2653    // 1. Completing the full traversal to find the possible duplicate in the macro namespace,
2654    // 2. Another full traversal to eliminate the candidate in the fn namespace.
2655    //
2656    // Thus, we have to do an iteration after collection is finished.
2657    //
2658    // As an optimization, we only deduplicate if we're in a proc-macro crate,
2659    // and only if we already found something that looks like a proc macro.
2660    if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2661        kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2662    }
2663
2664    kinds.retain(|res| descrs.insert(res.descr()));
2665
2666    if descrs.len() == 1 {
2667        // There is no way for users to disambiguate at this point, so better return the first
2668        // candidate and not show a warning.
2669        return false;
2670    } else if !emit_error {
2671        return true;
2672    }
2673
2674    let mut msg = format!("`{path_str}` is ");
2675    match kinds.as_slice() {
2676        [res1, res2] => {
2677            msg += &format!(
2678                "both {} {} and {} {}",
2679                res1.article(),
2680                res1.descr(),
2681                res2.article(),
2682                res2.descr()
2683            );
2684        }
2685        _ => {
2686            let mut kinds = kinds.iter().peekable();
2687            while let Some(res) = kinds.next() {
2688                if kinds.peek().is_some() {
2689                    msg += &format!("{} {}, ", res.article(), res.descr());
2690                } else {
2691                    msg += &format!("and {} {}", res.article(), res.descr());
2692                }
2693            }
2694        }
2695    }
2696
2697    report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2698        if let Some(sp) = sp {
2699            diag.span_label(sp, "ambiguous link");
2700        } else {
2701            diag.note("ambiguous link");
2702        }
2703
2704        for res in kinds {
2705            suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2706        }
2707    });
2708    true
2709}
2710
2711/// In case of an ambiguity or mismatched disambiguator, suggest the correct
2712/// disambiguator.
2713fn suggest_disambiguator(
2714    res: Res,
2715    diag: &mut Diag<'_>,
2716    path_str: &str,
2717    link_range: MarkdownLinkRange,
2718    sp: Option<rustc_span::Span>,
2719    diag_info: &DiagnosticInfo<'_>,
2720) {
2721    let suggestion = res.disambiguator_suggestion();
2722    let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2723
2724    let ori_link = match link_range {
2725        MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2726        MarkdownLinkRange::WholeLink(_) => None,
2727    };
2728
2729    if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2730        let mut spans = suggestion.as_help_span(ori_link, sp);
2731        if spans.len() > 1 {
2732            diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2733        } else {
2734            let (sp, suggestion_text) = spans.pop().unwrap();
2735            diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2736        }
2737    } else {
2738        diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2739    }
2740}
2741
2742/// Report a link from a public item to a private one.
2743fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2744    let sym;
2745    let item_name = match diag_info.item.name {
2746        Some(name) => {
2747            sym = name;
2748            sym.as_str()
2749        }
2750        None => "<unknown>",
2751    };
2752    let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2753
2754    report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2755        if let Some(sp) = sp {
2756            diag.span_label(sp, "this item is private");
2757        }
2758
2759        let note_msg = if cx.document_private() {
2760            "this link resolves only because you passed `--document-private-items`, but will break without"
2761        } else {
2762            "this link will resolve properly if you pass `--document-private-items`"
2763        };
2764        diag.note(note_msg);
2765    });
2766}
2767
2768/// Resolve a primitive type or value.
2769fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2770    if ns != TypeNS {
2771        return None;
2772    }
2773    use PrimitiveType::*;
2774    let prim = match path_str {
2775        "isize" => Isize,
2776        "i8" => I8,
2777        "i16" => I16,
2778        "i32" => I32,
2779        "i64" => I64,
2780        "i128" => I128,
2781        "usize" => Usize,
2782        "u8" => U8,
2783        "u16" => U16,
2784        "u32" => U32,
2785        "u64" => U64,
2786        "u128" => U128,
2787        "f16" => F16,
2788        "f32" => F32,
2789        "f64" => F64,
2790        "f128" => F128,
2791        "char" => Char,
2792        "bool" | "true" | "false" => Bool,
2793        "str" | "&str" => Str,
2794        // See #80181 for why these don't have symbols associated.
2795        "slice" => Slice,
2796        "array" => Array,
2797        "tuple" => Tuple,
2798        "unit" => Unit,
2799        "pointer" | "*const" | "*mut" => RawPointer,
2800        "reference" | "&" | "&mut" => Reference,
2801        "fn" => Fn,
2802        "never" | "!" => Never,
2803        _ => return None,
2804    };
2805    debug!("resolved primitives {prim:?}");
2806    Some(Res::Primitive(prim))
2807}