Skip to main content

rustdoc/passes/
collect_intra_doc_links.rs

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