Skip to main content

rustdoc/passes/
collect_intra_doc_links.rs

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