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