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