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