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