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