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