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        if !self.cx.document_private()
1071            && let Some(def_id) = item.item_id.as_def_id()
1072            && let Some(def_id) = def_id.as_local()
1073            && !tcx.effective_visibilities(()).is_exported(def_id)
1074            && !has_primitive_or_keyword_or_attribute_docs(&item.attrs.other_attrs)
1075        {
1076            // Skip link resolution for non-exported items.
1077            return;
1078        }
1079
1080        let mut insert_links = |item_id, doc: &str| {
1081            let module_id = match tcx.def_kind(item_id) {
1082                DefKind::Mod if item.inner_docs(tcx) => item_id,
1083                _ => find_nearest_parent_module(tcx, item_id).unwrap(),
1084            };
1085            for md_link in preprocessed_markdown_links(&doc) {
1086                let link = self.resolve_link(&doc, item, item_id, module_id, &md_link);
1087                if let Some(link) = link {
1088                    self.cx
1089                        .cache
1090                        .intra_doc_links
1091                        .entry(item.item_or_reexport_id())
1092                        .or_default()
1093                        .insert(link);
1094                }
1095            }
1096        };
1097
1098        // We want to resolve in the lexical scope of the documentation.
1099        // In the presence of re-exports, this is not the same as the module of the item.
1100        // Rather than merging all documentation into one, resolve it one attribute at a time
1101        // so we know which module it came from.
1102        for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
1103            if !may_have_doc_links(&doc) {
1104                continue;
1105            }
1106
1107            debug!("combined_docs={doc}");
1108            // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1109            // This is a degenerate case and it's not supported by rustdoc.
1110            let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
1111            insert_links(item_id, &doc)
1112        }
1113
1114        // Also resolve links in the note text of `#[deprecated]`.
1115        for attr in &item.attrs.other_attrs {
1116            let Attribute::Parsed(AttributeKind::Deprecated { span: depr_span, deprecation }) =
1117                attr
1118            else {
1119                continue;
1120            };
1121            let Some(note_sym) = deprecation.note else { continue };
1122            let note = note_sym.as_str();
1123
1124            if !may_have_doc_links(note) {
1125                continue;
1126            }
1127
1128            debug!("deprecated_note={note}");
1129            // When resolving an intra-doc link inside a deprecation note that is on an inlined
1130            // `use` statement, we need to use the `def_id` of the `use` statement, not the
1131            // inlined item.
1132            // <https://github.com/rust-lang/rust/pull/151120>
1133            let item_id = if let Some(inline_stmt_id) = item.inline_stmt_id
1134                && find_attr!(tcx, inline_stmt_id, Deprecated { span, ..} if span == depr_span)
1135            {
1136                inline_stmt_id.to_def_id()
1137            } else {
1138                item.item_id.expect_def_id()
1139            };
1140            insert_links(item_id, note)
1141        }
1142    }
1143
1144    pub(crate) fn save_link(&mut self, item_id: ItemId, link: ItemLink) {
1145        self.cx.cache.intra_doc_links.entry(item_id).or_default().insert(link);
1146    }
1147
1148    /// This is the entry point for resolving an intra-doc link.
1149    ///
1150    /// FIXME(jynelson): this is way too many arguments
1151    fn resolve_link(
1152        &mut self,
1153        dox: &str,
1154        item: &Item,
1155        item_id: DefId,
1156        module_id: DefId,
1157        PreprocessedMarkdownLink(pp_link, ori_link): &PreprocessedMarkdownLink,
1158    ) -> Option<ItemLink> {
1159        trace!("considering link '{}'", ori_link.link);
1160
1161        let diag_info = DiagnosticInfo {
1162            item,
1163            dox,
1164            ori_link: &ori_link.link,
1165            link_range: ori_link.range.clone(),
1166        };
1167        let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1168            pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1169        let disambiguator = *disambiguator;
1170
1171        let mut resolved = self.resolve_with_disambiguator_cached(
1172            ResolutionInfo {
1173                item_id,
1174                module_id,
1175                dis: disambiguator,
1176                path_str: path_str.clone(),
1177                extra_fragment: extra_fragment.clone(),
1178            },
1179            diag_info.clone(), // this struct should really be Copy, but Range is not :(
1180            // For reference-style links we want to report only one error so unsuccessful
1181            // resolutions are cached, for other links we want to report an error every
1182            // time so they are not cached.
1183            matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1184        )?;
1185
1186        if resolved.len() > 1 {
1187            let links = AmbiguousLinks {
1188                link_text: link_text.clone(),
1189                diag_info: diag_info.into(),
1190                resolved,
1191            };
1192
1193            self.ambiguous_links
1194                .entry((item.item_id, path_str.to_string()))
1195                .or_default()
1196                .push(links);
1197            None
1198        } else if let Some((res, fragment)) = resolved.pop() {
1199            self.compute_link(res, fragment, path_str, disambiguator, diag_info, link_text)
1200        } else {
1201            None
1202        }
1203    }
1204
1205    /// Returns `true` if a link could be generated from the given intra-doc information.
1206    ///
1207    /// This is a very light version of `format::href_with_root_path` since we're only interested
1208    /// about whether we can generate a link to an item or not.
1209    ///
1210    /// * If `original_did` is local, then we check if the item is reexported or public.
1211    /// * If `original_did` is not local, then we check if the crate it comes from is a direct
1212    ///   public dependency.
1213    fn validate_link(&self, original_did: DefId) -> bool {
1214        let tcx = self.cx.tcx;
1215        let def_kind = tcx.def_kind(original_did);
1216        let did = match def_kind {
1217            DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::Variant => {
1218                // documented on their parent's page
1219                tcx.parent(original_did)
1220            }
1221            // If this a constructor, we get the parent (either a struct or a variant) and then
1222            // generate the link for this item.
1223            DefKind::Ctor(..) => return self.validate_link(tcx.parent(original_did)),
1224            DefKind::ExternCrate => {
1225                // Link to the crate itself, not the `extern crate` item.
1226                if let Some(local_did) = original_did.as_local() {
1227                    tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
1228                } else {
1229                    original_did
1230                }
1231            }
1232            _ => original_did,
1233        };
1234
1235        let cache = &self.cx.cache;
1236        if !original_did.is_local()
1237            && !cache.effective_visibilities.is_directly_public(tcx, did)
1238            && !cache.document_private
1239            && !cache.primitive_locations.values().any(|&id| id == did)
1240        {
1241            return false;
1242        }
1243
1244        cache.paths.get(&did).is_some()
1245            || cache.external_paths.contains_key(&did)
1246            || !did.is_local()
1247    }
1248
1249    pub(crate) fn resolve_ambiguities(&mut self) {
1250        let mut ambiguous_links = mem::take(&mut self.ambiguous_links);
1251        for ((item_id, path_str), info_items) in ambiguous_links.iter_mut() {
1252            for info in info_items {
1253                info.resolved.retain(|(res, _)| match res {
1254                    Res::Def(_, def_id) => self.validate_link(*def_id),
1255                    // Primitive types are always valid.
1256                    Res::Primitive(_) => true,
1257                });
1258                let diag_info = info.diag_info.as_info();
1259                match info.resolved.len() {
1260                    1 => {
1261                        let (res, fragment) = info.resolved.pop().unwrap();
1262                        if let Some(link) = self.compute_link(
1263                            res,
1264                            fragment,
1265                            path_str,
1266                            None,
1267                            diag_info,
1268                            &info.link_text,
1269                        ) {
1270                            self.save_link(*item_id, link);
1271                        }
1272                    }
1273                    0 => {
1274                        report_diagnostic(
1275                            self.cx.tcx,
1276                            BROKEN_INTRA_DOC_LINKS,
1277                            format!("all items matching `{path_str}` are private or doc(hidden)"),
1278                            &diag_info,
1279                            |diag, sp, _| {
1280                                if let Some(sp) = sp {
1281                                    diag.span_label(sp, "unresolved link");
1282                                } else {
1283                                    diag.note("unresolved link");
1284                                }
1285                            },
1286                        );
1287                    }
1288                    _ => {
1289                        let candidates = info
1290                            .resolved
1291                            .iter()
1292                            .map(|(res, fragment)| {
1293                                let def_id = if let Some(UrlFragment::Item(def_id)) = fragment {
1294                                    Some(*def_id)
1295                                } else {
1296                                    None
1297                                };
1298                                (*res, def_id)
1299                            })
1300                            .collect::<Vec<_>>();
1301                        ambiguity_error(self.cx, &diag_info, path_str, &candidates, true);
1302                    }
1303                }
1304            }
1305        }
1306    }
1307
1308    fn compute_link(
1309        &mut self,
1310        mut res: Res,
1311        fragment: Option<UrlFragment>,
1312        path_str: &str,
1313        disambiguator: Option<Disambiguator>,
1314        diag_info: DiagnosticInfo<'_>,
1315        link_text: &Box<str>,
1316    ) -> Option<ItemLink> {
1317        // Check for a primitive which might conflict with a module
1318        // Report the ambiguity and require that the user specify which one they meant.
1319        // FIXME: could there ever be a primitive not in the type namespace?
1320        if matches!(
1321            disambiguator,
1322            None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1323        ) && !matches!(res, Res::Primitive(_))
1324            && let Some(prim) = resolve_primitive(path_str, TypeNS)
1325        {
1326            // `prim@char`
1327            if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1328                res = prim;
1329            } else {
1330                // `[char]` when a `char` module is in scope
1331                let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)];
1332                ambiguity_error(self.cx, &diag_info, path_str, candidates, true);
1333                return None;
1334            }
1335        }
1336
1337        match res {
1338            Res::Primitive(_) => {
1339                if let Some(UrlFragment::Item(id)) = fragment {
1340                    // We're actually resolving an associated item of a primitive, so we need to
1341                    // verify the disambiguator (if any) matches the type of the associated item.
1342                    // This case should really follow the same flow as the `Res::Def` branch below,
1343                    // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1344                    // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1345                    // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1346                    // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1347                    // for discussion on the matter.
1348                    let kind = self.cx.tcx.def_kind(id);
1349                    self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1350                } else {
1351                    match disambiguator {
1352                        Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1353                        Some(other) => {
1354                            self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1355                            return None;
1356                        }
1357                    }
1358                }
1359
1360                res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1361                    link: Box::<str>::from(diag_info.ori_link),
1362                    link_text: link_text.clone(),
1363                    page_id,
1364                    fragment,
1365                })
1366            }
1367            Res::Def(kind, id) => {
1368                let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1369                    (self.cx.tcx.def_kind(id), id)
1370                } else {
1371                    (kind, id)
1372                };
1373                self.verify_disambiguator(
1374                    path_str,
1375                    kind_for_dis,
1376                    id_for_dis,
1377                    disambiguator,
1378                    &diag_info,
1379                )?;
1380
1381                let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1382                Some(ItemLink {
1383                    link: Box::<str>::from(diag_info.ori_link),
1384                    link_text: link_text.clone(),
1385                    page_id,
1386                    fragment,
1387                })
1388            }
1389        }
1390    }
1391
1392    fn verify_disambiguator(
1393        &self,
1394        path_str: &str,
1395        kind: DefKind,
1396        id: DefId,
1397        disambiguator: Option<Disambiguator>,
1398        diag_info: &DiagnosticInfo<'_>,
1399    ) -> Option<()> {
1400        debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1401
1402        // Disallow e.g. linking to enums with `struct@`
1403        debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1404        match (kind, disambiguator) {
1405                | (
1406                    DefKind::Const { .. }
1407                    | DefKind::ConstParam
1408                    | DefKind::AssocConst { .. }
1409                    | DefKind::AnonConst,
1410                    Some(Disambiguator::Kind(DefKind::Const { .. })),
1411                )
1412                // NOTE: this allows 'method' to mean both normal functions and associated functions
1413                // This can't cause ambiguity because both are in the same namespace.
1414                | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1415                // These are namespaces; allow anything in the namespace to match
1416                | (_, Some(Disambiguator::Namespace(_)))
1417                // If no disambiguator given, allow anything
1418                | (_, None)
1419                // All of these are valid, so do nothing
1420                => {}
1421                (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1422                (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1423                    self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1424                    return None;
1425                }
1426            }
1427
1428        // item can be non-local e.g. when using `#[rustc_doc_primitive = "pointer"]`
1429        if let Some(dst_id) = id.as_local()
1430            && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1431            && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1432            && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1433        {
1434            privacy_error(self.cx, diag_info, path_str);
1435        }
1436
1437        Some(())
1438    }
1439
1440    fn report_disambiguator_mismatch(
1441        &self,
1442        path_str: &str,
1443        specified: Disambiguator,
1444        resolved: Res,
1445        diag_info: &DiagnosticInfo<'_>,
1446    ) {
1447        // The resolved item did not match the disambiguator; give a better error than 'not found'
1448        let msg = format!("incompatible link kind for `{path_str}`");
1449        let callback = |diag: &mut Diag<'_, ()>, sp: Option<rustc_span::Span>, link_range| {
1450            let note = format!(
1451                "this link resolved to {} {}, which is not {} {}",
1452                resolved.article(),
1453                resolved.descr(),
1454                specified.article(),
1455                specified.descr(),
1456            );
1457            if let Some(sp) = sp {
1458                diag.span_label(sp, note);
1459            } else {
1460                diag.note(note);
1461            }
1462            suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1463        };
1464        report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1465    }
1466
1467    fn report_rawptr_assoc_feature_gate(
1468        &self,
1469        dox: &str,
1470        ori_link: &MarkdownLinkRange,
1471        item: &Item,
1472    ) {
1473        let span = match source_span_for_markdown_range(
1474            self.cx.tcx,
1475            dox,
1476            ori_link.inner_range(),
1477            &item.attrs.doc_strings,
1478        ) {
1479            Some((sp, _)) => sp,
1480            None => item.attr_span(self.cx.tcx),
1481        };
1482        rustc_session::parse::feature_err(
1483            self.cx.tcx.sess,
1484            sym::intra_doc_pointers,
1485            span,
1486            "linking to associated items of raw pointers is experimental",
1487        )
1488        .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1489        .emit();
1490    }
1491
1492    fn resolve_with_disambiguator_cached(
1493        &mut self,
1494        key: ResolutionInfo,
1495        diag: DiagnosticInfo<'_>,
1496        // If errors are cached then they are only reported on first occurrence
1497        // which we want in some cases but not in others.
1498        cache_errors: bool,
1499    ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1500        if let Some(res) = self.visited_links.get(&key)
1501            && (res.is_some() || cache_errors)
1502        {
1503            return res.clone().map(|r| vec![r]);
1504        }
1505
1506        let mut candidates = self.resolve_with_disambiguator(&key, diag.clone());
1507
1508        // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1509        // However I'm not sure how to check that across crates.
1510        if let Some(candidate) = candidates.first()
1511            && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1512            && key.path_str.contains("::")
1513        // We only want to check this if this is an associated item.
1514        {
1515            if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1516                self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1517                return None;
1518            } else {
1519                candidates = vec![*candidate];
1520            }
1521        }
1522
1523        // If there are multiple items with the same "kind" (for example, both "associated types")
1524        // and after removing duplicated kinds, only one remains, the `ambiguity_error` function
1525        // won't emit an error. So at this point, we can just take the first candidate as it was
1526        // the first retrieved and use it to generate the link.
1527        if let [candidate, _candidate2, ..] = *candidates
1528            && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1529        {
1530            candidates = vec![candidate];
1531        }
1532
1533        let mut out = Vec::with_capacity(candidates.len());
1534        for (res, def_id) in candidates {
1535            let fragment = match (&key.extra_fragment, def_id) {
1536                (Some(_), Some(def_id)) => {
1537                    report_anchor_conflict(self.cx, diag, def_id);
1538                    return None;
1539                }
1540                (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1541                (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1542                (None, None) => None,
1543            };
1544            out.push((res, fragment));
1545        }
1546        if let [r] = out.as_slice() {
1547            self.visited_links.insert(key, Some(r.clone()));
1548        } else if cache_errors {
1549            self.visited_links.insert(key, None);
1550        }
1551        Some(out)
1552    }
1553
1554    /// After parsing the disambiguator, resolve the main part of the link.
1555    fn resolve_with_disambiguator(
1556        &mut self,
1557        key: &ResolutionInfo,
1558        diag: DiagnosticInfo<'_>,
1559    ) -> Vec<(Res, Option<DefId>)> {
1560        let disambiguator = key.dis;
1561        let path_str = &key.path_str;
1562        let item_id = key.item_id;
1563        let module_id = key.module_id;
1564
1565        match disambiguator.map(Disambiguator::ns) {
1566            Some(expected_ns) => {
1567                match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1568                    Ok(candidates) => candidates,
1569                    Err(err) => {
1570                        // We only looked in one namespace. Try to give a better error if possible.
1571                        // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`.
1572                        // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach.
1573                        let mut err = ResolutionFailure::NotResolved(err);
1574                        for other_ns in [TypeNS, ValueNS, MacroNS] {
1575                            if other_ns != expected_ns
1576                                && let Ok(&[res, ..]) = self
1577                                    .resolve(path_str, other_ns, None, item_id, module_id)
1578                                    .as_deref()
1579                            {
1580                                err = ResolutionFailure::WrongNamespace {
1581                                    res: full_res(self.cx.tcx, res),
1582                                    expected_ns,
1583                                };
1584                                break;
1585                            }
1586                        }
1587                        resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1588                        vec![]
1589                    }
1590                }
1591            }
1592            None => {
1593                // Try everything!
1594                let candidate = |ns| {
1595                    self.resolve(path_str, ns, None, item_id, module_id)
1596                        .map_err(ResolutionFailure::NotResolved)
1597                };
1598
1599                let candidates = PerNS {
1600                    macro_ns: candidate(MacroNS),
1601                    type_ns: candidate(TypeNS),
1602                    value_ns: candidate(ValueNS).and_then(|v_res| {
1603                        for (res, _) in v_res.iter() {
1604                            // Constructors are picked up in the type namespace.
1605                            if let Res::Def(DefKind::Ctor(..), _) = res {
1606                                return Err(ResolutionFailure::WrongNamespace {
1607                                    res: *res,
1608                                    expected_ns: TypeNS,
1609                                });
1610                            }
1611                        }
1612                        Ok(v_res)
1613                    }),
1614                };
1615
1616                let len = candidates
1617                    .iter()
1618                    .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1619
1620                if len == 0 {
1621                    resolution_failure(
1622                        self,
1623                        diag,
1624                        path_str,
1625                        disambiguator,
1626                        candidates.into_iter().filter_map(|res| res.err()).collect(),
1627                    );
1628                    vec![]
1629                } else if len == 1 {
1630                    candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1631                } else {
1632                    let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1633                    if len == 2 && has_derive_trait_collision {
1634                        candidates.type_ns.unwrap()
1635                    } else {
1636                        // If we're reporting an ambiguity, don't mention the namespaces that failed
1637                        let mut candidates = candidates.map(|candidate| candidate.ok());
1638                        // If there a collision between a trait and a derive, we ignore the derive.
1639                        if has_derive_trait_collision {
1640                            candidates.macro_ns = None;
1641                        }
1642                        candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1643                    }
1644                }
1645            }
1646        }
1647    }
1648}
1649
1650/// Get the section of a link between the backticks,
1651/// or the whole link if there aren't any backticks.
1652///
1653/// For example:
1654///
1655/// ```text
1656/// [`Foo`]
1657///   ^^^
1658/// ```
1659///
1660/// This function does nothing if `ori_link.range` is a `MarkdownLinkRange::WholeLink`.
1661fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1662    let range = match ori_link_range {
1663        mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1664        MarkdownLinkRange::Destination(inner) => inner.clone(),
1665    };
1666    let ori_link_text = &dox[range.clone()];
1667    let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1668    let before_second_backtick_group = ori_link_text
1669        .bytes()
1670        .skip(after_first_backtick_group)
1671        .position(|b| b == b'`')
1672        .unwrap_or(ori_link_text.len());
1673    MarkdownLinkRange::Destination(
1674        (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1675    )
1676}
1677
1678/// Returns true if we should ignore `link` due to it being unlikely
1679/// that it is an intra-doc link. `link` should still have disambiguators
1680/// if there were any.
1681///
1682/// The difference between this and [`should_ignore_link()`] is that this
1683/// check should only be used on links that still have disambiguators.
1684fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1685    link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1686}
1687
1688/// Returns true if we should ignore `path_str` due to it being unlikely
1689/// that it is an intra-doc link.
1690fn should_ignore_link(path_str: &str) -> bool {
1691    path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1692}
1693
1694#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1695/// Disambiguators for a link.
1696enum Disambiguator {
1697    /// `prim@`
1698    ///
1699    /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1700    Primitive,
1701    /// `struct@` or `f()`
1702    Kind(DefKind),
1703    /// `type@`
1704    Namespace(Namespace),
1705}
1706
1707impl Disambiguator {
1708    /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1709    ///
1710    /// This returns `Ok(Some(...))` if a disambiguator was found,
1711    /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1712    /// if there was a problem with the disambiguator.
1713    fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1714        use Disambiguator::{Kind, Namespace as NS, Primitive};
1715
1716        let suffixes = [
1717            // If you update this list, please also update the relevant rustdoc book section!
1718            ("!()", DefKind::Macro(MacroKinds::BANG)),
1719            ("!{}", DefKind::Macro(MacroKinds::BANG)),
1720            ("![]", DefKind::Macro(MacroKinds::BANG)),
1721            ("()", DefKind::Fn),
1722            ("!", DefKind::Macro(MacroKinds::BANG)),
1723        ];
1724
1725        if let Some(idx) = link.find('@') {
1726            let (prefix, rest) = link.split_at(idx);
1727            let d = match prefix {
1728                // If you update this list, please also update the relevant rustdoc book section!
1729                "struct" => Kind(DefKind::Struct),
1730                "enum" => Kind(DefKind::Enum),
1731                "trait" => Kind(DefKind::Trait),
1732                "union" => Kind(DefKind::Union),
1733                "module" | "mod" => Kind(DefKind::Mod),
1734                "const" | "constant" => Kind(DefKind::Const { is_type_const: false }),
1735                "static" => Kind(DefKind::Static {
1736                    mutability: Mutability::Not,
1737                    nested: false,
1738                    safety: Safety::Safe,
1739                }),
1740                "function" | "fn" | "method" => Kind(DefKind::Fn),
1741                "derive" => Kind(DefKind::Macro(MacroKinds::DERIVE)),
1742                "field" => Kind(DefKind::Field),
1743                "variant" => Kind(DefKind::Variant),
1744                "type" => NS(Namespace::TypeNS),
1745                "value" => NS(Namespace::ValueNS),
1746                "macro" => NS(Namespace::MacroNS),
1747                "prim" | "primitive" => Primitive,
1748                "tyalias" | "typealias" => Kind(DefKind::TyAlias),
1749                _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1750            };
1751
1752            for (suffix, kind) in suffixes {
1753                if let Some(path_str) = rest.strip_suffix(suffix) {
1754                    if d.ns() != Kind(kind).ns() {
1755                        return Err((
1756                            format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1757                            0..idx,
1758                        ));
1759                    } else if path_str.len() > 1 {
1760                        // path_str != "@"
1761                        return Ok(Some((d, &path_str[1..], &rest[1..])));
1762                    }
1763                }
1764            }
1765
1766            Ok(Some((d, &rest[1..], &rest[1..])))
1767        } else {
1768            for (suffix, kind) in suffixes {
1769                // Avoid turning `!` or `()` into an empty string
1770                if let Some(path_str) = link.strip_suffix(suffix)
1771                    && !path_str.is_empty()
1772                {
1773                    return Ok(Some((Kind(kind), path_str, link)));
1774                }
1775            }
1776            Ok(None)
1777        }
1778    }
1779
1780    fn ns(self) -> Namespace {
1781        match self {
1782            Self::Namespace(n) => n,
1783            // for purposes of link resolution, fields are in the value namespace.
1784            Self::Kind(DefKind::Field) => ValueNS,
1785            Self::Kind(k) => {
1786                k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1787            }
1788            Self::Primitive => TypeNS,
1789        }
1790    }
1791
1792    fn article(self) -> &'static str {
1793        match self {
1794            Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1795            Self::Kind(k) => k.article(),
1796            Self::Primitive => "a",
1797        }
1798    }
1799
1800    fn descr(self) -> &'static str {
1801        match self {
1802            Self::Namespace(n) => n.descr(),
1803            // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1804            // printing "module" vs "crate" so using the wrong ID is not a huge problem
1805            Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1806            Self::Primitive => "builtin type",
1807        }
1808    }
1809}
1810
1811/// A suggestion to show in a diagnostic.
1812enum Suggestion {
1813    /// `struct@`
1814    Prefix(&'static str),
1815    /// `f()`
1816    Function,
1817    /// `m!`
1818    Macro,
1819}
1820
1821impl Suggestion {
1822    fn descr(&self) -> Cow<'static, str> {
1823        match self {
1824            Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1825            Self::Function => "add parentheses".into(),
1826            Self::Macro => "add an exclamation mark".into(),
1827        }
1828    }
1829
1830    fn as_help(&self, path_str: &str) -> String {
1831        // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1832        match self {
1833            Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1834            Self::Function => format!("{path_str}()"),
1835            Self::Macro => format!("{path_str}!"),
1836        }
1837    }
1838
1839    fn as_help_span(
1840        &self,
1841        ori_link: &str,
1842        sp: rustc_span::Span,
1843    ) -> Vec<(rustc_span::Span, String)> {
1844        let inner_sp = match ori_link.find('(') {
1845            Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1846                sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1847            }
1848            Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1849            None => sp,
1850        };
1851        let inner_sp = match ori_link.find('!') {
1852            Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1853                sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1854            }
1855            Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1856            None => inner_sp,
1857        };
1858        let inner_sp = match ori_link.find('@') {
1859            Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1860                sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1861            }
1862            Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1863            None => inner_sp,
1864        };
1865        match self {
1866            Self::Prefix(prefix) => {
1867                // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1868                let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
1869                if sp.hi() != inner_sp.hi() {
1870                    sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1871                }
1872                sugg
1873            }
1874            Self::Function => {
1875                let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1876                if sp.lo() != inner_sp.lo() {
1877                    sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1878                }
1879                sugg
1880            }
1881            Self::Macro => {
1882                let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1883                if sp.lo() != inner_sp.lo() {
1884                    sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1885                }
1886                sugg
1887            }
1888        }
1889    }
1890}
1891
1892/// Reports a diagnostic for an intra-doc link.
1893///
1894/// If no link range is provided, or the source span of the link cannot be determined, the span of
1895/// the entire documentation block is used for the lint. If a range is provided but the span
1896/// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1897///
1898/// The `decorate` callback is invoked in all cases to allow further customization of the
1899/// diagnostic before emission. If the span of the link was able to be determined, the second
1900/// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1901/// to it.
1902fn report_diagnostic(
1903    tcx: TyCtxt<'_>,
1904    lint: &'static Lint,
1905    msg: impl Into<DiagMessage> + Display,
1906    DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1907    decorate: impl FnOnce(&mut Diag<'_, ()>, Option<rustc_span::Span>, MarkdownLinkRange),
1908) {
1909    let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
1910        // If non-local, no need to check anything.
1911        info!("ignoring warning from parent crate: {msg}");
1912        return;
1913    };
1914
1915    let sp = item.attr_span(tcx);
1916
1917    tcx.emit_node_span_lint(
1918        lint,
1919        hir_id,
1920        sp,
1921        rustc_errors::DiagDecorator(|lint| {
1922            lint.primary_message(msg);
1923
1924            let (span, link_range) = match link_range {
1925                MarkdownLinkRange::Destination(md_range) => {
1926                    let mut md_range = md_range.clone();
1927                    let sp = source_span_for_markdown_range(
1928                        tcx,
1929                        dox,
1930                        &md_range,
1931                        &item.attrs.doc_strings,
1932                    )
1933                    .map(|(mut sp, _)| {
1934                        while dox.as_bytes().get(md_range.start) == Some(&b' ')
1935                            || dox.as_bytes().get(md_range.start) == Some(&b'`')
1936                        {
1937                            md_range.start += 1;
1938                            sp = sp.with_lo(sp.lo() + BytePos(1));
1939                        }
1940                        while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
1941                            || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
1942                        {
1943                            md_range.end -= 1;
1944                            sp = sp.with_hi(sp.hi() - BytePos(1));
1945                        }
1946                        sp
1947                    });
1948                    (sp, MarkdownLinkRange::Destination(md_range))
1949                }
1950                MarkdownLinkRange::WholeLink(md_range) => (
1951                    source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
1952                        .map(|(sp, _)| sp),
1953                    link_range.clone(),
1954                ),
1955            };
1956
1957            if let Some(sp) = span {
1958                lint.span(sp);
1959            } else {
1960                // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1961                //                       ^     ~~~~
1962                //                       |     link_range
1963                //                       last_new_line_offset
1964                let md_range = link_range.inner_range().clone();
1965                let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
1966                let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1967
1968                // Print the line containing the `md_range` and manually mark it with '^'s.
1969                lint.note(format!(
1970                    "the link appears in this line:\n\n{line}\n\
1971                     {indicator: <before$}{indicator:^<found$}",
1972                    indicator = "",
1973                    before = md_range.start - last_new_line_offset,
1974                    found = md_range.len(),
1975                ));
1976            }
1977
1978            decorate(lint, span, link_range);
1979        }),
1980    );
1981}
1982
1983/// Reports a link that failed to resolve.
1984///
1985/// This also tries to resolve any intermediate path segments that weren't
1986/// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1987/// `std::io::Error::x`, this will resolve `std::io::Error`.
1988fn resolution_failure(
1989    collector: &LinkCollector<'_, '_>,
1990    diag_info: DiagnosticInfo<'_>,
1991    path_str: &str,
1992    disambiguator: Option<Disambiguator>,
1993    kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1994) {
1995    let tcx = collector.cx.tcx;
1996    report_diagnostic(
1997        tcx,
1998        BROKEN_INTRA_DOC_LINKS,
1999        format!("unresolved link to `{path_str}`"),
2000        &diag_info,
2001        |diag, sp, link_range| {
2002            let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
2003            let assoc_item_not_allowed = |res: Res| {
2004                let name = res.name(tcx);
2005                format!(
2006                    "`{name}` is {} {}, not a module or type, and cannot have associated items",
2007                    res.article(),
2008                    res.descr()
2009                )
2010            };
2011            // ignore duplicates
2012            let mut variants_seen = SmallVec::<[_; 3]>::new();
2013            for mut failure in kinds {
2014                let variant = mem::discriminant(&failure);
2015                if variants_seen.contains(&variant) {
2016                    continue;
2017                }
2018                variants_seen.push(variant);
2019
2020                if let ResolutionFailure::NotResolved(UnresolvedPath {
2021                    item_id,
2022                    module_id,
2023                    partial_res,
2024                    unresolved,
2025                }) = &mut failure
2026                {
2027                    use DefKind::*;
2028
2029                    let item_id = *item_id;
2030                    let module_id = *module_id;
2031
2032                    // Check if _any_ parent of the path gets resolved.
2033                    // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
2034                    let mut name = path_str;
2035                    'outer: loop {
2036                        // FIXME(jynelson): this might conflict with my `Self` fix in #76467
2037                        let Some((start, end)) = name.rsplit_once("::") else {
2038                            // avoid bug that marked [Quux::Z] as missing Z, not Quux
2039                            if partial_res.is_none() {
2040                                *unresolved = name.into();
2041                            }
2042                            break;
2043                        };
2044                        name = start;
2045                        for ns in [TypeNS, ValueNS, MacroNS] {
2046                            if let Ok(v_res) =
2047                                collector.resolve(start, ns, None, item_id, module_id)
2048                            {
2049                                debug!("found partial_res={v_res:?}");
2050                                if let Some(&res) = v_res.first() {
2051                                    *partial_res = Some(full_res(tcx, res));
2052                                    *unresolved = end.into();
2053                                    break 'outer;
2054                                }
2055                            }
2056                        }
2057                        *unresolved = end.into();
2058                    }
2059
2060                    let last_found_module = match *partial_res {
2061                        Some(Res::Def(DefKind::Mod, id)) => Some(id),
2062                        None => Some(module_id),
2063                        _ => None,
2064                    };
2065                    // See if this was a module: `[path]` or `[std::io::nope]`
2066                    if let Some(module) = last_found_module {
2067                        let note = if partial_res.is_some() {
2068                            // Part of the link resolved; e.g. `std::io::nonexistent`
2069                            let module_name = tcx.item_name(module);
2070                            format!("no item named `{unresolved}` in module `{module_name}`")
2071                        } else {
2072                            // None of the link resolved; e.g. `Notimported`
2073                            format!("no item named `{unresolved}` in scope")
2074                        };
2075                        if let Some(span) = sp {
2076                            diag.span_label(span, note);
2077                        } else {
2078                            diag.note(note);
2079                        }
2080
2081                        if !path_str.contains("::") {
2082                            if disambiguator.is_none_or(|d| d.ns() == MacroNS)
2083                                && collector
2084                                    .cx
2085                                    .tcx
2086                                    .resolutions(())
2087                                    .all_macro_rules
2088                                    .contains(&Symbol::intern(path_str))
2089                            {
2090                                diag.note(format!(
2091                                    "`macro_rules` named `{path_str}` exists in this crate, \
2092                                     but it is not in scope at this link's location"
2093                                ));
2094                            } else {
2095                                // If the link has `::` in it, assume it was meant to be an
2096                                // intra-doc link. Otherwise, the `[]` might be unrelated.
2097                                diag.help(
2098                                    "to escape `[` and `]` characters, \
2099                                           add '\\' before them like `\\[` or `\\]`",
2100                                );
2101                            }
2102                        }
2103
2104                        continue;
2105                    }
2106
2107                    // Otherwise, it must be an associated item or variant
2108                    let res = partial_res.expect("None case was handled by `last_found_module`");
2109                    let kind_did = match res {
2110                        Res::Def(kind, did) => Some((kind, did)),
2111                        Res::Primitive(_) => None,
2112                    };
2113                    let is_struct_variant = |did| {
2114                        if let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind()
2115                            && def.is_enum()
2116                            && let Some(variant) =
2117                                def.variants().iter().find(|v| v.name == res.name(tcx))
2118                        {
2119                            // ctor is `None` if variant is a struct
2120                            variant.ctor.is_none()
2121                        } else {
2122                            false
2123                        }
2124                    };
2125                    let path_description = if let Some((kind, did)) = kind_did {
2126                        match kind {
2127                            Mod | ForeignMod => "inner item",
2128                            Struct => "field or associated item",
2129                            Enum | Union => "variant or associated item",
2130                            Variant if is_struct_variant(did) => {
2131                                let variant = res.name(tcx);
2132                                let note = format!("variant `{variant}` has no such field");
2133                                if let Some(span) = sp {
2134                                    diag.span_label(span, note);
2135                                } else {
2136                                    diag.note(note);
2137                                }
2138                                return;
2139                            }
2140                            Variant
2141                            | Field
2142                            | Closure
2143                            | AssocTy
2144                            | AssocConst { .. }
2145                            | AssocFn
2146                            | Fn
2147                            | Macro(_)
2148                            | Const { .. }
2149                            | ConstParam
2150                            | ExternCrate
2151                            | Use
2152                            | LifetimeParam
2153                            | Ctor(_, _)
2154                            | AnonConst
2155                            | InlineConst => {
2156                                let note = assoc_item_not_allowed(res);
2157                                if let Some(span) = sp {
2158                                    diag.span_label(span, note);
2159                                } else {
2160                                    diag.note(note);
2161                                }
2162                                return;
2163                            }
2164                            Trait
2165                            | TyAlias
2166                            | ForeignTy
2167                            | OpaqueTy
2168                            | TraitAlias
2169                            | TyParam
2170                            | Static { .. } => "associated item",
2171                            Impl { .. } | GlobalAsm | SyntheticCoroutineBody => {
2172                                unreachable!("not a path")
2173                            }
2174                        }
2175                    } else {
2176                        "associated item"
2177                    };
2178                    let name = res.name(tcx);
2179                    let note = format!(
2180                        "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2181                        res = res.descr(),
2182                        disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2183                    );
2184                    if let Some(span) = sp {
2185                        diag.span_label(span, note);
2186                    } else {
2187                        diag.note(note);
2188                    }
2189
2190                    continue;
2191                }
2192                let note = match failure {
2193                    ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2194                    ResolutionFailure::WrongNamespace { res, expected_ns } => {
2195                        suggest_disambiguator(
2196                            res,
2197                            diag,
2198                            path_str,
2199                            link_range.clone(),
2200                            sp,
2201                            &diag_info,
2202                        );
2203
2204                        if let Some(disambiguator) = disambiguator
2205                            && !matches!(disambiguator, Disambiguator::Namespace(..))
2206                        {
2207                            format!(
2208                                "this link resolves to {}, which is not {} {}",
2209                                item(res),
2210                                disambiguator.article(),
2211                                disambiguator.descr()
2212                            )
2213                        } else {
2214                            format!(
2215                                "this link resolves to {}, which is not in the {} namespace",
2216                                item(res),
2217                                expected_ns.descr()
2218                            )
2219                        }
2220                    }
2221                };
2222                if let Some(span) = sp {
2223                    diag.span_label(span, note);
2224                } else {
2225                    diag.note(note);
2226                }
2227            }
2228        },
2229    );
2230}
2231
2232fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2233    let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2234    anchor_failure(cx, diag_info, msg, 1)
2235}
2236
2237fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2238    let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2239    let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2240    anchor_failure(cx, diag_info, msg, 0)
2241}
2242
2243/// Report an anchor failure.
2244fn anchor_failure(
2245    cx: &DocContext<'_>,
2246    diag_info: DiagnosticInfo<'_>,
2247    msg: String,
2248    anchor_idx: usize,
2249) {
2250    report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2251        if let Some(mut sp) = sp {
2252            if let Some((fragment_offset, _)) =
2253                diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2254            {
2255                sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2256            }
2257            diag.span_label(sp, "invalid anchor");
2258        }
2259    });
2260}
2261
2262/// Report an error in the link disambiguator.
2263fn disambiguator_error(
2264    cx: &DocContext<'_>,
2265    mut diag_info: DiagnosticInfo<'_>,
2266    disambiguator_range: MarkdownLinkRange,
2267    msg: impl Into<DiagMessage> + Display,
2268) {
2269    diag_info.link_range = disambiguator_range;
2270    report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2271        let msg = format!(
2272            "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2273            crate::DOC_RUST_LANG_ORG_VERSION
2274        );
2275        diag.note(msg);
2276    });
2277}
2278
2279fn report_malformed_generics(
2280    cx: &DocContext<'_>,
2281    diag_info: DiagnosticInfo<'_>,
2282    err: MalformedGenerics,
2283    path_str: &str,
2284) {
2285    report_diagnostic(
2286        cx.tcx,
2287        BROKEN_INTRA_DOC_LINKS,
2288        format!("unresolved link to `{path_str}`"),
2289        &diag_info,
2290        |diag, sp, _link_range| {
2291            let note = match err {
2292                MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2293                MalformedGenerics::MissingType => "missing type for generic parameters",
2294                MalformedGenerics::HasFullyQualifiedSyntax => {
2295                    diag.note(
2296                        "see https://github.com/rust-lang/rust/issues/74563 for more information",
2297                    );
2298                    "fully-qualified syntax is unsupported"
2299                }
2300                MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
2301                MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2302                MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2303            };
2304            if let Some(span) = sp {
2305                diag.span_label(span, note);
2306            } else {
2307                diag.note(note);
2308            }
2309        },
2310    );
2311}
2312
2313/// Report an ambiguity error, where there were multiple possible resolutions.
2314///
2315/// If all `candidates` have the same kind, it's not possible to disambiguate so in this case,
2316/// the function won't emit an error and will return `false`. Otherwise, it'll emit the error and
2317/// return `true`.
2318fn ambiguity_error(
2319    cx: &DocContext<'_>,
2320    diag_info: &DiagnosticInfo<'_>,
2321    path_str: &str,
2322    candidates: &[(Res, Option<DefId>)],
2323    emit_error: bool,
2324) -> bool {
2325    let mut descrs = FxHashSet::default();
2326    // proc macro can exist in multiple namespaces at once, so we need to compare `DefIds`
2327    //  to remove the candidate in the fn namespace.
2328    let mut possible_proc_macro_id = None;
2329    let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro];
2330    let mut kinds = candidates
2331        .iter()
2332        .map(|(res, def_id)| {
2333            let r =
2334                if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2335            if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2336                possible_proc_macro_id = Some(id);
2337            }
2338            r
2339        })
2340        .collect::<Vec<_>>();
2341    // In order to properly dedup proc macros, we have to do it in two passes:
2342    // 1. Completing the full traversal to find the possible duplicate in the macro namespace,
2343    // 2. Another full traversal to eliminate the candidate in the fn namespace.
2344    //
2345    // Thus, we have to do an iteration after collection is finished.
2346    //
2347    // As an optimization, we only deduplicate if we're in a proc-macro crate,
2348    // and only if we already found something that looks like a proc macro.
2349    if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2350        kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2351    }
2352
2353    kinds.retain(|res| descrs.insert(res.descr()));
2354
2355    if descrs.len() == 1 {
2356        // There is no way for users to disambiguate at this point, so better return the first
2357        // candidate and not show a warning.
2358        return false;
2359    } else if !emit_error {
2360        return true;
2361    }
2362
2363    let mut msg = format!("`{path_str}` is ");
2364    match kinds.as_slice() {
2365        [res1, res2] => {
2366            msg += &format!(
2367                "both {} {} and {} {}",
2368                res1.article(),
2369                res1.descr(),
2370                res2.article(),
2371                res2.descr()
2372            );
2373        }
2374        _ => {
2375            let mut kinds = kinds.iter().peekable();
2376            while let Some(res) = kinds.next() {
2377                if kinds.peek().is_some() {
2378                    msg += &format!("{} {}, ", res.article(), res.descr());
2379                } else {
2380                    msg += &format!("and {} {}", res.article(), res.descr());
2381                }
2382            }
2383        }
2384    }
2385
2386    report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2387        if let Some(sp) = sp {
2388            diag.span_label(sp, "ambiguous link");
2389        } else {
2390            diag.note("ambiguous link");
2391        }
2392
2393        for res in kinds {
2394            suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2395        }
2396    });
2397    true
2398}
2399
2400/// In case of an ambiguity or mismatched disambiguator, suggest the correct
2401/// disambiguator.
2402fn suggest_disambiguator(
2403    res: Res,
2404    diag: &mut Diag<'_, ()>,
2405    path_str: &str,
2406    link_range: MarkdownLinkRange,
2407    sp: Option<rustc_span::Span>,
2408    diag_info: &DiagnosticInfo<'_>,
2409) {
2410    let suggestion = res.disambiguator_suggestion();
2411    let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2412
2413    let ori_link = match link_range {
2414        MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2415        MarkdownLinkRange::WholeLink(_) => None,
2416    };
2417
2418    if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2419        let mut spans = suggestion.as_help_span(ori_link, sp);
2420        if spans.len() > 1 {
2421            diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2422        } else {
2423            let (sp, suggestion_text) = spans.pop().unwrap();
2424            diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2425        }
2426    } else {
2427        diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2428    }
2429}
2430
2431/// Report a link from a public item to a private one.
2432fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2433    let sym;
2434    let item_name = match diag_info.item.name {
2435        Some(name) => {
2436            sym = name;
2437            sym.as_str()
2438        }
2439        None => "<unknown>",
2440    };
2441    let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2442
2443    report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2444        if let Some(sp) = sp {
2445            diag.span_label(sp, "this item is private");
2446        }
2447
2448        let note_msg = if cx.document_private() {
2449            "this link resolves only because you passed `--document-private-items`, but will break without"
2450        } else {
2451            "this link will resolve properly if you pass `--document-private-items`"
2452        };
2453        diag.note(note_msg);
2454    });
2455}
2456
2457/// Resolve a primitive type or value.
2458fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2459    if ns != TypeNS {
2460        return None;
2461    }
2462    use PrimitiveType::*;
2463    let prim = match path_str {
2464        "isize" => Isize,
2465        "i8" => I8,
2466        "i16" => I16,
2467        "i32" => I32,
2468        "i64" => I64,
2469        "i128" => I128,
2470        "usize" => Usize,
2471        "u8" => U8,
2472        "u16" => U16,
2473        "u32" => U32,
2474        "u64" => U64,
2475        "u128" => U128,
2476        "f16" => F16,
2477        "f32" => F32,
2478        "f64" => F64,
2479        "f128" => F128,
2480        "char" => Char,
2481        "bool" | "true" | "false" => Bool,
2482        "str" | "&str" => Str,
2483        // See #80181 for why these don't have symbols associated.
2484        "slice" => Slice,
2485        "array" => Array,
2486        "tuple" => Tuple,
2487        "unit" => Unit,
2488        "pointer" | "*const" | "*mut" => RawPointer,
2489        "reference" | "&" | "&mut" => Reference,
2490        "fn" => Fn,
2491        "never" | "!" => Never,
2492        _ => return None,
2493    };
2494    debug!("resolved primitives {prim:?}");
2495    Some(Res::Primitive(prim))
2496}