1use std::borrow::Cow;
6use std::fmt::Display;
7use std::mem;
8use std::ops::Range;
9
10use rustc_ast::util::comments::may_have_doc_links;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
12use rustc_data_structures::intern::Interned;
13use rustc_errors::{Applicability, Diag, DiagMessage};
14use rustc_hir::attrs::AttributeKind;
15use rustc_hir::def::Namespace::*;
16use rustc_hir::def::{DefKind, MacroKinds, Namespace, PerNS};
17use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE};
18use rustc_hir::{Attribute, Mutability, Safety, find_attr};
19use rustc_middle::ty::{Ty, TyCtxt};
20use rustc_middle::{bug, span_bug, ty};
21use rustc_resolve::rustdoc::pulldown_cmark::LinkType;
22use rustc_resolve::rustdoc::{
23 MalformedGenerics, has_primitive_or_keyword_or_attribute_docs, prepare_to_doc_link_resolution,
24 source_span_for_markdown_range, strip_generics_from_path,
25};
26use rustc_session::config::CrateType;
27use rustc_session::lint::Lint;
28use rustc_span::BytePos;
29use rustc_span::symbol::{Ident, Symbol, sym};
30use smallvec::{SmallVec, smallvec};
31use tracing::{debug, info, instrument, trace};
32
33use crate::clean::utils::find_nearest_parent_module;
34use crate::clean::{self, Crate, Item, ItemId, ItemLink, PrimitiveType};
35use crate::core::DocContext;
36use crate::html::markdown::{MarkdownLink, MarkdownLinkRange, markdown_links};
37use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
38use crate::passes::Pass;
39use crate::visit::DocVisitor;
40
41pub(crate) const COLLECT_INTRA_DOC_LINKS: Pass =
42 Pass { name: "collect-intra-doc-links", run: None, description: "resolves intra-doc links" };
43
44pub(crate) fn collect_intra_doc_links<'a, 'tcx>(
45 krate: Crate,
46 cx: &'a mut DocContext<'tcx>,
47) -> (Crate, LinkCollector<'a, 'tcx>) {
48 let mut collector = LinkCollector {
49 cx,
50 visited_links: FxHashMap::default(),
51 ambiguous_links: FxIndexMap::default(),
52 };
53 collector.visit_crate(&krate);
54 (krate, collector)
55}
56
57fn filter_assoc_items_by_name_and_namespace(
58 tcx: TyCtxt<'_>,
59 assoc_items_of: DefId,
60 ident: Ident,
61 ns: Namespace,
62) -> impl Iterator<Item = &ty::AssocItem> {
63 tcx.associated_items(assoc_items_of).filter_by_name_unhygienic(ident.name).filter(move |item| {
64 item.namespace() == ns && tcx.hygienic_eq(ident, item.ident(tcx), assoc_items_of)
65 })
66}
67
68#[derive(Copy, Clone, Debug, Hash, PartialEq)]
69pub(crate) enum Res {
70 Def(DefKind, DefId),
71 Primitive(PrimitiveType),
72}
73
74type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
75
76impl Res {
77 fn descr(self) -> &'static str {
78 match self {
79 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
80 Res::Primitive(_) => "primitive type",
81 }
82 }
83
84 fn article(self) -> &'static str {
85 match self {
86 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
87 Res::Primitive(_) => "a",
88 }
89 }
90
91 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
92 match self {
93 Res::Def(_, id) => tcx.item_name(id),
94 Res::Primitive(prim) => prim.as_sym(),
95 }
96 }
97
98 fn def_id(self, tcx: TyCtxt<'_>) -> Option<DefId> {
99 match self {
100 Res::Def(_, id) => Some(id),
101 Res::Primitive(prim) => PrimitiveType::primitive_locations(tcx).get(&prim).copied(),
102 }
103 }
104
105 fn from_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Res {
106 Res::Def(tcx.def_kind(def_id), def_id)
107 }
108
109 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(MacroKinds::BANG) => return Suggestion::Macro,
121
122 DefKind::Macro(MacroKinds::DERIVE) => "derive",
123 DefKind::Struct => "struct",
124 DefKind::Enum => "enum",
125 DefKind::Trait => "trait",
126 DefKind::Union => "union",
127 DefKind::Mod => "mod",
128 DefKind::Const { .. }
129 | DefKind::ConstParam
130 | DefKind::AssocConst { .. }
131 | DefKind::AnonConst => "const",
132 DefKind::Static { .. } => "static",
133 DefKind::Field => "field",
134 DefKind::Variant | DefKind::Ctor(..) => "variant",
135 DefKind::TyAlias => "tyalias",
136 _ => match kind
138 .ns()
139 .expect("tried to calculate a disambiguator for a def without a namespace?")
140 {
141 Namespace::TypeNS => "type",
142 Namespace::ValueNS => "value",
143 Namespace::MacroNS => "macro",
144 },
145 };
146
147 Suggestion::Prefix(prefix)
148 }
149}
150
151impl TryFrom<ResolveRes> for Res {
152 type Error = ();
153
154 fn try_from(res: ResolveRes) -> Result<Self, ()> {
155 use rustc_hir::def::Res::*;
156 match res {
157 Def(kind, id) => Ok(Res::Def(kind, id)),
158 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
159 ToolMod | NonMacroAttr(..) | Err => Result::Err(()),
161 other => bug!("unrecognized res {other:?}"),
162 }
163 }
164}
165
166#[derive(Debug)]
169struct UnresolvedPath<'a> {
170 item_id: DefId,
172 module_id: DefId,
174 partial_res: Option<Res>,
178 unresolved: Cow<'a, str>,
182}
183
184#[derive(Debug)]
185enum ResolutionFailure<'a> {
186 WrongNamespace {
188 res: Res,
190 expected_ns: Namespace,
195 },
196 NotResolved(UnresolvedPath<'a>),
197}
198
199#[derive(Clone, Debug, Hash, PartialEq, Eq)]
200pub(crate) enum UrlFragment {
201 Item(DefId),
202 UserWritten(String),
206}
207
208#[derive(Clone, Debug, Hash, PartialEq, Eq)]
209pub(crate) struct ResolutionInfo {
210 item_id: DefId,
211 module_id: DefId,
212 dis: Option<Disambiguator>,
213 path_str: Box<str>,
214 extra_fragment: Option<String>,
215}
216
217#[derive(Clone)]
218pub(crate) struct DiagnosticInfo<'a> {
219 item: &'a Item,
220 dox: &'a str,
221 ori_link: &'a str,
222 link_range: MarkdownLinkRange,
223}
224
225pub(crate) struct OwnedDiagnosticInfo {
226 item: Item,
227 dox: String,
228 ori_link: String,
229 link_range: MarkdownLinkRange,
230}
231
232impl From<DiagnosticInfo<'_>> for OwnedDiagnosticInfo {
233 fn from(f: DiagnosticInfo<'_>) -> Self {
234 Self {
235 item: f.item.clone(),
236 dox: f.dox.to_string(),
237 ori_link: f.ori_link.to_string(),
238 link_range: f.link_range.clone(),
239 }
240 }
241}
242
243impl OwnedDiagnosticInfo {
244 pub(crate) fn as_info(&self) -> DiagnosticInfo<'_> {
245 DiagnosticInfo {
246 item: &self.item,
247 ori_link: &self.ori_link,
248 dox: &self.dox,
249 link_range: self.link_range.clone(),
250 }
251 }
252}
253
254pub(crate) struct LinkCollector<'a, 'tcx> {
255 pub(crate) cx: &'a mut DocContext<'tcx>,
256 pub(crate) visited_links: FxHashMap<ResolutionInfo, Option<(Res, Option<UrlFragment>)>>,
259 pub(crate) ambiguous_links: FxIndexMap<(ItemId, String), Vec<AmbiguousLinks>>,
270}
271
272pub(crate) struct AmbiguousLinks {
273 link_text: Box<str>,
274 diag_info: OwnedDiagnosticInfo,
275 resolved: Vec<(Res, Option<UrlFragment>)>,
276}
277
278impl<'tcx> LinkCollector<'_, 'tcx> {
279 fn variant_field<'path>(
286 &self,
287 path_str: &'path str,
288 item_id: DefId,
289 module_id: DefId,
290 ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
291 let tcx = self.cx.tcx;
292 let no_res = || UnresolvedPath {
293 item_id,
294 module_id,
295 partial_res: None,
296 unresolved: path_str.into(),
297 };
298
299 debug!("looking for enum variant {path_str}");
300 let mut split = path_str.rsplitn(3, "::");
301 let variant_field_name = Symbol::intern(split.next().unwrap());
302 let variant_name = Symbol::intern(split.next().ok_or_else(no_res)?);
306
307 let path = split.next().ok_or_else(no_res)?;
310 let ty_res = self.resolve_path(path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
311
312 match ty_res {
313 Res::Def(DefKind::Enum | DefKind::TyAlias, did) => {
314 match tcx.type_of(did).instantiate_identity().skip_norm_wip().kind() {
315 ty::Adt(def, _) if def.is_enum() => {
316 if let Some(variant) =
317 def.variants().iter().find(|v| v.name == variant_name)
318 && let Some(field) =
319 variant.fields.iter().find(|f| f.name == variant_field_name)
320 {
321 Ok((ty_res, field.did))
322 } else {
323 Err(UnresolvedPath {
324 item_id,
325 module_id,
326 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
327 unresolved: variant_field_name.to_string().into(),
328 })
329 }
330 }
331 _ => unreachable!(),
332 }
333 }
334 _ => Err(UnresolvedPath {
335 item_id,
336 module_id,
337 partial_res: Some(ty_res),
338 unresolved: variant_name.to_string().into(),
339 }),
340 }
341 }
342
343 fn resolve_path(
349 &self,
350 path_str: &str,
351 ns: Namespace,
352 item_id: DefId,
353 module_id: DefId,
354 ) -> Option<Res> {
355 if let res @ Some(..) = resolve_self_ty(self.cx.tcx, path_str, ns, item_id) {
356 return res;
357 }
358
359 let result = self
361 .cx
362 .tcx
363 .doc_link_resolutions(module_id)
364 .get(&(Symbol::intern(path_str), ns))
365 .copied()
366 .unwrap_or_else(|| {
371 span_bug!(
372 self.cx.tcx.def_span(item_id),
373 "no resolution for {path_str:?} {ns:?} {module_id:?}",
374 )
375 })
376 .and_then(|res| res.try_into().ok())
377 .or_else(|| resolve_primitive(path_str, ns));
378 debug!("{path_str} resolved to {result:?} in namespace {ns:?}");
379 result
380 }
381
382 fn resolve<'path>(
385 &self,
386 path_str: &'path str,
387 ns: Namespace,
388 disambiguator: Option<Disambiguator>,
389 item_id: DefId,
390 module_id: DefId,
391 ) -> Result<Vec<(Res, Option<DefId>)>, UnresolvedPath<'path>> {
392 let tcx = self.cx.tcx;
393
394 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
395 return Ok(match res {
396 Res::Def(
397 DefKind::AssocFn
398 | DefKind::AssocConst { .. }
399 | DefKind::AssocTy
400 | DefKind::Variant,
401 def_id,
402 ) => {
403 vec![(Res::from_def_id(self.cx.tcx, self.cx.tcx.parent(def_id)), Some(def_id))]
404 }
405 _ => vec![(res, None)],
406 });
407 } else if ns == MacroNS {
408 return Err(UnresolvedPath {
409 item_id,
410 module_id,
411 partial_res: None,
412 unresolved: path_str.into(),
413 });
414 }
415
416 let (path_root, item_str) = match path_str.rsplit_once("::") {
419 Some(res @ (_path_root, item_str)) if !item_str.is_empty() => res,
420 _ => {
421 debug!("`::` missing or at end, assuming {path_str} was not in scope");
425 return Err(UnresolvedPath {
426 item_id,
427 module_id,
428 partial_res: None,
429 unresolved: path_str.into(),
430 });
431 }
432 };
433 let item_name = Symbol::intern(item_str);
434
435 match resolve_primitive(path_root, TypeNS)
440 .or_else(|| self.resolve_path(path_root, TypeNS, item_id, module_id))
441 .map(|ty_res| {
442 resolve_associated_item(tcx, ty_res, item_name, ns, disambiguator, module_id)
443 .into_iter()
444 .map(|(res, def_id)| (res, Some(def_id)))
445 .collect::<Vec<_>>()
446 }) {
447 Some(r) if !r.is_empty() => Ok(r),
448 _ => {
449 if ns == Namespace::ValueNS {
450 self.variant_field(path_str, item_id, module_id)
451 .map(|(res, def_id)| vec![(res, Some(def_id))])
452 } else {
453 Err(UnresolvedPath {
454 item_id,
455 module_id,
456 partial_res: None,
457 unresolved: path_root.into(),
458 })
459 }
460 }
461 }
462 }
463}
464
465fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
466 assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
467}
468
469fn resolve_primitive_inherent_assoc_item<'tcx>(
471 tcx: TyCtxt<'tcx>,
472 prim_ty: PrimitiveType,
473 ns: Namespace,
474 item_ident: Ident,
475) -> Vec<(Res, DefId)> {
476 prim_ty
477 .impls(tcx)
478 .flat_map(|impl_| {
479 filter_assoc_items_by_name_and_namespace(tcx, impl_, item_ident, ns)
480 .map(|item| (Res::Primitive(prim_ty), item.def_id))
481 })
482 .collect::<Vec<_>>()
483}
484
485fn resolve_self_ty<'tcx>(
486 tcx: TyCtxt<'tcx>,
487 path_str: &str,
488 ns: Namespace,
489 item_id: DefId,
490) -> Option<Res> {
491 if ns != TypeNS || path_str != "Self" {
492 return None;
493 }
494
495 let self_id = match tcx.def_kind(item_id) {
496 def_kind @ (DefKind::AssocFn
497 | DefKind::AssocConst { .. }
498 | DefKind::AssocTy
499 | DefKind::Variant
500 | DefKind::Field) => {
501 let parent_def_id = tcx.parent(item_id);
502 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant {
503 tcx.parent(parent_def_id)
504 } else {
505 parent_def_id
506 }
507 }
508 _ => item_id,
509 };
510
511 match tcx.def_kind(self_id) {
512 DefKind::Impl { .. } => {
513 ty_to_res(tcx, tcx.type_of(self_id).instantiate_identity().skip_norm_wip())
514 }
515 DefKind::Use => None,
516 def_kind => Some(Res::Def(def_kind, self_id)),
517 }
518}
519
520fn ty_to_res<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Res> {
524 use PrimitiveType::*;
525 Some(match *ty.kind() {
526 ty::Bool => Res::Primitive(Bool),
527 ty::Char => Res::Primitive(Char),
528 ty::Int(ity) => Res::Primitive(ity.into()),
529 ty::Uint(uty) => Res::Primitive(uty.into()),
530 ty::Float(fty) => Res::Primitive(fty.into()),
531 ty::Str => Res::Primitive(Str),
532 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
533 ty::Tuple(_) => Res::Primitive(Tuple),
534 ty::Pat(..) => Res::Primitive(Pat),
535 ty::Array(..) => Res::Primitive(Array),
536 ty::Slice(_) => Res::Primitive(Slice),
537 ty::RawPtr(_, _) => Res::Primitive(RawPointer),
538 ty::Ref(..) => Res::Primitive(Reference),
539 ty::FnDef(..) => panic!("type alias to a function definition"),
540 ty::FnPtr(..) => Res::Primitive(Fn),
541 ty::Never => Res::Primitive(Never),
542 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
543 Res::from_def_id(tcx, did)
544 }
545 ty::Alias(..)
546 | ty::Closure(..)
547 | ty::CoroutineClosure(..)
548 | ty::Coroutine(..)
549 | ty::CoroutineWitness(..)
550 | ty::Dynamic(..)
551 | ty::UnsafeBinder(_)
552 | ty::Param(_)
553 | ty::Bound(..)
554 | ty::Placeholder(_)
555 | ty::Infer(_)
556 | ty::Error(_) => return None,
557 })
558}
559
560fn primitive_type_to_ty<'tcx>(tcx: TyCtxt<'tcx>, prim: PrimitiveType) -> Option<Ty<'tcx>> {
564 use PrimitiveType::*;
565
566 Some(match prim {
570 Bool => tcx.types.bool,
571 Str => tcx.types.str_,
572 Char => tcx.types.char,
573 Never => tcx.types.never,
574 I8 => tcx.types.i8,
575 I16 => tcx.types.i16,
576 I32 => tcx.types.i32,
577 I64 => tcx.types.i64,
578 I128 => tcx.types.i128,
579 Isize => tcx.types.isize,
580 F16 => tcx.types.f16,
581 F32 => tcx.types.f32,
582 F64 => tcx.types.f64,
583 F128 => tcx.types.f128,
584 U8 => tcx.types.u8,
585 U16 => tcx.types.u16,
586 U32 => tcx.types.u32,
587 U64 => tcx.types.u64,
588 U128 => tcx.types.u128,
589 Usize => tcx.types.usize,
590 _ => return None,
591 })
592}
593
594fn resolve_associated_item<'tcx>(
597 tcx: TyCtxt<'tcx>,
598 root_res: Res,
599 item_name: Symbol,
600 ns: Namespace,
601 disambiguator: Option<Disambiguator>,
602 module_id: DefId,
603) -> Vec<(Res, DefId)> {
604 let item_ident = Ident::with_dummy_span(item_name);
605
606 match root_res {
607 Res::Def(DefKind::TyAlias, alias_did) => {
608 let Some(aliased_res) =
612 ty_to_res(tcx, tcx.type_of(alias_did).instantiate_identity().skip_norm_wip())
613 else {
614 return vec![];
615 };
616 let aliased_items =
617 resolve_associated_item(tcx, aliased_res, item_name, ns, disambiguator, module_id);
618 aliased_items
619 .into_iter()
620 .map(|(res, assoc_did)| {
621 if is_assoc_item_on_alias_page(tcx, assoc_did) {
622 (root_res, assoc_did)
623 } else {
624 (res, assoc_did)
625 }
626 })
627 .collect()
628 }
629 Res::Primitive(prim) => resolve_assoc_on_primitive(tcx, prim, ns, item_ident, module_id),
630 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, did) => {
631 resolve_assoc_on_adt(tcx, did, item_ident, ns, disambiguator, module_id)
632 }
633 Res::Def(DefKind::ForeignTy, did) => {
634 resolve_assoc_on_simple_type(tcx, did, item_ident, ns, module_id)
635 }
636 Res::Def(DefKind::Trait, did) => filter_assoc_items_by_name_and_namespace(
637 tcx,
638 did,
639 Ident::with_dummy_span(item_name),
640 ns,
641 )
642 .map(|item| (root_res, item.def_id))
643 .collect::<Vec<_>>(),
644 _ => Vec::new(),
645 }
646}
647
648fn is_assoc_item_on_alias_page<'tcx>(tcx: TyCtxt<'tcx>, assoc_did: DefId) -> bool {
651 match tcx.def_kind(assoc_did) {
652 DefKind::Variant | DefKind::Field => true,
654 _ => false,
655 }
656}
657
658fn resolve_assoc_on_primitive<'tcx>(
659 tcx: TyCtxt<'tcx>,
660 prim: PrimitiveType,
661 ns: Namespace,
662 item_ident: Ident,
663 module_id: DefId,
664) -> Vec<(Res, DefId)> {
665 let root_res = Res::Primitive(prim);
666 let items = resolve_primitive_inherent_assoc_item(tcx, prim, ns, item_ident);
667 if !items.is_empty() {
668 items
669 } else {
671 primitive_type_to_ty(tcx, prim)
672 .map(|ty| {
673 resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
674 .iter()
675 .map(|item| (root_res, item.def_id))
676 .collect::<Vec<_>>()
677 })
678 .unwrap_or_default()
679 }
680}
681
682fn resolve_assoc_on_adt<'tcx>(
683 tcx: TyCtxt<'tcx>,
684 adt_def_id: DefId,
685 item_ident: Ident,
686 ns: Namespace,
687 disambiguator: Option<Disambiguator>,
688 module_id: DefId,
689) -> Vec<(Res, DefId)> {
690 debug!("looking for associated item named {item_ident} for item {adt_def_id:?}");
691 let root_res = Res::from_def_id(tcx, adt_def_id);
692 let adt_ty = tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
693 let adt_def = adt_ty.ty_adt_def().expect("must be ADT");
694 if ns == TypeNS && adt_def.is_enum() {
696 for variant in adt_def.variants() {
697 if variant.name == item_ident.name {
698 return vec![(root_res, variant.def_id)];
699 }
700 }
701 }
702
703 if let Some(Disambiguator::Kind(DefKind::Field)) = disambiguator
704 && (adt_def.is_struct() || adt_def.is_union())
705 {
706 return resolve_structfield(adt_def, item_ident.name)
707 .into_iter()
708 .map(|did| (root_res, did))
709 .collect();
710 }
711
712 let assoc_items = resolve_assoc_on_simple_type(tcx, adt_def_id, item_ident, ns, module_id);
713 if !assoc_items.is_empty() {
714 return assoc_items;
715 }
716
717 if ns == Namespace::ValueNS && (adt_def.is_struct() || adt_def.is_union()) {
718 return resolve_structfield(adt_def, item_ident.name)
719 .into_iter()
720 .map(|did| (root_res, did))
721 .collect();
722 }
723
724 vec![]
725}
726
727fn resolve_assoc_on_simple_type<'tcx>(
729 tcx: TyCtxt<'tcx>,
730 ty_def_id: DefId,
731 item_ident: Ident,
732 ns: Namespace,
733 module_id: DefId,
734) -> Vec<(Res, DefId)> {
735 let root_res = Res::from_def_id(tcx, ty_def_id);
736 let inherent_assoc_items: Vec<_> = tcx
738 .inherent_impls(ty_def_id)
739 .iter()
740 .flat_map(|&imp| filter_assoc_items_by_name_and_namespace(tcx, imp, item_ident, ns))
741 .map(|item| (root_res, item.def_id))
742 .collect();
743 debug!("got inherent assoc items {inherent_assoc_items:?}");
744 if !inherent_assoc_items.is_empty() {
745 return inherent_assoc_items;
746 }
747
748 let ty = tcx.type_of(ty_def_id).instantiate_identity().skip_norm_wip();
754 let trait_assoc_items = resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
755 .into_iter()
756 .map(|item| (root_res, item.def_id))
757 .collect::<Vec<_>>();
758 debug!("got trait assoc items {trait_assoc_items:?}");
759 trait_assoc_items
760}
761
762fn resolve_structfield<'tcx>(adt_def: ty::AdtDef<'tcx>, item_name: Symbol) -> Option<DefId> {
763 debug!("looking for fields named {item_name} for {adt_def:?}");
764 adt_def
765 .non_enum_variant()
766 .fields
767 .iter()
768 .find(|field| field.name == item_name)
769 .map(|field| field.did)
770}
771
772fn resolve_associated_trait_item<'tcx>(
778 ty: Ty<'tcx>,
779 module: DefId,
780 item_ident: Ident,
781 ns: Namespace,
782 tcx: TyCtxt<'tcx>,
783) -> Vec<ty::AssocItem> {
784 let traits = trait_impls_for(tcx, ty, module);
791 debug!("considering traits {traits:?}");
792 let candidates = traits
793 .iter()
794 .flat_map(|&(impl_, trait_)| {
795 filter_assoc_items_by_name_and_namespace(tcx, trait_, item_ident, ns).map(
796 move |trait_assoc| {
797 trait_assoc_to_impl_assoc_item(tcx, impl_, trait_assoc.def_id)
798 .unwrap_or(*trait_assoc)
799 },
800 )
801 })
802 .collect::<Vec<_>>();
803 debug!("the candidates were {candidates:?}");
805 candidates
806}
807
808#[instrument(level = "debug", skip(tcx), ret)]
818fn trait_assoc_to_impl_assoc_item<'tcx>(
819 tcx: TyCtxt<'tcx>,
820 impl_id: DefId,
821 trait_assoc_id: DefId,
822) -> Option<ty::AssocItem> {
823 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
824 debug!(?trait_to_impl_assoc_map);
825 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
826 debug!(?impl_assoc_id);
827 Some(tcx.associated_item(impl_assoc_id))
828}
829
830#[instrument(level = "debug", skip(tcx))]
836fn trait_impls_for<'tcx>(
837 tcx: TyCtxt<'tcx>,
838 ty: Ty<'tcx>,
839 module: DefId,
840) -> FxIndexSet<(DefId, DefId)> {
841 let mut impls = FxIndexSet::default();
842
843 for &trait_ in tcx.doc_link_traits_in_scope(module) {
844 tcx.for_each_relevant_impl(trait_, ty, |impl_| {
845 let trait_ref = tcx.impl_trait_ref(impl_);
846 let impl_type = trait_ref.skip_binder().self_ty();
848 trace!(
849 "comparing type {impl_type} with kind {kind:?} against type {ty:?}",
850 kind = impl_type.kind(),
851 );
852 let saw_impl = impl_type == ty
858 || match (impl_type.kind(), ty.kind()) {
859 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
860 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
861 impl_def.did() == ty_def.did()
862 }
863 _ => false,
864 };
865
866 if saw_impl {
867 impls.insert((impl_, trait_));
868 }
869 });
870 }
871
872 impls
873}
874
875fn is_derive_trait_collision<T>(ns: &PerNS<Result<Vec<(Res, T)>, ResolutionFailure<'_>>>) -> bool {
879 if let (Ok(type_ns), Ok(macro_ns)) = (&ns.type_ns, &ns.macro_ns) {
880 type_ns.iter().any(|(res, _)| matches!(res, Res::Def(DefKind::Trait, _)))
881 && macro_ns.iter().any(|(res, _)| {
882 matches!(
883 res,
884 Res::Def(DefKind::Macro(kinds), _) if kinds.contains(MacroKinds::DERIVE)
885 )
886 })
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 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
928pub(crate) struct PreprocessedMarkdownLink(
930 Result<PreprocessingInfo, PreprocessingError>,
931 MarkdownLink,
932);
933
934fn preprocess_link(
941 ori_link: &MarkdownLink,
942 dox: &str,
943) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
944 let can_be_url = !matches!(
952 ori_link.kind,
953 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown | LinkType::ReferenceUnknown
954 );
955
956 if ori_link.link.is_empty() {
958 return None;
959 }
960
961 if can_be_url && ori_link.link.contains('/') {
963 return None;
964 }
965
966 let stripped = ori_link.link.replace('`', "");
967 let mut parts = stripped.split('#');
968
969 let link = parts.next().unwrap();
970 let link = link.trim();
971 if link.is_empty() {
972 return None;
974 }
975 let extra_fragment = parts.next();
976 if parts.next().is_some() {
977 return Some(Err(PreprocessingError::MultipleAnchors));
979 }
980
981 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
983 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
984 Ok(None) => (None, link, link),
985 Err((err_msg, relative_range)) => {
986 if !(can_be_url && should_ignore_link_with_disambiguators(link)) {
988 let disambiguator_range = match range_between_backticks(&ori_link.range, dox) {
989 MarkdownLinkRange::Destination(no_backticks_range) => {
990 MarkdownLinkRange::Destination(
991 (no_backticks_range.start + relative_range.start)
992 ..(no_backticks_range.start + relative_range.end),
993 )
994 }
995 mdlr @ MarkdownLinkRange::WholeLink(_) => mdlr,
996 };
997 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
998 } else {
999 return None;
1000 }
1001 }
1002 };
1003
1004 let is_shortcut_style = ori_link.kind == LinkType::ShortcutUnknown;
1005 let ignore_urllike = can_be_url || (is_shortcut_style && !ori_link.link.contains('`'));
1022 if ignore_urllike && should_ignore_link(path_str) {
1023 return None;
1024 }
1025 if is_shortcut_style
1031 && let Some(suffix) = ori_link.link.strip_prefix('!')
1032 && !suffix.is_empty()
1033 && suffix.chars().all(|c| c.is_ascii_alphabetic())
1034 {
1035 return None;
1036 }
1037
1038 let path_str = match strip_generics_from_path(path_str) {
1040 Ok(path) => path,
1041 Err(err) => {
1042 debug!("link has malformed generics: {path_str}");
1043 return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
1044 }
1045 };
1046
1047 assert!(!path_str.contains(['<', '>'].as_slice()));
1049
1050 if path_str.contains(' ') {
1052 return None;
1053 }
1054
1055 Some(Ok(PreprocessingInfo {
1056 path_str,
1057 disambiguator,
1058 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1059 link_text: Box::<str>::from(link_text),
1060 }))
1061}
1062
1063fn preprocessed_markdown_links(s: &str) -> Vec<PreprocessedMarkdownLink> {
1064 markdown_links(s, |link| {
1065 preprocess_link(&link, s).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1066 })
1067}
1068
1069impl LinkCollector<'_, '_> {
1070 #[instrument(level = "debug", skip_all)]
1071 fn resolve_links(&mut self, item: &Item) {
1072 let tcx = self.cx.tcx;
1073 let document_private = self.cx.document_private();
1074 let effective_visibilities = tcx.effective_visibilities(());
1075 let should_skip_link_resolution = |item_id: DefId| {
1076 !document_private
1077 && item_id
1078 .as_local()
1079 .is_some_and(|local_def_id| !effective_visibilities.is_exported(local_def_id))
1080 && !has_primitive_or_keyword_or_attribute_docs(&item.attrs.other_attrs)
1081 };
1082
1083 if let Some(def_id) = item.item_id.as_def_id()
1084 && should_skip_link_resolution(def_id)
1085 {
1086 return;
1088 }
1089
1090 let mut try_insert_links = |item_id, doc: &str| {
1091 if should_skip_link_resolution(item_id) {
1092 return;
1093 }
1094 let module_id = match tcx.def_kind(item_id) {
1095 DefKind::Mod if item.inner_docs(tcx) => item_id,
1096 _ => find_nearest_parent_module(tcx, item_id).unwrap(),
1097 };
1098 for md_link in preprocessed_markdown_links(&doc) {
1099 let link = self.resolve_link(&doc, item, item_id, module_id, &md_link);
1100 if let Some(link) = link {
1101 self.cx
1102 .cache
1103 .intra_doc_links
1104 .entry(item.item_or_reexport_id())
1105 .or_default()
1106 .insert(link);
1107 }
1108 }
1109 };
1110
1111 for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
1116 if !may_have_doc_links(&doc) {
1117 continue;
1118 }
1119
1120 debug!("combined_docs={doc}");
1121 let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
1124 try_insert_links(item_id, &doc)
1125 }
1126
1127 for attr in &item.attrs.other_attrs {
1129 let Attribute::Parsed(AttributeKind::Deprecated { span: depr_span, deprecation }) =
1130 attr
1131 else {
1132 continue;
1133 };
1134 let Some(note_sym) = deprecation.note else { continue };
1135 let note = note_sym.as_str();
1136
1137 if !may_have_doc_links(note) {
1138 continue;
1139 }
1140
1141 debug!("deprecated_note={note}");
1142 let item_id = if let Some(inline_stmt_id) = item.inline_stmt_id
1147 && find_attr!(tcx, inline_stmt_id, Deprecated { span, ..} if span == depr_span)
1148 {
1149 inline_stmt_id.to_def_id()
1150 } else {
1151 item.item_id.expect_def_id()
1152 };
1153 try_insert_links(item_id, note)
1154 }
1155 }
1156
1157 pub(crate) fn save_link(&mut self, item_id: ItemId, link: ItemLink) {
1158 self.cx.cache.intra_doc_links.entry(item_id).or_default().insert(link);
1159 }
1160
1161 fn resolve_link(
1165 &mut self,
1166 dox: &str,
1167 item: &Item,
1168 item_id: DefId,
1169 module_id: DefId,
1170 PreprocessedMarkdownLink(pp_link, ori_link): &PreprocessedMarkdownLink,
1171 ) -> Option<ItemLink> {
1172 trace!("considering link '{}'", ori_link.link);
1173
1174 let diag_info = DiagnosticInfo {
1175 item,
1176 dox,
1177 ori_link: &ori_link.link,
1178 link_range: ori_link.range.clone(),
1179 };
1180 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1181 pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1182 let disambiguator = *disambiguator;
1183
1184 let mut resolved = self.resolve_with_disambiguator_cached(
1185 ResolutionInfo {
1186 item_id,
1187 module_id,
1188 dis: disambiguator,
1189 path_str: path_str.clone(),
1190 extra_fragment: extra_fragment.clone(),
1191 },
1192 diag_info.clone(), matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1197 )?;
1198
1199 if resolved.len() > 1 {
1200 let links = AmbiguousLinks {
1201 link_text: link_text.clone(),
1202 diag_info: diag_info.into(),
1203 resolved,
1204 };
1205
1206 self.ambiguous_links
1207 .entry((item.item_id, path_str.to_string()))
1208 .or_default()
1209 .push(links);
1210 None
1211 } else if let Some((res, fragment)) = resolved.pop() {
1212 self.compute_link(res, fragment, path_str, disambiguator, diag_info, link_text)
1213 } else {
1214 None
1215 }
1216 }
1217
1218 fn validate_link(&self, original_did: DefId) -> bool {
1227 let tcx = self.cx.tcx;
1228 let def_kind = tcx.def_kind(original_did);
1229 let did = match def_kind {
1230 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::Variant => {
1231 tcx.parent(original_did)
1233 }
1234 DefKind::Ctor(..) => return self.validate_link(tcx.parent(original_did)),
1237 DefKind::ExternCrate => {
1238 if let Some(local_did) = original_did.as_local() {
1240 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
1241 } else {
1242 original_did
1243 }
1244 }
1245 _ => original_did,
1246 };
1247
1248 let cache = &self.cx.cache;
1249 if !original_did.is_local()
1250 && !cache.effective_visibilities.is_directly_public(tcx, did)
1251 && !cache.document_private
1252 && !cache.primitive_locations.values().any(|&id| id == did)
1253 {
1254 return false;
1255 }
1256
1257 cache.paths.get(&did).is_some()
1258 || cache.external_paths.contains_key(&did)
1259 || !did.is_local()
1260 }
1261
1262 pub(crate) fn resolve_ambiguities(&mut self) {
1263 let mut ambiguous_links = mem::take(&mut self.ambiguous_links);
1264 for ((item_id, path_str), info_items) in ambiguous_links.iter_mut() {
1265 for info in info_items {
1266 info.resolved.retain(|(res, _)| match res {
1267 Res::Def(_, def_id) => self.validate_link(*def_id),
1268 Res::Primitive(_) => true,
1270 });
1271 let diag_info = info.diag_info.as_info();
1272 match info.resolved.len() {
1273 1 => {
1274 let (res, fragment) = info.resolved.pop().unwrap();
1275 if let Some(link) = self.compute_link(
1276 res,
1277 fragment,
1278 path_str,
1279 None,
1280 diag_info,
1281 &info.link_text,
1282 ) {
1283 self.save_link(*item_id, link);
1284 }
1285 }
1286 0 => {
1287 report_diagnostic(
1288 self.cx.tcx,
1289 BROKEN_INTRA_DOC_LINKS,
1290 format!("all items matching `{path_str}` are private or doc(hidden)"),
1291 &diag_info,
1292 |diag, sp, _| {
1293 if let Some(sp) = sp {
1294 diag.span_label(sp, "unresolved link");
1295 } else {
1296 diag.note("unresolved link");
1297 }
1298 },
1299 );
1300 }
1301 _ => {
1302 let candidates = info
1303 .resolved
1304 .iter()
1305 .map(|(res, fragment)| {
1306 let def_id = if let Some(UrlFragment::Item(def_id)) = fragment {
1307 Some(*def_id)
1308 } else {
1309 None
1310 };
1311 (*res, def_id)
1312 })
1313 .collect::<Vec<_>>();
1314 ambiguity_error(self.cx, &diag_info, path_str, &candidates, true);
1315 }
1316 }
1317 }
1318 }
1319 }
1320
1321 fn compute_link(
1322 &mut self,
1323 mut res: Res,
1324 fragment: Option<UrlFragment>,
1325 path_str: &str,
1326 disambiguator: Option<Disambiguator>,
1327 diag_info: DiagnosticInfo<'_>,
1328 link_text: &Box<str>,
1329 ) -> Option<ItemLink> {
1330 if matches!(
1334 disambiguator,
1335 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1336 ) && !matches!(res, Res::Primitive(_))
1337 && let Some(prim) = resolve_primitive(path_str, TypeNS)
1338 {
1339 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1341 res = prim;
1342 } else {
1343 let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)];
1345 ambiguity_error(self.cx, &diag_info, path_str, candidates, true);
1346 return None;
1347 }
1348 }
1349
1350 match res {
1351 Res::Primitive(_) => {
1352 if let Some(UrlFragment::Item(id)) = fragment {
1353 let kind = self.cx.tcx.def_kind(id);
1362 self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1363 } else {
1364 match disambiguator {
1365 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1366 Some(other) => {
1367 self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1368 return None;
1369 }
1370 }
1371 }
1372
1373 res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1374 link: Box::<str>::from(diag_info.ori_link),
1375 link_text: link_text.clone(),
1376 page_id,
1377 fragment,
1378 })
1379 }
1380 Res::Def(kind, id) => {
1381 let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1382 (self.cx.tcx.def_kind(id), id)
1383 } else {
1384 (kind, id)
1385 };
1386 self.verify_disambiguator(
1387 path_str,
1388 kind_for_dis,
1389 id_for_dis,
1390 disambiguator,
1391 &diag_info,
1392 )?;
1393
1394 let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1395 Some(ItemLink {
1396 link: Box::<str>::from(diag_info.ori_link),
1397 link_text: link_text.clone(),
1398 page_id,
1399 fragment,
1400 })
1401 }
1402 }
1403 }
1404
1405 fn verify_disambiguator(
1406 &self,
1407 path_str: &str,
1408 kind: DefKind,
1409 id: DefId,
1410 disambiguator: Option<Disambiguator>,
1411 diag_info: &DiagnosticInfo<'_>,
1412 ) -> Option<()> {
1413 debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1414
1415 debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1417 match (kind, disambiguator) {
1418 | (
1419 DefKind::Const { .. }
1420 | DefKind::ConstParam
1421 | DefKind::AssocConst { .. }
1422 | DefKind::AnonConst,
1423 Some(Disambiguator::Kind(DefKind::Const { .. })),
1424 )
1425 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1428 | (_, Some(Disambiguator::Namespace(_)))
1430 | (_, None)
1432 => {}
1434 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1435 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1436 self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1437 return None;
1438 }
1439 }
1440
1441 if let Some(dst_id) = id.as_local()
1443 && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1444 && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1445 && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1446 {
1447 privacy_error(self.cx, diag_info, path_str);
1448 }
1449
1450 Some(())
1451 }
1452
1453 fn report_disambiguator_mismatch(
1454 &self,
1455 path_str: &str,
1456 specified: Disambiguator,
1457 resolved: Res,
1458 diag_info: &DiagnosticInfo<'_>,
1459 ) {
1460 let msg = format!("incompatible link kind for `{path_str}`");
1462 let callback = |diag: &mut Diag<'_, ()>, sp: Option<rustc_span::Span>, link_range| {
1463 let note = format!(
1464 "this link resolved to {} {}, which is not {} {}",
1465 resolved.article(),
1466 resolved.descr(),
1467 specified.article(),
1468 specified.descr(),
1469 );
1470 if let Some(sp) = sp {
1471 diag.span_label(sp, note);
1472 } else {
1473 diag.note(note);
1474 }
1475 suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1476 };
1477 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1478 }
1479
1480 fn report_rawptr_assoc_feature_gate(
1481 &self,
1482 dox: &str,
1483 ori_link: &MarkdownLinkRange,
1484 item: &Item,
1485 ) {
1486 let span = match source_span_for_markdown_range(
1487 self.cx.tcx,
1488 dox,
1489 ori_link.inner_range(),
1490 &item.attrs.doc_strings,
1491 ) {
1492 Some((sp, _)) => sp,
1493 None => item.attr_span(self.cx.tcx),
1494 };
1495 rustc_session::parse::feature_err(
1496 self.cx.tcx.sess,
1497 sym::intra_doc_pointers,
1498 span,
1499 "linking to associated items of raw pointers is experimental",
1500 )
1501 .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1502 .emit();
1503 }
1504
1505 fn resolve_with_disambiguator_cached(
1506 &mut self,
1507 key: ResolutionInfo,
1508 diag: DiagnosticInfo<'_>,
1509 cache_errors: bool,
1512 ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1513 if let Some(res) = self.visited_links.get(&key)
1514 && (res.is_some() || cache_errors)
1515 {
1516 return res.clone().map(|r| vec![r]);
1517 }
1518
1519 let mut candidates = self.resolve_with_disambiguator(&key, diag.clone());
1520
1521 if let Some(candidate) = candidates.first()
1524 && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1525 && key.path_str.contains("::")
1526 {
1528 if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1529 self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1530 return None;
1531 } else {
1532 candidates = vec![*candidate];
1533 }
1534 }
1535
1536 if let [candidate, _candidate2, ..] = *candidates
1541 && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1542 {
1543 candidates = vec![candidate];
1544 }
1545
1546 let mut out = Vec::with_capacity(candidates.len());
1547 for (res, def_id) in candidates {
1548 let fragment = match (&key.extra_fragment, def_id) {
1549 (Some(_), Some(def_id)) => {
1550 report_anchor_conflict(self.cx, diag, def_id);
1551 return None;
1552 }
1553 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1554 (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1555 (None, None) => None,
1556 };
1557 out.push((res, fragment));
1558 }
1559 if let [r] = out.as_slice() {
1560 self.visited_links.insert(key, Some(r.clone()));
1561 } else if cache_errors {
1562 self.visited_links.insert(key, None);
1563 }
1564 Some(out)
1565 }
1566
1567 fn resolve_with_disambiguator(
1569 &mut self,
1570 key: &ResolutionInfo,
1571 diag: DiagnosticInfo<'_>,
1572 ) -> Vec<(Res, Option<DefId>)> {
1573 let disambiguator = key.dis;
1574 let path_str = &key.path_str;
1575 let item_id = key.item_id;
1576 let module_id = key.module_id;
1577
1578 match disambiguator.map(Disambiguator::ns) {
1579 Some(expected_ns) => {
1580 match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1581 Ok(candidates) => candidates,
1582 Err(err) => {
1583 let mut err = ResolutionFailure::NotResolved(err);
1587 for other_ns in [TypeNS, ValueNS, MacroNS] {
1588 if other_ns != expected_ns
1589 && let Ok(&[res, ..]) = self
1590 .resolve(path_str, other_ns, None, item_id, module_id)
1591 .as_deref()
1592 {
1593 err = ResolutionFailure::WrongNamespace {
1594 res: full_res(self.cx.tcx, res),
1595 expected_ns,
1596 };
1597 break;
1598 }
1599 }
1600 resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1601 vec![]
1602 }
1603 }
1604 }
1605 None => {
1606 let candidate = |ns| {
1608 self.resolve(path_str, ns, None, item_id, module_id)
1609 .map_err(ResolutionFailure::NotResolved)
1610 };
1611
1612 let candidates = PerNS {
1613 macro_ns: candidate(MacroNS),
1614 type_ns: candidate(TypeNS),
1615 value_ns: candidate(ValueNS).and_then(|v_res| {
1616 for (res, _) in v_res.iter() {
1617 if let Res::Def(DefKind::Ctor(..), _) = res {
1619 return Err(ResolutionFailure::WrongNamespace {
1620 res: *res,
1621 expected_ns: TypeNS,
1622 });
1623 }
1624 }
1625 Ok(v_res)
1626 }),
1627 };
1628
1629 let len = candidates
1630 .iter()
1631 .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1632
1633 if len == 0 {
1634 resolution_failure(
1635 self,
1636 diag,
1637 path_str,
1638 disambiguator,
1639 candidates.into_iter().filter_map(|res| res.err()).collect(),
1640 );
1641 vec![]
1642 } else if len == 1 {
1643 candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1644 } else {
1645 let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1646 if len == 2 && has_derive_trait_collision {
1647 candidates.type_ns.unwrap()
1648 } else {
1649 let mut candidates = candidates.map(|candidate| candidate.ok());
1651 if has_derive_trait_collision {
1653 candidates.macro_ns = None;
1654 }
1655 candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1656 }
1657 }
1658 }
1659 }
1660 }
1661}
1662
1663fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1675 let range = match ori_link_range {
1676 mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1677 MarkdownLinkRange::Destination(inner) => inner.clone(),
1678 };
1679 let ori_link_text = &dox[range.clone()];
1680 let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1681 let before_second_backtick_group = ori_link_text
1682 .bytes()
1683 .skip(after_first_backtick_group)
1684 .position(|b| b == b'`')
1685 .unwrap_or(ori_link_text.len());
1686 MarkdownLinkRange::Destination(
1687 (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1688 )
1689}
1690
1691fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1698 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1699}
1700
1701fn should_ignore_link(path_str: &str) -> bool {
1704 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1705}
1706
1707#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1708enum Disambiguator {
1710 Primitive,
1714 Kind(DefKind),
1716 Namespace(Namespace),
1718}
1719
1720impl Disambiguator {
1721 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1727 use Disambiguator::{Kind, Namespace as NS, Primitive};
1728
1729 let suffixes = [
1730 ("!()", DefKind::Macro(MacroKinds::BANG)),
1732 ("!{}", DefKind::Macro(MacroKinds::BANG)),
1733 ("![]", DefKind::Macro(MacroKinds::BANG)),
1734 ("()", DefKind::Fn),
1735 ("!", DefKind::Macro(MacroKinds::BANG)),
1736 ];
1737
1738 if let Some(idx) = link.find('@') {
1739 let (prefix, rest) = link.split_at(idx);
1740 let d = match prefix {
1741 "struct" => Kind(DefKind::Struct),
1743 "enum" => Kind(DefKind::Enum),
1744 "trait" => Kind(DefKind::Trait),
1745 "union" => Kind(DefKind::Union),
1746 "module" | "mod" => Kind(DefKind::Mod),
1747 "const" | "constant" => Kind(DefKind::Const { is_type_const: false }),
1748 "static" => Kind(DefKind::Static {
1749 mutability: Mutability::Not,
1750 nested: false,
1751 safety: Safety::Safe,
1752 }),
1753 "function" | "fn" | "method" => Kind(DefKind::Fn),
1754 "derive" => Kind(DefKind::Macro(MacroKinds::DERIVE)),
1755 "field" => Kind(DefKind::Field),
1756 "variant" => Kind(DefKind::Variant),
1757 "type" => NS(Namespace::TypeNS),
1758 "value" => NS(Namespace::ValueNS),
1759 "macro" => NS(Namespace::MacroNS),
1760 "prim" | "primitive" => Primitive,
1761 "tyalias" | "typealias" => Kind(DefKind::TyAlias),
1762 _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1763 };
1764
1765 for (suffix, kind) in suffixes {
1766 if let Some(path_str) = rest.strip_suffix(suffix) {
1767 if d.ns() != Kind(kind).ns() {
1768 return Err((
1769 format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1770 0..idx,
1771 ));
1772 } else if path_str.len() > 1 {
1773 return Ok(Some((d, &path_str[1..], &rest[1..])));
1775 }
1776 }
1777 }
1778
1779 Ok(Some((d, &rest[1..], &rest[1..])))
1780 } else {
1781 for (suffix, kind) in suffixes {
1782 if let Some(path_str) = link.strip_suffix(suffix)
1784 && !path_str.is_empty()
1785 {
1786 return Ok(Some((Kind(kind), path_str, link)));
1787 }
1788 }
1789 Ok(None)
1790 }
1791 }
1792
1793 fn ns(self) -> Namespace {
1794 match self {
1795 Self::Namespace(n) => n,
1796 Self::Kind(DefKind::Field) => ValueNS,
1798 Self::Kind(k) => {
1799 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1800 }
1801 Self::Primitive => TypeNS,
1802 }
1803 }
1804
1805 fn article(self) -> &'static str {
1806 match self {
1807 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1808 Self::Kind(k) => k.article(),
1809 Self::Primitive => "a",
1810 }
1811 }
1812
1813 fn descr(self) -> &'static str {
1814 match self {
1815 Self::Namespace(n) => n.descr(),
1816 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1819 Self::Primitive => "builtin type",
1820 }
1821 }
1822}
1823
1824enum Suggestion {
1826 Prefix(&'static str),
1828 Function,
1830 Macro,
1832}
1833
1834impl Suggestion {
1835 fn descr(&self) -> Cow<'static, str> {
1836 match self {
1837 Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1838 Self::Function => "add parentheses".into(),
1839 Self::Macro => "add an exclamation mark".into(),
1840 }
1841 }
1842
1843 fn as_help(&self, path_str: &str) -> String {
1844 match self {
1846 Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1847 Self::Function => format!("{path_str}()"),
1848 Self::Macro => format!("{path_str}!"),
1849 }
1850 }
1851
1852 fn as_help_span(
1853 &self,
1854 ori_link: &str,
1855 sp: rustc_span::Span,
1856 ) -> Vec<(rustc_span::Span, String)> {
1857 let inner_sp = match ori_link.find('(') {
1858 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1859 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1860 }
1861 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1862 None => sp,
1863 };
1864 let inner_sp = match ori_link.find('!') {
1865 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1866 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1867 }
1868 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1869 None => inner_sp,
1870 };
1871 let inner_sp = match ori_link.find('@') {
1872 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1873 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1874 }
1875 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1876 None => inner_sp,
1877 };
1878 match self {
1879 Self::Prefix(prefix) => {
1880 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
1882 if sp.hi() != inner_sp.hi() {
1883 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1884 }
1885 sugg
1886 }
1887 Self::Function => {
1888 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1889 if sp.lo() != inner_sp.lo() {
1890 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1891 }
1892 sugg
1893 }
1894 Self::Macro => {
1895 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1896 if sp.lo() != inner_sp.lo() {
1897 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1898 }
1899 sugg
1900 }
1901 }
1902 }
1903}
1904
1905fn report_diagnostic(
1916 tcx: TyCtxt<'_>,
1917 lint: &'static Lint,
1918 msg: impl Into<DiagMessage> + Display,
1919 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1920 decorate: impl FnOnce(&mut Diag<'_, ()>, Option<rustc_span::Span>, MarkdownLinkRange),
1921) {
1922 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
1923 info!("ignoring warning from parent crate: {msg}");
1925 return;
1926 };
1927
1928 let sp = item.attr_span(tcx);
1929
1930 tcx.emit_node_span_lint(
1931 lint,
1932 hir_id,
1933 sp,
1934 rustc_errors::DiagDecorator(|lint| {
1935 lint.primary_message(msg);
1936
1937 let (span, link_range) = match link_range {
1938 MarkdownLinkRange::Destination(md_range) => {
1939 let mut md_range = md_range.clone();
1940 let sp = source_span_for_markdown_range(
1941 tcx,
1942 dox,
1943 &md_range,
1944 &item.attrs.doc_strings,
1945 )
1946 .map(|(mut sp, _)| {
1947 while dox.as_bytes().get(md_range.start) == Some(&b' ')
1948 || dox.as_bytes().get(md_range.start) == Some(&b'`')
1949 {
1950 md_range.start += 1;
1951 sp = sp.with_lo(sp.lo() + BytePos(1));
1952 }
1953 while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
1954 || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
1955 {
1956 md_range.end -= 1;
1957 sp = sp.with_hi(sp.hi() - BytePos(1));
1958 }
1959 sp
1960 });
1961 (sp, MarkdownLinkRange::Destination(md_range))
1962 }
1963 MarkdownLinkRange::WholeLink(md_range) => (
1964 source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
1965 .map(|(sp, _)| sp),
1966 link_range.clone(),
1967 ),
1968 };
1969
1970 if let Some(sp) = span {
1971 lint.span(sp);
1972 } else {
1973 let md_range = link_range.inner_range().clone();
1978 let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
1979 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1980
1981 lint.note(format!(
1983 "the link appears in this line:\n\n{line}\n\
1984 {indicator: <before$}{indicator:^<found$}",
1985 indicator = "",
1986 before = md_range.start - last_new_line_offset,
1987 found = md_range.len(),
1988 ));
1989 }
1990
1991 decorate(lint, span, link_range);
1992 }),
1993 );
1994}
1995
1996fn resolution_failure(
2002 collector: &LinkCollector<'_, '_>,
2003 diag_info: DiagnosticInfo<'_>,
2004 path_str: &str,
2005 disambiguator: Option<Disambiguator>,
2006 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
2007) {
2008 let tcx = collector.cx.tcx;
2009 report_diagnostic(
2010 tcx,
2011 BROKEN_INTRA_DOC_LINKS,
2012 format!("unresolved link to `{path_str}`"),
2013 &diag_info,
2014 |diag, sp, link_range| {
2015 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
2016 let assoc_item_not_allowed = |res: Res| {
2017 let name = res.name(tcx);
2018 format!(
2019 "`{name}` is {} {}, not a module or type, and cannot have associated items",
2020 res.article(),
2021 res.descr()
2022 )
2023 };
2024 let mut variants_seen = SmallVec::<[_; 3]>::new();
2026 for mut failure in kinds {
2027 let variant = mem::discriminant(&failure);
2028 if variants_seen.contains(&variant) {
2029 continue;
2030 }
2031 variants_seen.push(variant);
2032
2033 if let ResolutionFailure::NotResolved(UnresolvedPath {
2034 item_id,
2035 module_id,
2036 partial_res,
2037 unresolved,
2038 }) = &mut failure
2039 {
2040 use DefKind::*;
2041
2042 let item_id = *item_id;
2043 let module_id = *module_id;
2044
2045 let mut name = path_str;
2048 'outer: loop {
2049 let Some((start, end)) = name.rsplit_once("::") else {
2051 if partial_res.is_none() {
2053 *unresolved = name.into();
2054 }
2055 break;
2056 };
2057 name = start;
2058 for ns in [TypeNS, ValueNS, MacroNS] {
2059 if let Ok(v_res) =
2060 collector.resolve(start, ns, None, item_id, module_id)
2061 {
2062 debug!("found partial_res={v_res:?}");
2063 if let Some(&res) = v_res.first() {
2064 *partial_res = Some(full_res(tcx, res));
2065 *unresolved = end.into();
2066 break 'outer;
2067 }
2068 }
2069 }
2070 *unresolved = end.into();
2071 }
2072
2073 let last_found_module = match *partial_res {
2074 Some(Res::Def(DefKind::Mod, id)) => Some(id),
2075 None => Some(module_id),
2076 _ => None,
2077 };
2078 if let Some(module) = last_found_module {
2080 let note = if partial_res.is_some() {
2081 let module_name = tcx.item_name(module);
2083 format!("no item named `{unresolved}` in module `{module_name}`")
2084 } else {
2085 format!("no item named `{unresolved}` in scope")
2087 };
2088 if let Some(span) = sp {
2089 diag.span_label(span, note);
2090 } else {
2091 diag.note(note);
2092 }
2093
2094 if !path_str.contains("::") {
2095 if disambiguator.is_none_or(|d| d.ns() == MacroNS)
2096 && collector
2097 .cx
2098 .tcx
2099 .resolutions(())
2100 .all_macro_rules
2101 .contains(&Symbol::intern(path_str))
2102 {
2103 diag.note(format!(
2104 "`macro_rules` named `{path_str}` exists in this crate, \
2105 but it is not in scope at this link's location"
2106 ));
2107 } else {
2108 diag.help(
2111 "to escape `[` and `]` characters, \
2112 add '\\' before them like `\\[` or `\\]`",
2113 );
2114 }
2115 }
2116
2117 continue;
2118 }
2119
2120 let res = partial_res.expect("None case was handled by `last_found_module`");
2122 let kind_did = match res {
2123 Res::Def(kind, did) => Some((kind, did)),
2124 Res::Primitive(_) => None,
2125 };
2126 let is_struct_variant = |did| {
2127 if let ty::Adt(def, _) =
2128 tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
2129 && def.is_enum()
2130 && let Some(variant) =
2131 def.variants().iter().find(|v| v.name == res.name(tcx))
2132 {
2133 variant.ctor.is_none()
2135 } else {
2136 false
2137 }
2138 };
2139 let path_description = if let Some((kind, did)) = kind_did {
2140 match kind {
2141 Mod | ForeignMod => "inner item",
2142 Struct => "field or associated item",
2143 Enum | Union => "variant or associated item",
2144 Variant if is_struct_variant(did) => {
2145 let variant = res.name(tcx);
2146 let note = format!("variant `{variant}` has no such field");
2147 if let Some(span) = sp {
2148 diag.span_label(span, note);
2149 } else {
2150 diag.note(note);
2151 }
2152 return;
2153 }
2154 Variant
2155 | Field
2156 | Closure
2157 | AssocTy
2158 | AssocConst { .. }
2159 | AssocFn
2160 | Fn
2161 | Macro(_)
2162 | Const { .. }
2163 | ConstParam
2164 | ExternCrate
2165 | Use
2166 | LifetimeParam
2167 | Ctor(_, _)
2168 | AnonConst
2169 | InlineConst => {
2170 let note = assoc_item_not_allowed(res);
2171 if let Some(span) = sp {
2172 diag.span_label(span, note);
2173 } else {
2174 diag.note(note);
2175 }
2176 return;
2177 }
2178 Trait
2179 | TyAlias
2180 | ForeignTy
2181 | OpaqueTy
2182 | TraitAlias
2183 | TyParam
2184 | Static { .. } => "associated item",
2185 Impl { .. } | GlobalAsm | SyntheticCoroutineBody => {
2186 unreachable!("not a path")
2187 }
2188 }
2189 } else {
2190 "associated item"
2191 };
2192 let name = res.name(tcx);
2193 let note = format!(
2194 "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2195 res = res.descr(),
2196 disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2197 );
2198 if let Some(span) = sp {
2199 diag.span_label(span, note);
2200 } else {
2201 diag.note(note);
2202 }
2203
2204 continue;
2205 }
2206 let note = match failure {
2207 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2208 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2209 suggest_disambiguator(
2210 res,
2211 diag,
2212 path_str,
2213 link_range.clone(),
2214 sp,
2215 &diag_info,
2216 );
2217
2218 if let Some(disambiguator) = disambiguator
2219 && !matches!(disambiguator, Disambiguator::Namespace(..))
2220 {
2221 format!(
2222 "this link resolves to {}, which is not {} {}",
2223 item(res),
2224 disambiguator.article(),
2225 disambiguator.descr()
2226 )
2227 } else {
2228 format!(
2229 "this link resolves to {}, which is not in the {} namespace",
2230 item(res),
2231 expected_ns.descr()
2232 )
2233 }
2234 }
2235 };
2236 if let Some(span) = sp {
2237 diag.span_label(span, note);
2238 } else {
2239 diag.note(note);
2240 }
2241 }
2242 },
2243 );
2244}
2245
2246fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2247 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2248 anchor_failure(cx, diag_info, msg, 1)
2249}
2250
2251fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2252 let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2253 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2254 anchor_failure(cx, diag_info, msg, 0)
2255}
2256
2257fn anchor_failure(
2259 cx: &DocContext<'_>,
2260 diag_info: DiagnosticInfo<'_>,
2261 msg: String,
2262 anchor_idx: usize,
2263) {
2264 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2265 if let Some(mut sp) = sp {
2266 if let Some((fragment_offset, _)) =
2267 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2268 {
2269 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2270 }
2271 diag.span_label(sp, "invalid anchor");
2272 }
2273 });
2274}
2275
2276fn disambiguator_error(
2278 cx: &DocContext<'_>,
2279 mut diag_info: DiagnosticInfo<'_>,
2280 disambiguator_range: MarkdownLinkRange,
2281 msg: impl Into<DiagMessage> + Display,
2282) {
2283 diag_info.link_range = disambiguator_range;
2284 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2285 let msg = format!(
2286 "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2287 crate::DOC_RUST_LANG_ORG_VERSION
2288 );
2289 diag.note(msg);
2290 });
2291}
2292
2293fn report_malformed_generics(
2294 cx: &DocContext<'_>,
2295 diag_info: DiagnosticInfo<'_>,
2296 err: MalformedGenerics,
2297 path_str: &str,
2298) {
2299 report_diagnostic(
2300 cx.tcx,
2301 BROKEN_INTRA_DOC_LINKS,
2302 format!("unresolved link to `{path_str}`"),
2303 &diag_info,
2304 |diag, sp, _link_range| {
2305 let note = match err {
2306 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2307 MalformedGenerics::MissingType => "missing type for generic parameters",
2308 MalformedGenerics::HasFullyQualifiedSyntax => {
2309 diag.note(
2310 "see https://github.com/rust-lang/rust/issues/74563 for more information",
2311 );
2312 "fully-qualified syntax is unsupported"
2313 }
2314 MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
2315 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2316 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2317 };
2318 if let Some(span) = sp {
2319 diag.span_label(span, note);
2320 } else {
2321 diag.note(note);
2322 }
2323 },
2324 );
2325}
2326
2327fn ambiguity_error(
2333 cx: &DocContext<'_>,
2334 diag_info: &DiagnosticInfo<'_>,
2335 path_str: &str,
2336 candidates: &[(Res, Option<DefId>)],
2337 emit_error: bool,
2338) -> bool {
2339 let mut descrs = FxHashSet::default();
2340 let mut possible_proc_macro_id = None;
2343 let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro];
2344 let mut kinds = candidates
2345 .iter()
2346 .map(|(res, def_id)| {
2347 let r =
2348 if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2349 if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2350 possible_proc_macro_id = Some(id);
2351 }
2352 r
2353 })
2354 .collect::<Vec<_>>();
2355 if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2364 kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2365 }
2366
2367 kinds.retain(|res| descrs.insert(res.descr()));
2368
2369 if descrs.len() == 1 {
2370 return false;
2373 } else if !emit_error {
2374 return true;
2375 }
2376
2377 let mut msg = format!("`{path_str}` is ");
2378 match kinds.as_slice() {
2379 [res1, res2] => {
2380 msg += &format!(
2381 "both {} {} and {} {}",
2382 res1.article(),
2383 res1.descr(),
2384 res2.article(),
2385 res2.descr()
2386 );
2387 }
2388 _ => {
2389 let mut kinds = kinds.iter().peekable();
2390 while let Some(res) = kinds.next() {
2391 if kinds.peek().is_some() {
2392 msg += &format!("{} {}, ", res.article(), res.descr());
2393 } else {
2394 msg += &format!("and {} {}", res.article(), res.descr());
2395 }
2396 }
2397 }
2398 }
2399
2400 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2401 if let Some(sp) = sp {
2402 diag.span_label(sp, "ambiguous link");
2403 } else {
2404 diag.note("ambiguous link");
2405 }
2406
2407 for res in kinds {
2408 suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2409 }
2410 });
2411 true
2412}
2413
2414fn suggest_disambiguator(
2417 res: Res,
2418 diag: &mut Diag<'_, ()>,
2419 path_str: &str,
2420 link_range: MarkdownLinkRange,
2421 sp: Option<rustc_span::Span>,
2422 diag_info: &DiagnosticInfo<'_>,
2423) {
2424 let suggestion = res.disambiguator_suggestion();
2425 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2426
2427 let ori_link = match link_range {
2428 MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2429 MarkdownLinkRange::WholeLink(_) => None,
2430 };
2431
2432 if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2433 let mut spans = suggestion.as_help_span(ori_link, sp);
2434 if spans.len() > 1 {
2435 diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2436 } else {
2437 let (sp, suggestion_text) = spans.pop().unwrap();
2438 diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2439 }
2440 } else {
2441 diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2442 }
2443}
2444
2445fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2447 let sym;
2448 let item_name = match diag_info.item.name {
2449 Some(name) => {
2450 sym = name;
2451 sym.as_str()
2452 }
2453 None => "<unknown>",
2454 };
2455 let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2456
2457 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2458 if let Some(sp) = sp {
2459 diag.span_label(sp, "this item is private");
2460 }
2461
2462 let note_msg = if cx.document_private() {
2463 "this link resolves only because you passed `--document-private-items`, but will break without"
2464 } else {
2465 "this link will resolve properly if you pass `--document-private-items`"
2466 };
2467 diag.note(note_msg);
2468 });
2469}
2470
2471fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2473 if ns != TypeNS {
2474 return None;
2475 }
2476 use PrimitiveType::*;
2477 let prim = match path_str {
2478 "isize" => Isize,
2479 "i8" => I8,
2480 "i16" => I16,
2481 "i32" => I32,
2482 "i64" => I64,
2483 "i128" => I128,
2484 "usize" => Usize,
2485 "u8" => U8,
2486 "u16" => U16,
2487 "u32" => U32,
2488 "u64" => U64,
2489 "u128" => U128,
2490 "f16" => F16,
2491 "f32" => F32,
2492 "f64" => F64,
2493 "f128" => F128,
2494 "char" => Char,
2495 "bool" | "true" | "false" => Bool,
2496 "str" | "&str" => Str,
2497 "slice" => Slice,
2499 "array" => Array,
2500 "tuple" => Tuple,
2501 "unit" => Unit,
2502 "pointer" | "*const" | "*mut" => RawPointer,
2503 "reference" | "&" | "&mut" => Reference,
2504 "fn" => Fn,
2505 "never" | "!" => Never,
2506 _ => return None,
2507 };
2508 debug!("resolved primitives {prim:?}");
2509 Some(Res::Primitive(prim))
2510}