rustdoc/passes/
collect_intra_doc_links.rs

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