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