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_lint::Lint;
20use rustc_middle::ty::{Ty, TyCtxt};
21use rustc_middle::{bug, span_bug, ty};
22use rustc_resolve::rustdoc::pulldown_cmark::LinkType;
23use rustc_resolve::rustdoc::{
24 MalformedGenerics, has_primitive_or_keyword_or_attribute_docs, prepare_to_doc_link_resolution,
25 source_span_for_markdown_range, strip_generics_from_path,
26};
27use rustc_span::BytePos;
28use rustc_span::def_id::ModId;
29use rustc_span::edit_distance::find_best_match_for_name;
30use rustc_span::symbol::{Ident, Symbol, sym};
31use rustc_structures::CrateType;
32use smallvec::{SmallVec, smallvec};
33use tracing::{debug, info, instrument, trace};
34
35use crate::clean::utils::find_nearest_parent_module;
36use crate::clean::{self, Crate, Item, ItemId, ItemLink, PrimitiveType, reexport_chain};
37use crate::core::DocContext;
38use crate::html::markdown::{MarkdownLink, MarkdownLinkRange, markdown_links};
39use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
40use crate::visit::DocVisitor;
41
42pub(super) fn collect_intra_doc_links(
43 krate: Crate,
44 cx: &mut DocContext<'_>,
45) -> (Crate, LinkCollection) {
46 let mut collector = LinkCollector { cx, links: LinkCollection::default() };
47 collector.visit_crate(&krate);
48 (krate, collector.links)
49}
50
51pub(super) fn resolve_ambiguous_links(links: LinkCollection, cx: &mut DocContext<'_>) {
52 LinkCollector { cx, links }.resolve_ambiguities();
53}
54
55fn filter_assoc_items_by_name_and_namespace(
56 tcx: TyCtxt<'_>,
57 assoc_items_of: DefId,
58 ident: Ident,
59 ns: Namespace,
60) -> impl Iterator<Item = &ty::AssocItem> {
61 tcx.associated_items(assoc_items_of).filter_by_name_unhygienic(ident.name).filter(move |item| {
62 item.namespace() == ns && tcx.hygienic_eq(ident, item.ident(tcx), assoc_items_of)
63 })
64}
65
66#[derive(Copy, Clone, Debug, Hash, PartialEq)]
67pub(crate) enum Res {
68 Def(DefKind, DefId),
69 Primitive(PrimitiveType),
70}
71
72type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
73
74impl Res {
75 fn descr(self) -> &'static str {
76 match self {
77 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
78 Res::Primitive(_) => "primitive type",
79 }
80 }
81
82 fn article(self) -> &'static str {
83 match self {
84 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
85 Res::Primitive(_) => "a",
86 }
87 }
88
89 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
90 match self {
91 Res::Def(_, id) => tcx.item_name(id),
92 Res::Primitive(prim) => prim.as_sym(),
93 }
94 }
95
96 fn def_id(self, tcx: TyCtxt<'_>) -> Option<DefId> {
97 match self {
98 Res::Def(_, id) => Some(id),
99 Res::Primitive(prim) => PrimitiveType::primitive_locations(tcx).get(&prim).copied(),
100 }
101 }
102
103 fn from_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Res {
104 Res::Def(tcx.def_kind(def_id), def_id)
105 }
106
107 fn disambiguator_suggestion(self) -> Suggestion {
109 let kind = match self {
110 Res::Primitive(_) => return Suggestion::Prefix("prim"),
111 Res::Def(kind, _) => kind,
112 };
113
114 let prefix = match kind {
115 DefKind::Fn | DefKind::AssocFn => return Suggestion::Function,
116 DefKind::Macro(MacroKinds::ATTR) => "attribute",
119 DefKind::Macro(MacroKinds::DERIVE) => "derive",
120 DefKind::Macro(_) => return Suggestion::Macro,
121 DefKind::Struct => "struct",
122 DefKind::Enum => "enum",
123 DefKind::Trait => "trait",
124 DefKind::Union => "union",
125 DefKind::Mod => "mod",
126 DefKind::Const { .. }
127 | DefKind::ConstParam
128 | DefKind::AssocConst { .. }
129 | DefKind::AnonConst => "const",
130 DefKind::Static { .. } => "static",
131 DefKind::Field => "field",
132 DefKind::Variant | DefKind::Ctor(..) => "variant",
133 DefKind::TyAlias => "tyalias",
134 _ => match kind
136 .ns()
137 .expect("tried to calculate a disambiguator for a def without a namespace?")
138 {
139 Namespace::TypeNS => "type",
140 Namespace::ValueNS => "value",
141 Namespace::MacroNS => "macro",
142 },
143 };
144
145 Suggestion::Prefix(prefix)
146 }
147}
148
149impl TryFrom<ResolveRes> for Res {
150 type Error = ();
151
152 fn try_from(res: ResolveRes) -> Result<Self, ()> {
153 use rustc_hir::def::Res::*;
154 match res {
155 Def(kind, id) => Ok(Res::Def(kind, id)),
156 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
157 ToolMod | NonMacroAttr(..) | Err => Result::Err(()),
159 other => bug!("unrecognized res {other:?}"),
160 }
161 }
162}
163
164#[derive(Debug)]
167struct UnresolvedPath<'a> {
168 item_id: DefId,
170 module_id: ModId,
172 partial_res: Option<Res>,
176 unresolved: Cow<'a, str>,
180}
181
182#[derive(Debug)]
183enum ResolutionFailure<'a> {
184 WrongNamespace {
186 res: Res,
188 expected_ns: Namespace,
193 },
194 NotResolved(UnresolvedPath<'a>),
195}
196
197#[derive(Clone, Debug, Hash, PartialEq, Eq)]
198pub(crate) enum UrlFragment {
199 Item(DefId),
200 UserWritten(String),
204}
205
206#[derive(Clone, Debug, Hash, PartialEq, Eq)]
207pub(crate) struct ResolutionInfo {
208 item_id: DefId,
209 module_id: ModId,
210 dis: Option<Disambiguator>,
211 path_str: Box<str>,
212 extra_fragment: Option<String>,
213}
214
215#[derive(Clone)]
216pub(crate) struct DiagnosticInfo<'a> {
217 item: &'a Item,
218 dox: &'a str,
219 ori_link: &'a str,
220 link_range: MarkdownLinkRange,
221}
222
223pub(crate) struct OwnedDiagnosticInfo {
224 item: Item,
225 dox: String,
226 ori_link: String,
227 link_range: MarkdownLinkRange,
228}
229
230impl From<DiagnosticInfo<'_>> for OwnedDiagnosticInfo {
231 fn from(f: DiagnosticInfo<'_>) -> Self {
232 Self {
233 item: f.item.clone(),
234 dox: f.dox.to_string(),
235 ori_link: f.ori_link.to_string(),
236 link_range: f.link_range.clone(),
237 }
238 }
239}
240
241impl OwnedDiagnosticInfo {
242 pub(crate) fn as_info(&self) -> DiagnosticInfo<'_> {
243 DiagnosticInfo {
244 item: &self.item,
245 ori_link: &self.ori_link,
246 dox: &self.dox,
247 link_range: self.link_range.clone(),
248 }
249 }
250}
251
252struct LinkCollector<'a, 'tcx> {
253 cx: &'a mut DocContext<'tcx>,
254 links: LinkCollection,
255}
256
257#[derive(Default)]
258pub(super) struct LinkCollection {
259 visited: FxHashMap<ResolutionInfo, Option<(Res, Option<UrlFragment>)>>,
262 ambiguous: FxIndexMap<(ItemId, String), Vec<AmbiguousLinks>>,
273}
274
275pub(crate) struct AmbiguousLinks {
276 link_text: Box<str>,
277 diag_info: OwnedDiagnosticInfo,
278 resolved: Vec<(Res, Option<UrlFragment>)>,
279}
280
281impl<'tcx> LinkCollector<'_, 'tcx> {
282 fn variant_field<'path>(
289 &self,
290 path_str: &'path str,
291 item_id: DefId,
292 module_id: ModId,
293 ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
294 let tcx = self.cx.tcx;
295 let no_res = || UnresolvedPath {
296 item_id,
297 module_id,
298 partial_res: None,
299 unresolved: path_str.into(),
300 };
301
302 debug!("looking for enum variant {path_str}");
303 let mut split = path_str.rsplitn(3, "::");
304 let variant_field_name = Symbol::intern(split.next().unwrap());
305 let variant_name = Symbol::intern(split.next().ok_or_else(no_res)?);
309
310 let path = split.next().ok_or_else(no_res)?;
313 let ty_res = self.resolve_path(path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
314
315 match ty_res {
316 Res::Def(DefKind::Enum | DefKind::TyAlias, did) => {
317 match tcx.type_of(did).instantiate_identity().skip_norm_wip().kind() {
318 ty::Adt(def, _) if def.is_enum() => {
319 if let Some(variant) =
320 def.variants().iter().find(|v| v.name == variant_name)
321 && let Some(field) =
322 variant.fields.iter().find(|f| f.name == variant_field_name)
323 {
324 Ok((ty_res, field.did))
325 } else {
326 Err(UnresolvedPath {
327 item_id,
328 module_id,
329 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
330 unresolved: variant_field_name.to_string().into(),
331 })
332 }
333 }
334 _ => Err(UnresolvedPath {
335 item_id,
336 module_id,
337 partial_res: Some(Res::Def(DefKind::TyAlias, did)),
338 unresolved: variant_name.to_string().into(),
339 }),
340 }
341 }
342 _ => Err(UnresolvedPath {
343 item_id,
344 module_id,
345 partial_res: Some(ty_res),
346 unresolved: variant_name.to_string().into(),
347 }),
348 }
349 }
350
351 fn resolve_path(
357 &self,
358 path_str: &str,
359 ns: Namespace,
360 item_id: DefId,
361 module_id: ModId,
362 ) -> Option<Res> {
363 if let res @ Some(..) = resolve_self_ty(self.cx.tcx, path_str, ns, item_id) {
364 return res;
365 }
366
367 let result = self
369 .cx
370 .tcx
371 .doc_link_resolutions(module_id)
372 .get(&(Symbol::intern(path_str), ns))
373 .copied()
374 .unwrap_or_else(|| {
379 span_bug!(
380 self.cx.tcx.def_span(item_id),
381 "no resolution for {path_str:?} {ns:?} {module_id:?}",
382 )
383 })
384 .and_then(|res| res.try_into().ok())
385 .or_else(|| resolve_primitive(path_str, ns));
386 debug!("{path_str} resolved to {result:?} in namespace {ns:?}");
387 result
388 }
389
390 fn resolve<'path>(
393 &self,
394 path_str: &'path str,
395 ns: Namespace,
396 disambiguator: Option<Disambiguator>,
397 item_id: DefId,
398 module_id: ModId,
399 ) -> Result<Vec<(Res, Option<DefId>)>, UnresolvedPath<'path>> {
400 let tcx = self.cx.tcx;
401
402 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
403 return Ok(match res {
404 Res::Def(
405 DefKind::AssocFn
406 | DefKind::AssocConst { .. }
407 | DefKind::AssocTy
408 | DefKind::Variant,
409 def_id,
410 ) => {
411 vec![(Res::from_def_id(self.cx.tcx, self.cx.tcx.parent(def_id)), Some(def_id))]
412 }
413 _ => vec![(res, None)],
414 });
415 } else if ns == MacroNS {
416 return Err(UnresolvedPath {
417 item_id,
418 module_id,
419 partial_res: None,
420 unresolved: path_str.into(),
421 });
422 }
423
424 let (path_root, item_str) = match path_str.rsplit_once("::") {
427 Some(res @ (_path_root, item_str)) if !item_str.is_empty() => res,
428 _ => {
429 debug!("`::` missing or at end, assuming {path_str} was not in scope");
433 return Err(UnresolvedPath {
434 item_id,
435 module_id,
436 partial_res: None,
437 unresolved: path_str.into(),
438 });
439 }
440 };
441 let item_name = Symbol::intern(item_str);
442
443 match resolve_primitive(path_root, TypeNS)
448 .or_else(|| self.resolve_path(path_root, TypeNS, item_id, module_id))
449 .map(|ty_res| {
450 resolve_associated_item(tcx, ty_res, item_name, ns, disambiguator, module_id)
451 .into_iter()
452 .map(|(res, def_id)| (res, Some(def_id)))
453 .collect::<Vec<_>>()
454 }) {
455 Some(r) if !r.is_empty() => Ok(r),
456 _ => {
457 if ns == Namespace::ValueNS {
458 self.variant_field(path_str, item_id, module_id)
459 .map(|(res, def_id)| vec![(res, Some(def_id))])
460 } else {
461 Err(UnresolvedPath {
462 item_id,
463 module_id,
464 partial_res: None,
465 unresolved: path_root.into(),
466 })
467 }
468 }
469 }
470 }
471}
472
473fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
474 assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
475}
476
477fn resolve_primitive_inherent_assoc_item<'tcx>(
479 tcx: TyCtxt<'tcx>,
480 prim_ty: PrimitiveType,
481 ns: Namespace,
482 item_ident: Ident,
483) -> Vec<(Res, DefId)> {
484 prim_ty
485 .impls(tcx)
486 .flat_map(|impl_| {
487 filter_assoc_items_by_name_and_namespace(tcx, impl_, item_ident, ns)
488 .map(|item| (Res::Primitive(prim_ty), item.def_id))
489 })
490 .collect::<Vec<_>>()
491}
492
493fn resolve_self_ty<'tcx>(
494 tcx: TyCtxt<'tcx>,
495 path_str: &str,
496 ns: Namespace,
497 item_id: DefId,
498) -> Option<Res> {
499 if ns != TypeNS || path_str != "Self" {
500 return None;
501 }
502
503 let self_id = match tcx.def_kind(item_id) {
504 def_kind @ (DefKind::AssocFn
505 | DefKind::AssocConst { .. }
506 | DefKind::AssocTy
507 | DefKind::Variant
508 | DefKind::Field) => {
509 let parent_def_id = tcx.parent(item_id);
510 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant {
511 tcx.parent(parent_def_id)
512 } else {
513 parent_def_id
514 }
515 }
516 _ => item_id,
517 };
518
519 match tcx.def_kind(self_id) {
520 DefKind::Impl { .. } => {
521 ty_to_res(tcx, tcx.type_of(self_id).instantiate_identity().skip_norm_wip())
522 }
523 DefKind::Use => None,
524 def_kind => Some(Res::Def(def_kind, self_id)),
525 }
526}
527
528fn ty_to_res<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Res> {
532 use PrimitiveType::*;
533 Some(match *ty.kind() {
534 ty::Bool => Res::Primitive(Bool),
535 ty::Char => Res::Primitive(Char),
536 ty::Int(ity) => Res::Primitive(ity.into()),
537 ty::Uint(uty) => Res::Primitive(uty.into()),
538 ty::Float(fty) => Res::Primitive(fty.into()),
539 ty::Str => Res::Primitive(Str),
540 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
541 ty::Tuple(_) => Res::Primitive(Tuple),
542 ty::Pat(..) => Res::Primitive(Pat),
543 ty::Array(..) => Res::Primitive(Array),
544 ty::Slice(_) => Res::Primitive(Slice),
545 ty::RawPtr(_, _) => Res::Primitive(RawPointer),
546 ty::Ref(..) => Res::Primitive(Reference),
547 ty::FnDef(..) => panic!("type alias to a function definition"),
548 ty::FnPtr(..) => Res::Primitive(Fn),
549 ty::Never => Res::Primitive(Never),
550 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
551 Res::from_def_id(tcx, did)
552 }
553 ty::Alias(_, ..)
554 | ty::Closure(..)
555 | ty::CoroutineClosure(..)
556 | ty::Coroutine(..)
557 | ty::CoroutineWitness(..)
558 | ty::Dynamic(..)
559 | ty::UnsafeBinder(_)
560 | ty::Param(_)
561 | ty::Bound(..)
562 | ty::Placeholder(_)
563 | ty::Infer(_)
564 | ty::Error(_) => return None,
565 })
566}
567
568fn primitive_type_to_ty<'tcx>(tcx: TyCtxt<'tcx>, prim: PrimitiveType) -> Option<Ty<'tcx>> {
572 use PrimitiveType::*;
573
574 Some(match prim {
578 Bool => tcx.types.bool,
579 Str => tcx.types.str_,
580 Char => tcx.types.char,
581 Never => tcx.types.never,
582 I8 => tcx.types.i8,
583 I16 => tcx.types.i16,
584 I32 => tcx.types.i32,
585 I64 => tcx.types.i64,
586 I128 => tcx.types.i128,
587 Isize => tcx.types.isize,
588 F16 => tcx.types.f16,
589 F32 => tcx.types.f32,
590 F64 => tcx.types.f64,
591 F128 => tcx.types.f128,
592 U8 => tcx.types.u8,
593 U16 => tcx.types.u16,
594 U32 => tcx.types.u32,
595 U64 => tcx.types.u64,
596 U128 => tcx.types.u128,
597 Usize => tcx.types.usize,
598 _ => return None,
599 })
600}
601
602fn resolve_associated_item<'tcx>(
605 tcx: TyCtxt<'tcx>,
606 root_res: Res,
607 item_name: Symbol,
608 ns: Namespace,
609 disambiguator: Option<Disambiguator>,
610 module_id: ModId,
611) -> Vec<(Res, DefId)> {
612 let item_ident = Ident::with_dummy_span(item_name);
613
614 match root_res {
615 Res::Def(DefKind::TyAlias, alias_did) => {
616 let Some(aliased_res) =
620 ty_to_res(tcx, tcx.type_of(alias_did).instantiate_identity().skip_norm_wip())
621 else {
622 return vec![];
623 };
624 let aliased_items =
625 resolve_associated_item(tcx, aliased_res, item_name, ns, disambiguator, module_id);
626 aliased_items
627 .into_iter()
628 .map(|(res, assoc_did)| {
629 if is_assoc_item_on_alias_page(tcx, assoc_did) {
630 (root_res, assoc_did)
631 } else {
632 (res, assoc_did)
633 }
634 })
635 .collect()
636 }
637 Res::Primitive(prim) => resolve_assoc_on_primitive(tcx, prim, ns, item_ident, module_id),
638 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, did) => {
639 resolve_assoc_on_adt(tcx, did, item_ident, ns, disambiguator, module_id)
640 }
641 Res::Def(DefKind::ForeignTy, did) => {
642 resolve_assoc_on_simple_type(tcx, did, item_ident, ns, module_id)
643 }
644 Res::Def(DefKind::Trait, did) => filter_assoc_items_by_name_and_namespace(
645 tcx,
646 did,
647 Ident::with_dummy_span(item_name),
648 ns,
649 )
650 .map(|item| (root_res, item.def_id))
651 .collect::<Vec<_>>(),
652 _ => Vec::new(),
653 }
654}
655
656fn is_assoc_item_on_alias_page<'tcx>(tcx: TyCtxt<'tcx>, assoc_did: DefId) -> bool {
659 match tcx.def_kind(assoc_did) {
660 DefKind::Variant | DefKind::Field => true,
662 _ => false,
663 }
664}
665
666fn resolve_assoc_on_primitive<'tcx>(
667 tcx: TyCtxt<'tcx>,
668 prim: PrimitiveType,
669 ns: Namespace,
670 item_ident: Ident,
671 module_id: ModId,
672) -> Vec<(Res, DefId)> {
673 let root_res = Res::Primitive(prim);
674 let items = resolve_primitive_inherent_assoc_item(tcx, prim, ns, item_ident);
675 if !items.is_empty() {
676 items
677 } else {
679 primitive_type_to_ty(tcx, prim)
680 .map(|ty| {
681 resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
682 .iter()
683 .map(|item| (root_res, item.def_id))
684 .collect::<Vec<_>>()
685 })
686 .unwrap_or_default()
687 }
688}
689
690fn resolve_assoc_on_adt<'tcx>(
691 tcx: TyCtxt<'tcx>,
692 adt_def_id: DefId,
693 item_ident: Ident,
694 ns: Namespace,
695 disambiguator: Option<Disambiguator>,
696 module_id: ModId,
697) -> Vec<(Res, DefId)> {
698 debug!("looking for associated item named {item_ident} for item {adt_def_id:?}");
699 let root_res = Res::from_def_id(tcx, adt_def_id);
700 let adt_ty = tcx.type_of(adt_def_id).instantiate_identity().skip_norm_wip();
701 let adt_def = adt_ty.ty_adt_def().expect("must be ADT");
702 if ns == TypeNS && adt_def.is_enum() {
704 for variant in adt_def.variants() {
705 if variant.name == item_ident.name {
706 return vec![(root_res, variant.def_id)];
707 }
708 }
709 }
710
711 if let Some(Disambiguator::Kind(DefKind::Field)) = disambiguator
712 && (adt_def.is_struct() || adt_def.is_union())
713 {
714 return resolve_structfield(adt_def, item_ident.name)
715 .into_iter()
716 .map(|did| (root_res, did))
717 .collect();
718 }
719
720 let assoc_items = resolve_assoc_on_simple_type(tcx, adt_def_id, item_ident, ns, module_id);
721 if !assoc_items.is_empty() {
722 return assoc_items;
723 }
724
725 if ns == Namespace::ValueNS && (adt_def.is_struct() || adt_def.is_union()) {
726 return resolve_structfield(adt_def, item_ident.name)
727 .into_iter()
728 .map(|did| (root_res, did))
729 .collect();
730 }
731
732 vec![]
733}
734
735fn resolve_assoc_on_simple_type<'tcx>(
737 tcx: TyCtxt<'tcx>,
738 ty_def_id: DefId,
739 item_ident: Ident,
740 ns: Namespace,
741 module_id: ModId,
742) -> Vec<(Res, DefId)> {
743 let root_res = Res::from_def_id(tcx, ty_def_id);
744 let inherent_assoc_items: Vec<_> = tcx
746 .inherent_impls(ty_def_id)
747 .iter()
748 .flat_map(|&imp| filter_assoc_items_by_name_and_namespace(tcx, imp, item_ident, ns))
749 .map(|item| (root_res, item.def_id))
750 .collect();
751 debug!("got inherent assoc items {inherent_assoc_items:?}");
752 if !inherent_assoc_items.is_empty() {
753 return inherent_assoc_items;
754 }
755
756 let ty = tcx.type_of(ty_def_id).instantiate_identity().skip_norm_wip();
762 let trait_assoc_items = resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
763 .into_iter()
764 .map(|item| (root_res, item.def_id))
765 .collect::<Vec<_>>();
766 debug!("got trait assoc items {trait_assoc_items:?}");
767 trait_assoc_items
768}
769
770fn resolve_structfield<'tcx>(adt_def: ty::AdtDef<'tcx>, item_name: Symbol) -> Option<DefId> {
771 debug!("looking for fields named {item_name} for {adt_def:?}");
772 adt_def
773 .non_enum_variant()
774 .fields
775 .iter()
776 .find(|field| field.name == item_name)
777 .map(|field| field.did)
778}
779
780fn resolve_associated_trait_item<'tcx>(
786 ty: Ty<'tcx>,
787 module: ModId,
788 item_ident: Ident,
789 ns: Namespace,
790 tcx: TyCtxt<'tcx>,
791) -> Vec<ty::AssocItem> {
792 let traits = trait_impls_for(tcx, ty, module);
799 debug!("considering traits {traits:?}");
800 let candidates = traits
801 .iter()
802 .flat_map(|&(impl_, trait_)| {
803 filter_assoc_items_by_name_and_namespace(tcx, trait_, item_ident, ns).map(
804 move |trait_assoc| {
805 trait_assoc_to_impl_assoc_item(tcx, impl_, trait_assoc.def_id)
806 .unwrap_or(*trait_assoc)
807 },
808 )
809 })
810 .collect::<Vec<_>>();
811 debug!("the candidates were {candidates:?}");
813 candidates
814}
815
816#[instrument(level = "debug", skip(tcx), ret)]
826fn trait_assoc_to_impl_assoc_item<'tcx>(
827 tcx: TyCtxt<'tcx>,
828 impl_id: DefId,
829 trait_assoc_id: DefId,
830) -> Option<ty::AssocItem> {
831 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
832 debug!(?trait_to_impl_assoc_map);
833 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
834 debug!(?impl_assoc_id);
835 Some(tcx.associated_item(impl_assoc_id))
836}
837
838#[instrument(level = "debug", skip(tcx))]
844fn trait_impls_for<'tcx>(
845 tcx: TyCtxt<'tcx>,
846 ty: Ty<'tcx>,
847 module: ModId,
848) -> FxIndexSet<(DefId, DefId)> {
849 let mut impls = FxIndexSet::default();
850
851 for &trait_ in tcx.doc_link_traits_in_scope(module) {
852 tcx.for_each_relevant_impl(trait_, ty, |impl_| {
853 let trait_ref = tcx.impl_trait_ref(impl_);
854 let impl_type = trait_ref.skip_binder().self_ty();
856 trace!(
857 "comparing type {impl_type} with kind {kind:?} against type {ty:?}",
858 kind = impl_type.kind(),
859 );
860 let saw_impl = impl_type == ty
866 || match (impl_type.kind(), ty.kind()) {
867 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
868 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
869 impl_def.did() == ty_def.did()
870 }
871 _ => false,
872 };
873
874 if saw_impl {
875 impls.insert((impl_, trait_));
876 }
877 });
878 }
879
880 impls
881}
882
883fn is_derive_trait_collision<T>(ns: &PerNS<Result<Vec<(Res, T)>, ResolutionFailure<'_>>>) -> bool {
887 if let (Ok(type_ns), Ok(macro_ns)) = (&ns.type_ns, &ns.macro_ns) {
888 type_ns.iter().any(|(res, _)| matches!(res, Res::Def(DefKind::Trait, _)))
889 && macro_ns.iter().any(|(res, _)| {
890 matches!(
891 res,
892 Res::Def(DefKind::Macro(kinds), _) if kinds.contains(MacroKinds::DERIVE)
893 )
894 })
895 } else {
896 false
897 }
898}
899
900impl DocVisitor<'_> for LinkCollector<'_, '_> {
901 fn visit_item(&mut self, item: &Item) {
902 self.resolve_links(item);
903 self.visit_item_recur(item)
904 }
905}
906
907enum PreprocessingError {
908 MultipleAnchors,
910 Disambiguator(MarkdownLinkRange, String),
911 MalformedGenerics(MalformedGenerics, String),
912}
913
914impl PreprocessingError {
915 fn report(&self, cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
916 match self {
917 PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info),
918 PreprocessingError::Disambiguator(range, msg) => {
919 disambiguator_error(cx, diag_info, range.clone(), msg.clone())
920 }
921 PreprocessingError::MalformedGenerics(err, path_str) => {
922 report_malformed_generics(cx, diag_info, *err, path_str)
923 }
924 }
925 }
926}
927
928#[derive(Clone)]
929struct PreprocessingInfo {
930 path_str: Box<str>,
931 disambiguator: Option<Disambiguator>,
932 extra_fragment: Option<String>,
933 link_text: Box<str>,
934}
935
936pub(crate) struct PreprocessedMarkdownLink(
938 Result<PreprocessingInfo, PreprocessingError>,
939 MarkdownLink,
940);
941
942fn preprocess_link(
949 ori_link: &MarkdownLink,
950 dox: &str,
951) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
952 let can_be_url = !matches!(
960 ori_link.kind,
961 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown | LinkType::ReferenceUnknown
962 );
963
964 if ori_link.link.is_empty() {
966 return None;
967 }
968
969 if can_be_url && ori_link.link.contains('/') {
971 return None;
972 }
973
974 let stripped = ori_link.link.replace('`', "");
975 let mut parts = stripped.split('#');
976
977 let link = parts.next().unwrap();
978 let link = link.trim();
979 if link.is_empty() {
980 return None;
982 }
983 let extra_fragment = parts.next();
984 if parts.next().is_some() {
985 return Some(Err(PreprocessingError::MultipleAnchors));
987 }
988
989 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
991 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
992 Ok(None) => (None, link, link),
993 Err((err_msg, relative_range)) => {
994 if !(can_be_url && should_ignore_link_with_disambiguators(link)) {
996 let disambiguator_range = match range_between_backticks(&ori_link.range, dox) {
997 MarkdownLinkRange::Destination(no_backticks_range) => {
998 MarkdownLinkRange::Destination(
999 (no_backticks_range.start + relative_range.start)
1000 ..(no_backticks_range.start + relative_range.end),
1001 )
1002 }
1003 mdlr @ MarkdownLinkRange::WholeLink(_) => mdlr,
1004 };
1005 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1006 } else {
1007 return None;
1008 }
1009 }
1010 };
1011
1012 let is_shortcut_style = ori_link.kind == LinkType::ShortcutUnknown;
1013 let ignore_urllike = can_be_url || (is_shortcut_style && !ori_link.link.contains('`'));
1030 if ignore_urllike && should_ignore_link(path_str) {
1031 return None;
1032 }
1033 if is_shortcut_style
1039 && let Some(suffix) = ori_link.link.strip_prefix('!')
1040 && !suffix.is_empty()
1041 && suffix.chars().all(|c| c.is_ascii_alphabetic())
1042 {
1043 return None;
1044 }
1045
1046 let path_str = match strip_generics_from_path(path_str) {
1048 Ok(path) => path,
1049 Err(err) => {
1050 debug!("link has malformed generics: {path_str}");
1051 return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
1052 }
1053 };
1054
1055 assert!(!path_str.contains(['<', '>'].as_slice()));
1057
1058 if path_str.contains(' ') {
1060 return None;
1061 }
1062
1063 Some(Ok(PreprocessingInfo {
1064 path_str,
1065 disambiguator,
1066 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1067 link_text: Box::<str>::from(link_text),
1068 }))
1069}
1070
1071fn preprocessed_markdown_links(s: &str) -> Vec<PreprocessedMarkdownLink> {
1072 markdown_links(s, |link| {
1073 preprocess_link(&link, s).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1074 })
1075}
1076
1077impl LinkCollector<'_, '_> {
1078 #[instrument(level = "debug", skip_all)]
1079 fn resolve_links(&mut self, item: &Item) {
1080 let tcx = self.cx.tcx;
1081 let document_private = self.cx.document_private();
1082 let effective_visibilities = tcx.effective_visibilities(());
1083 let should_skip_link_resolution = |item_id: DefId| {
1084 !document_private
1085 && item_id
1086 .as_local()
1087 .is_some_and(|local_def_id| !effective_visibilities.is_exported(local_def_id))
1088 && !has_primitive_or_keyword_or_attribute_docs(&item.attrs.other_attrs)
1089 };
1090
1091 if let Some(def_id) = item.item_id.as_def_id()
1092 && should_skip_link_resolution(def_id)
1093 {
1094 return;
1096 }
1097
1098 let mut try_insert_links = |item_id, doc: &str| {
1099 if should_skip_link_resolution(item_id) {
1100 return;
1101 }
1102 let module_id = match tcx.def_kind(item_id) {
1103 DefKind::Mod if item.inner_docs(tcx) => ModId::new_unchecked(item_id),
1104 _ => find_nearest_parent_module(tcx, item_id).unwrap(),
1105 };
1106 for md_link in preprocessed_markdown_links(&doc) {
1107 let link = self.resolve_link(&doc, item, item_id, module_id, &md_link);
1108 if let Some(link) = link {
1109 self.cx
1110 .cache
1111 .intra_doc_links
1112 .entry(item.item_or_reexport_id())
1113 .or_default()
1114 .insert(link);
1115 }
1116 }
1117 };
1118
1119 for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
1124 if !may_have_doc_links(&doc) {
1125 continue;
1126 }
1127
1128 debug!("combined_docs={doc}");
1129 let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
1132 try_insert_links(item_id, &doc)
1133 }
1134
1135 for attr in &item.attrs.other_attrs {
1137 let Attribute::Parsed(AttributeKind::Deprecated { span: depr_span, deprecation }) =
1138 attr
1139 else {
1140 continue;
1141 };
1142 let Some(note_sym) = deprecation.note else { continue };
1143 let note = note_sym.as_str();
1144
1145 if !may_have_doc_links(note) {
1146 continue;
1147 }
1148
1149 debug!("deprecated_note={note}");
1150 let item_id = if let Some(inline_stmt_id) = item.inline_stmt_id {
1155 let target_def_id = item.item_id.expect_def_id();
1156 reexport_chain(tcx, inline_stmt_id, target_def_id)
1157 .iter()
1158 .flat_map(|reexport| reexport.id())
1159 .find(|&reexport_def_id| {
1160 find_attr!(
1161 tcx,
1162 reexport_def_id,
1163 Deprecated { span, .. } if span == depr_span
1164 )
1165 })
1166 .unwrap_or(target_def_id)
1167 } else {
1168 item.item_id.expect_def_id()
1169 };
1170 try_insert_links(item_id, note)
1171 }
1172 }
1173
1174 pub(crate) fn save_link(&mut self, item_id: ItemId, link: ItemLink) {
1175 self.cx.cache.intra_doc_links.entry(item_id).or_default().insert(link);
1176 }
1177
1178 fn resolve_link(
1180 &mut self,
1181 dox: &str,
1182 item: &Item,
1183 item_id: DefId,
1184 module_id: ModId,
1185 PreprocessedMarkdownLink(pp_link, ori_link): &PreprocessedMarkdownLink,
1186 ) -> Option<ItemLink> {
1187 trace!("considering link '{}'", ori_link.link);
1188
1189 let diag_info = DiagnosticInfo {
1190 item,
1191 dox,
1192 ori_link: &ori_link.link,
1193 link_range: ori_link.range.clone(),
1194 };
1195 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1196 pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1197 let disambiguator = *disambiguator;
1198
1199 let mut resolved = self.resolve_with_disambiguator_cached(
1200 ResolutionInfo {
1201 item_id,
1202 module_id,
1203 dis: disambiguator,
1204 path_str: path_str.clone(),
1205 extra_fragment: extra_fragment.clone(),
1206 },
1207 diag_info.clone(), matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1212 )?;
1213
1214 if resolved.len() > 1 {
1215 let links = AmbiguousLinks {
1216 link_text: link_text.clone(),
1217 diag_info: diag_info.into(),
1218 resolved,
1219 };
1220
1221 self.links
1222 .ambiguous
1223 .entry((item.item_id, path_str.to_string()))
1224 .or_default()
1225 .push(links);
1226 None
1227 } else if let Some((res, fragment)) = resolved.pop() {
1228 self.compute_link(res, fragment, path_str, disambiguator, diag_info, link_text)
1229 } else {
1230 None
1231 }
1232 }
1233
1234 fn validate_link(&self, original_did: DefId) -> bool {
1243 let tcx = self.cx.tcx;
1244 let def_kind = tcx.def_kind(original_did);
1245 let did = match def_kind {
1246 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst { .. } | DefKind::Variant => {
1247 tcx.parent(original_did)
1249 }
1250 DefKind::Ctor(..) => return self.validate_link(tcx.parent(original_did)),
1253 DefKind::ExternCrate => {
1254 if let Some(local_did) = original_did.as_local() {
1256 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
1257 } else {
1258 original_did
1259 }
1260 }
1261 _ => original_did,
1262 };
1263
1264 let cache = &self.cx.cache;
1265 if !original_did.is_local()
1266 && !cache.effective_visibilities.is_directly_public(tcx, did)
1267 && !cache.document_private
1268 && !cache.primitive_locations.values().any(|&id| id == did)
1269 {
1270 return false;
1271 }
1272
1273 cache.paths.get(&did).is_some()
1274 || cache.external_paths.contains_key(&did)
1275 || !did.is_local()
1276 }
1277
1278 fn resolve_ambiguities(&mut self) {
1279 let mut ambiguous_links = mem::take(&mut self.links.ambiguous);
1280 for ((item_id, path_str), info_items) in ambiguous_links.iter_mut() {
1281 for info in info_items {
1282 info.resolved.retain(|(res, _)| match res {
1283 Res::Def(_, def_id) => self.validate_link(*def_id),
1284 Res::Primitive(_) => true,
1286 });
1287 let diag_info = info.diag_info.as_info();
1288 match info.resolved.len() {
1289 1 => {
1290 let (res, fragment) = info.resolved.pop().unwrap();
1291 if let Some(link) = self.compute_link(
1292 res,
1293 fragment,
1294 path_str,
1295 None,
1296 diag_info,
1297 &info.link_text,
1298 ) {
1299 self.save_link(*item_id, link);
1300 }
1301 }
1302 0 => {
1303 report_diagnostic(
1304 self.cx.tcx,
1305 BROKEN_INTRA_DOC_LINKS,
1306 format!("all items matching `{path_str}` are private or doc(hidden)"),
1307 &diag_info,
1308 |diag, sp, _| {
1309 if let Some(sp) = sp {
1310 diag.span_label(sp, "unresolved link");
1311 } else {
1312 diag.note("unresolved link");
1313 }
1314 },
1315 );
1316 }
1317 _ => {
1318 let candidates = info
1319 .resolved
1320 .iter()
1321 .map(|(res, fragment)| {
1322 let def_id = if let Some(UrlFragment::Item(def_id)) = fragment {
1323 Some(*def_id)
1324 } else {
1325 None
1326 };
1327 (*res, def_id)
1328 })
1329 .collect::<Vec<_>>();
1330 ambiguity_error(self.cx, &diag_info, path_str, &candidates, true);
1331 }
1332 }
1333 }
1334 }
1335 }
1336
1337 fn compute_link(
1338 &mut self,
1339 mut res: Res,
1340 fragment: Option<UrlFragment>,
1341 path_str: &str,
1342 disambiguator: Option<Disambiguator>,
1343 diag_info: DiagnosticInfo<'_>,
1344 link_text: &Box<str>,
1345 ) -> Option<ItemLink> {
1346 if matches!(
1350 disambiguator,
1351 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1352 ) && !matches!(res, Res::Primitive(_))
1353 && let Some(prim) = resolve_primitive(path_str, TypeNS)
1354 {
1355 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1357 res = prim;
1358 } else {
1359 let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)];
1361 ambiguity_error(self.cx, &diag_info, path_str, candidates, true);
1362 return None;
1363 }
1364 }
1365
1366 match res {
1367 Res::Primitive(_) => {
1368 if let Some(UrlFragment::Item(id)) = fragment {
1369 let kind = self.cx.tcx.def_kind(id);
1378 self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1379 } else {
1380 match disambiguator {
1381 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1382 Some(other) => {
1383 self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1384 return None;
1385 }
1386 }
1387 }
1388
1389 res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1390 link: Box::<str>::from(diag_info.ori_link),
1391 link_text: link_text.clone(),
1392 page_id,
1393 fragment,
1394 })
1395 }
1396 Res::Def(kind, id) => {
1397 let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1398 (self.cx.tcx.def_kind(id), id)
1399 } else {
1400 (kind, id)
1401 };
1402 self.verify_disambiguator(
1403 path_str,
1404 kind_for_dis,
1405 id_for_dis,
1406 disambiguator,
1407 &diag_info,
1408 )?;
1409
1410 let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1411 Some(ItemLink {
1412 link: Box::<str>::from(diag_info.ori_link),
1413 link_text: link_text.clone(),
1414 page_id,
1415 fragment,
1416 })
1417 }
1418 }
1419 }
1420
1421 fn verify_disambiguator(
1422 &self,
1423 path_str: &str,
1424 kind: DefKind,
1425 id: DefId,
1426 disambiguator: Option<Disambiguator>,
1427 diag_info: &DiagnosticInfo<'_>,
1428 ) -> Option<()> {
1429 debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1430
1431 debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1433 match (kind, disambiguator) {
1434 | (
1435 DefKind::Const { .. }
1436 | DefKind::ConstParam
1437 | DefKind::AssocConst { .. }
1438 | DefKind::AnonConst,
1439 Some(Disambiguator::Kind(DefKind::Const { .. })),
1440 )
1441 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1444 | (_, Some(Disambiguator::Namespace(_)))
1446 | (_, None)
1448 => {}
1450 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1451 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1452 self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1453 return None;
1454 }
1455 }
1456
1457 if let Some(dst_id) = id.as_local()
1459 && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1460 && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1461 && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1462 {
1463 privacy_error(self.cx, diag_info, path_str);
1464 }
1465
1466 Some(())
1467 }
1468
1469 fn report_disambiguator_mismatch(
1470 &self,
1471 path_str: &str,
1472 specified: Disambiguator,
1473 resolved: Res,
1474 diag_info: &DiagnosticInfo<'_>,
1475 ) {
1476 let msg = format!("incompatible link kind for `{path_str}`");
1478 let callback = |diag: &mut Diag<'_, ()>, sp: Option<rustc_span::Span>, link_range| {
1479 let note = format!(
1480 "this link resolved to {} {}, which is not {} {}",
1481 resolved.article(),
1482 resolved.descr(),
1483 specified.article(),
1484 specified.descr(),
1485 );
1486 if let Some(sp) = sp {
1487 diag.span_label(sp, note);
1488 } else {
1489 diag.note(note);
1490 }
1491 suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1492 };
1493 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1494 }
1495
1496 fn report_rawptr_assoc_feature_gate(
1497 &self,
1498 dox: &str,
1499 ori_link: &MarkdownLinkRange,
1500 item: &Item,
1501 ) {
1502 let span = match source_span_for_markdown_range(
1503 self.cx.tcx,
1504 dox,
1505 ori_link.inner_range(),
1506 &item.attrs.doc_strings,
1507 ) {
1508 Some((sp, _)) => sp,
1509 None => item.attr_span(self.cx.tcx),
1510 };
1511 rustc_session::diagnostics::feature_err(
1512 self.cx.tcx.sess,
1513 sym::intra_doc_pointers,
1514 span,
1515 "linking to associated items of raw pointers is experimental",
1516 )
1517 .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1518 .emit();
1519 }
1520
1521 fn resolve_with_disambiguator_cached(
1522 &mut self,
1523 key: ResolutionInfo,
1524 diag: DiagnosticInfo<'_>,
1525 cache_errors: bool,
1528 ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1529 if let Some(res) = self.links.visited.get(&key)
1530 && (res.is_some() || cache_errors)
1531 {
1532 return res.clone().map(|r| vec![r]);
1533 }
1534
1535 let mut candidates = self.resolve_with_disambiguator(&key, diag.clone());
1536
1537 if let Some(candidate) = candidates.first()
1540 && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1541 && key.path_str.contains("::")
1542 {
1544 if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1545 self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1546 return None;
1547 } else {
1548 candidates = vec![*candidate];
1549 }
1550 }
1551
1552 if let [candidate, _candidate2, ..] = *candidates
1557 && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1558 {
1559 candidates = vec![candidate];
1560 }
1561
1562 let mut out = Vec::with_capacity(candidates.len());
1563 for (res, def_id) in candidates {
1564 let fragment = match (&key.extra_fragment, def_id) {
1565 (Some(_), Some(def_id)) => {
1566 report_anchor_conflict(self.cx, diag, def_id);
1567 return None;
1568 }
1569 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1570 (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1571 (None, None) => None,
1572 };
1573 out.push((res, fragment));
1574 }
1575 if let [r] = out.as_slice() {
1576 self.links.visited.insert(key, Some(r.clone()));
1577 } else if cache_errors {
1578 self.links.visited.insert(key, None);
1579 }
1580 Some(out)
1581 }
1582
1583 fn resolve_with_disambiguator(
1585 &mut self,
1586 key: &ResolutionInfo,
1587 diag: DiagnosticInfo<'_>,
1588 ) -> Vec<(Res, Option<DefId>)> {
1589 let disambiguator = key.dis;
1590 let path_str = &key.path_str;
1591 let item_id = key.item_id;
1592 let module_id = key.module_id;
1593
1594 match disambiguator.map(Disambiguator::ns) {
1595 Some(expected_ns) => {
1596 match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1597 Ok(candidates) => candidates,
1598 Err(err) => {
1599 let mut err = ResolutionFailure::NotResolved(err);
1603 for other_ns in [TypeNS, ValueNS, MacroNS] {
1604 if other_ns != expected_ns
1605 && let Ok(&[res, ..]) = self
1606 .resolve(path_str, other_ns, None, item_id, module_id)
1607 .as_deref()
1608 {
1609 err = ResolutionFailure::WrongNamespace {
1610 res: full_res(self.cx.tcx, res),
1611 expected_ns,
1612 };
1613 break;
1614 }
1615 }
1616 resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1617 vec![]
1618 }
1619 }
1620 }
1621 None => {
1622 let candidate = |ns| {
1624 self.resolve(path_str, ns, None, item_id, module_id)
1625 .map_err(ResolutionFailure::NotResolved)
1626 };
1627
1628 let candidates = PerNS {
1629 macro_ns: candidate(MacroNS),
1630 type_ns: candidate(TypeNS),
1631 value_ns: candidate(ValueNS).and_then(|v_res| {
1632 for (res, _) in v_res.iter() {
1633 if let Res::Def(DefKind::Ctor(..), _) = res {
1635 return Err(ResolutionFailure::WrongNamespace {
1636 res: *res,
1637 expected_ns: TypeNS,
1638 });
1639 }
1640 }
1641 Ok(v_res)
1642 }),
1643 };
1644
1645 let len = candidates
1646 .iter()
1647 .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1648
1649 if len == 0 {
1650 resolution_failure(
1651 self,
1652 diag,
1653 path_str,
1654 disambiguator,
1655 candidates.into_iter().filter_map(|res| res.err()).collect(),
1656 );
1657 vec![]
1658 } else if len == 1 {
1659 candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1660 } else {
1661 let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1662 if len == 2 && has_derive_trait_collision {
1663 candidates.type_ns.unwrap()
1664 } else {
1665 let mut candidates = candidates.map(|candidate| candidate.ok());
1667 if has_derive_trait_collision {
1669 candidates.macro_ns = None;
1670 }
1671 candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1672 }
1673 }
1674 }
1675 }
1676 }
1677}
1678
1679fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1691 let range = match ori_link_range {
1692 mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1693 MarkdownLinkRange::Destination(inner) => inner.clone(),
1694 };
1695 let ori_link_text = &dox[range.clone()];
1696 let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1697 let before_second_backtick_group = ori_link_text
1698 .bytes()
1699 .skip(after_first_backtick_group)
1700 .position(|b| b == b'`')
1701 .unwrap_or(ori_link_text.len());
1702 MarkdownLinkRange::Destination(
1703 (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1704 )
1705}
1706
1707fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1714 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1715}
1716
1717fn should_ignore_link(path_str: &str) -> bool {
1720 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1721}
1722
1723#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1724enum Disambiguator {
1726 Primitive,
1730 Kind(DefKind),
1732 Namespace(Namespace),
1734}
1735
1736impl Disambiguator {
1737 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1743 use Disambiguator::{Kind, Namespace as NS, Primitive};
1744
1745 let suffixes = [
1746 ("!()", DefKind::Macro(MacroKinds::BANG)),
1748 ("!{}", DefKind::Macro(MacroKinds::BANG)),
1749 ("![]", DefKind::Macro(MacroKinds::BANG)),
1750 ("()", DefKind::Fn),
1751 ("!", DefKind::Macro(MacroKinds::BANG)),
1752 ];
1753
1754 if let Some(idx) = link.find('@') {
1755 let (prefix, rest) = link.split_at(idx);
1756 let d = match prefix {
1757 "struct" => Kind(DefKind::Struct),
1759 "enum" => Kind(DefKind::Enum),
1760 "trait" => Kind(DefKind::Trait),
1761 "union" => Kind(DefKind::Union),
1762 "module" | "mod" => Kind(DefKind::Mod),
1763 "const" | "constant" => Kind(DefKind::Const { is_type_const: false }),
1764 "static" => Kind(DefKind::Static {
1765 mutability: Mutability::Not,
1766 nested: false,
1767 safety: Safety::Safe,
1768 }),
1769 "function" | "fn" | "method" => Kind(DefKind::Fn),
1770 "derive" => Kind(DefKind::Macro(MacroKinds::DERIVE)),
1771 "field" => Kind(DefKind::Field),
1772 "variant" => Kind(DefKind::Variant),
1773 "type" => NS(Namespace::TypeNS),
1774 "value" => NS(Namespace::ValueNS),
1775 "macro" => NS(Namespace::MacroNS),
1776 "prim" | "primitive" => Primitive,
1777 "tyalias" | "typealias" => Kind(DefKind::TyAlias),
1778 _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1779 };
1780
1781 for (suffix, kind) in suffixes {
1782 if let Some(path_str) = rest.strip_suffix(suffix) {
1783 if d.ns() != Kind(kind).ns() {
1784 return Err((
1785 format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1786 0..idx,
1787 ));
1788 } else if path_str.len() > 1 {
1789 return Ok(Some((d, &path_str[1..], &rest[1..])));
1791 }
1792 }
1793 }
1794
1795 Ok(Some((d, &rest[1..], &rest[1..])))
1796 } else {
1797 for (suffix, kind) in suffixes {
1798 if let Some(path_str) = link.strip_suffix(suffix)
1800 && !path_str.is_empty()
1801 {
1802 return Ok(Some((Kind(kind), path_str, link)));
1803 }
1804 }
1805 Ok(None)
1806 }
1807 }
1808
1809 fn ns(self) -> Namespace {
1810 match self {
1811 Self::Namespace(n) => n,
1812 Self::Kind(DefKind::Field) => ValueNS,
1814 Self::Kind(k) => {
1815 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1816 }
1817 Self::Primitive => TypeNS,
1818 }
1819 }
1820
1821 fn article(self) -> &'static str {
1822 match self {
1823 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1824 Self::Kind(k) => k.article(),
1825 Self::Primitive => "a",
1826 }
1827 }
1828
1829 fn descr(self) -> &'static str {
1830 match self {
1831 Self::Namespace(n) => n.descr(),
1832 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1835 Self::Primitive => "builtin type",
1836 }
1837 }
1838}
1839
1840enum Suggestion {
1842 Prefix(&'static str),
1844 Function,
1846 Macro,
1848}
1849
1850impl Suggestion {
1851 fn descr(&self) -> Cow<'static, str> {
1852 match self {
1853 Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1854 Self::Function => "add parentheses".into(),
1855 Self::Macro => "add an exclamation mark".into(),
1856 }
1857 }
1858
1859 fn as_help(&self, path_str: &str) -> String {
1860 match self {
1862 Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1863 Self::Function => format!("{path_str}()"),
1864 Self::Macro => format!("{path_str}!"),
1865 }
1866 }
1867
1868 fn as_help_span(
1869 &self,
1870 ori_link: &str,
1871 sp: rustc_span::Span,
1872 ) -> Vec<(rustc_span::Span, String)> {
1873 let inner_sp = match ori_link.find('(') {
1874 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1875 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1876 }
1877 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1878 None => sp,
1879 };
1880 let inner_sp = match ori_link.find('!') {
1881 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1882 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1883 }
1884 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1885 None => inner_sp,
1886 };
1887 let inner_sp = match ori_link.find('@') {
1888 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1889 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1890 }
1891 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1892 None => inner_sp,
1893 };
1894 match self {
1895 Self::Prefix(prefix) => {
1896 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
1898 if sp.hi() != inner_sp.hi() {
1899 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1900 }
1901 sugg
1902 }
1903 Self::Function => {
1904 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1905 if sp.lo() != inner_sp.lo() {
1906 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1907 }
1908 sugg
1909 }
1910 Self::Macro => {
1911 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1912 if sp.lo() != inner_sp.lo() {
1913 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1914 }
1915 sugg
1916 }
1917 }
1918 }
1919}
1920
1921fn report_diagnostic(
1932 tcx: TyCtxt<'_>,
1933 lint: &'static Lint,
1934 msg: impl Into<DiagMessage> + Display,
1935 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1936 decorate: impl FnOnce(&mut Diag<'_, ()>, Option<rustc_span::Span>, MarkdownLinkRange),
1937) {
1938 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
1939 info!("ignoring warning from parent crate: {msg}");
1941 return;
1942 };
1943
1944 let sp = item.attr_span(tcx);
1945
1946 tcx.emit_node_span_lint(
1947 lint,
1948 hir_id,
1949 sp,
1950 rustc_errors::DiagDecorator(|lint| {
1951 lint.primary_message(msg);
1952
1953 let (span, link_range) = match link_range {
1954 MarkdownLinkRange::Destination(md_range) => {
1955 let mut md_range = md_range.clone();
1956 let sp = source_span_for_markdown_range(
1957 tcx,
1958 dox,
1959 &md_range,
1960 &item.attrs.doc_strings,
1961 )
1962 .map(|(mut sp, _)| {
1963 while dox.as_bytes().get(md_range.start) == Some(&b' ')
1964 || dox.as_bytes().get(md_range.start) == Some(&b'`')
1965 {
1966 md_range.start += 1;
1967 sp = sp.with_lo(sp.lo() + BytePos(1));
1968 }
1969 while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
1970 || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
1971 {
1972 md_range.end -= 1;
1973 sp = sp.with_hi(sp.hi() - BytePos(1));
1974 }
1975 sp
1976 });
1977 (sp, MarkdownLinkRange::Destination(md_range))
1978 }
1979 MarkdownLinkRange::WholeLink(md_range) => (
1980 source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
1981 .map(|(sp, _)| sp),
1982 link_range.clone(),
1983 ),
1984 };
1985
1986 if let Some(sp) = span {
1987 lint.span(sp);
1988 } else {
1989 let md_range = link_range.inner_range().clone();
1994 let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
1995 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1996
1997 lint.note(format!(
1999 "the link appears in this line:\n\n{line}\n\
2000 {indicator: <before$}{indicator:^<found$}",
2001 indicator = "",
2002 before = md_range.start - last_new_line_offset,
2003 found = md_range.len(),
2004 ));
2005 }
2006
2007 decorate(lint, span, link_range);
2008 }),
2009 );
2010}
2011
2012fn suggest_path_name_typo(
2013 collector: &LinkCollector<'_, '_>,
2014 diag: &mut Diag<'_, ()>,
2015 span: Option<rustc_span::Span>,
2016 link_range: &MarkdownLinkRange,
2017 dox: &str,
2018 module: ModId,
2019 unresolved: &str,
2020 has_partial_res: bool,
2021 disambiguator: Option<Disambiguator>,
2022) {
2023 if unresolved.chars().count() <= 1 {
2024 return;
2026 }
2027
2028 let tcx = collector.cx.tcx;
2029 let lookup = Symbol::intern(unresolved);
2030 let children = if let Some(local_module) = module.as_local() {
2031 tcx.module_children_local(local_module.to_local_def_id())
2032 } else {
2033 tcx.module_children(module.to_def_id())
2034 };
2035 let candidates = children
2036 .iter()
2037 .filter(|child| {
2038 disambiguator.is_none_or(|disambiguator| child.res.matches_ns(disambiguator.ns()))
2039 })
2040 .map(|child| child.ident.name)
2041 .filter(|&name| name != lookup)
2042 .collect::<Vec<_>>();
2043 let Some(candidate) = find_best_match_for_name(&candidates, lookup, None) else {
2044 return;
2045 };
2046
2047 let msg = format!("there's a similarly named item `{candidate}`");
2048 if let (Some(span), MarkdownLinkRange::Destination(range)) = (span, link_range) {
2049 let link = &dox[range.clone()];
2050 let start = if has_partial_res { link.rfind(unresolved) } else { link.find(unresolved) };
2052 if let Some(start) = start {
2053 let mut suggestion = link.to_owned();
2054 suggestion.replace_range(start..start + unresolved.len(), candidate.as_str());
2055 diag.span_suggestion_verbose(span, msg, suggestion, Applicability::MaybeIncorrect);
2056 return;
2057 }
2058 }
2059 diag.help(msg);
2060}
2061
2062fn resolution_failure(
2068 collector: &LinkCollector<'_, '_>,
2069 diag_info: DiagnosticInfo<'_>,
2070 path_str: &str,
2071 disambiguator: Option<Disambiguator>,
2072 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
2073) {
2074 let tcx = collector.cx.tcx;
2075 report_diagnostic(
2076 tcx,
2077 BROKEN_INTRA_DOC_LINKS,
2078 format!("unresolved link to `{path_str}`"),
2079 &diag_info,
2080 |diag, sp, link_range| {
2081 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
2082 let assoc_item_not_allowed = |res: Res| {
2083 let name = res.name(tcx);
2084 format!(
2085 "`{name}` is {} {}, not a module or type, and cannot have associated items",
2086 res.article(),
2087 res.descr()
2088 )
2089 };
2090 let mut variants_seen =
2092 SmallVec::<[_; const { mem::variant_count::<ResolutionFailure<'_>>() }]>::new();
2093 for mut failure in kinds {
2094 let variant = mem::discriminant(&failure);
2095 if variants_seen.contains(&variant) {
2096 continue;
2097 }
2098 variants_seen.push(variant);
2099
2100 if let ResolutionFailure::NotResolved(UnresolvedPath {
2101 item_id,
2102 module_id,
2103 partial_res,
2104 unresolved,
2105 }) = &mut failure
2106 {
2107 use DefKind::*;
2108
2109 let item_id = *item_id;
2110 let module_id = *module_id;
2111
2112 let mut path_is_invalid = false;
2120 let is_invalid_segment =
2121 |segment: &str| segment.is_empty() || segment.contains(':');
2122
2123 let mut name = path_str;
2124 'outer: loop {
2125 let Some((start, end)) = name.rsplit_once("::") else {
2127 if is_invalid_segment(name) {
2130 path_is_invalid = true;
2131 break;
2132 }
2133 if partial_res.is_none() {
2134 *unresolved = name.into();
2135 }
2137 break;
2138 };
2139 if is_invalid_segment(end) {
2140 path_is_invalid = true;
2143 break;
2144 }
2145 for ns in [TypeNS, ValueNS, MacroNS] {
2146 if let Ok(v_res) =
2147 collector.resolve(start, ns, None, item_id, module_id)
2148 {
2149 debug!("found partial_res={v_res:?}");
2150 if let Some(&res) = v_res.first() {
2151 *partial_res = Some(full_res(tcx, res));
2152 *unresolved = end.into();
2153 break 'outer;
2154 }
2155 }
2156 }
2157 if start.is_empty() && partial_res.is_none() {
2158 *unresolved = end.into();
2161 break;
2162 }
2163 name = start;
2164 }
2165
2166 let last_found_module = match *partial_res {
2167 Some(Res::Def(DefKind::Mod, id)) => Some(ModId::new_unchecked(id)),
2168 None => Some(module_id),
2169 _ => None,
2170 };
2171 if let Some(module) = last_found_module {
2173 let note = if path_is_invalid {
2174 "invalid path separator".into()
2175 } else if partial_res.is_some() {
2176 let module_name = tcx.item_name(module);
2178 format!("no item named `{unresolved}` in module `{module_name}`")
2179 } else {
2180 format!("no item named `{unresolved}` in scope")
2182 };
2183 if let Some(span) = sp {
2184 diag.span_label(span, note);
2185 } else {
2186 diag.note(note);
2187 }
2188
2189 if !path_is_invalid {
2190 suggest_path_name_typo(
2191 collector,
2192 diag,
2193 sp,
2194 &link_range,
2195 diag_info.dox,
2196 module,
2197 unresolved,
2198 partial_res.is_some(),
2199 disambiguator,
2200 );
2201 }
2202
2203 if !path_str.contains("::") {
2204 if disambiguator.is_none_or(|d| d.ns() == MacroNS)
2205 && collector
2206 .cx
2207 .tcx
2208 .resolutions(())
2209 .all_macro_rules
2210 .contains(&Symbol::intern(path_str))
2211 {
2212 diag.note(format!(
2213 "`macro_rules` named `{path_str}` exists in this crate, \
2214 but it is not in scope at this link's location"
2215 ));
2216 } else {
2217 diag.help(
2220 "to escape `[` and `]` characters, \
2221 add '\\' before them like `\\[` or `\\]`",
2222 );
2223 }
2224 }
2225
2226 continue;
2227 }
2228
2229 let res = partial_res.expect("None case was handled by `last_found_module`");
2231 let kind_did = match res {
2232 Res::Def(kind, did) => Some((kind, did)),
2233 Res::Primitive(_) => None,
2234 };
2235 let is_struct_variant = |did| {
2236 if let ty::Adt(def, _) =
2237 tcx.type_of(did).instantiate_identity().skip_norm_wip().kind()
2238 && def.is_enum()
2239 && let Some(variant) =
2240 def.variants().iter().find(|v| v.name == res.name(tcx))
2241 {
2242 variant.ctor.is_none()
2244 } else {
2245 false
2246 }
2247 };
2248 let path_description = if let Some((kind, did)) = kind_did {
2249 match kind {
2250 Mod | ForeignMod => "inner item",
2251 Struct => "field or associated item",
2252 Enum | Union => "variant or associated item",
2253 Variant if is_struct_variant(did) => {
2254 let variant = res.name(tcx);
2255 let note = format!("variant `{variant}` has no such field");
2256 if let Some(span) = sp {
2257 diag.span_label(span, note);
2258 } else {
2259 diag.note(note);
2260 }
2261 return;
2262 }
2263 Variant
2264 | Field
2265 | Closure
2266 | AssocTy
2267 | AssocConst { .. }
2268 | AssocFn
2269 | Fn
2270 | Macro(_)
2271 | Const { .. }
2272 | ConstParam
2273 | ExternCrate
2274 | Use
2275 | LifetimeParam
2276 | Ctor(_, _)
2277 | AnonConst => {
2278 let note = assoc_item_not_allowed(res);
2279 if let Some(span) = sp {
2280 diag.span_label(span, note);
2281 } else {
2282 diag.note(note);
2283 }
2284 return;
2285 }
2286 Trait
2287 | TyAlias
2288 | ForeignTy
2289 | OpaqueTy
2290 | TraitAlias
2291 | TyParam
2292 | Static { .. } => "associated item",
2293 Impl { .. }
2294 | GlobalAsm
2295 | SyntheticCoroutineBody
2296 | TestBinderConstraints => {
2297 unreachable!("not a path")
2298 }
2299 }
2300 } else {
2301 "associated item"
2302 };
2303 let name = res.name(tcx);
2304 let note = format!(
2305 "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2306 res = res.descr(),
2307 disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2308 );
2309 if let Some(span) = sp {
2310 diag.span_label(span, note);
2311 } else {
2312 diag.note(note);
2313 }
2314
2315 continue;
2316 }
2317 let note = match failure {
2318 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2319 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2320 suggest_disambiguator(
2321 res,
2322 diag,
2323 path_str,
2324 link_range.clone(),
2325 sp,
2326 &diag_info,
2327 );
2328
2329 if let Some(disambiguator) = disambiguator
2330 && !matches!(disambiguator, Disambiguator::Namespace(..))
2331 {
2332 format!(
2333 "this link resolves to {}, which is not {} {}",
2334 item(res),
2335 disambiguator.article(),
2336 disambiguator.descr()
2337 )
2338 } else {
2339 format!(
2340 "this link resolves to {}, which is not in the {} namespace",
2341 item(res),
2342 expected_ns.descr()
2343 )
2344 }
2345 }
2346 };
2347 if let Some(span) = sp {
2348 diag.span_label(span, note);
2349 } else {
2350 diag.note(note);
2351 }
2352 }
2353 },
2354 );
2355}
2356
2357fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2358 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2359 anchor_failure(cx, diag_info, msg, 1)
2360}
2361
2362fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2363 let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2364 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2365 anchor_failure(cx, diag_info, msg, 0)
2366}
2367
2368fn anchor_failure(
2370 cx: &DocContext<'_>,
2371 diag_info: DiagnosticInfo<'_>,
2372 msg: String,
2373 anchor_idx: usize,
2374) {
2375 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2376 if let Some(mut sp) = sp {
2377 if let Some((fragment_offset, _)) =
2378 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2379 {
2380 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2381 }
2382 diag.span_label(sp, "invalid anchor");
2383 }
2384 });
2385}
2386
2387fn disambiguator_error(
2389 cx: &DocContext<'_>,
2390 mut diag_info: DiagnosticInfo<'_>,
2391 disambiguator_range: MarkdownLinkRange,
2392 msg: impl Into<DiagMessage> + Display,
2393) {
2394 diag_info.link_range = disambiguator_range;
2395 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2396 let msg = format!(
2397 "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2398 crate::DOC_RUST_LANG_ORG_VERSION
2399 );
2400 diag.note(msg);
2401 });
2402}
2403
2404fn report_malformed_generics(
2405 cx: &DocContext<'_>,
2406 diag_info: DiagnosticInfo<'_>,
2407 err: MalformedGenerics,
2408 path_str: &str,
2409) {
2410 report_diagnostic(
2411 cx.tcx,
2412 BROKEN_INTRA_DOC_LINKS,
2413 format!("unresolved link to `{path_str}`"),
2414 &diag_info,
2415 |diag, sp, _link_range| {
2416 let note = match err {
2417 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2418 MalformedGenerics::MissingType => "missing type for generic parameters",
2419 MalformedGenerics::HasFullyQualifiedSyntax => {
2420 diag.note(
2421 "see https://github.com/rust-lang/rust/issues/74563 for more information",
2422 );
2423 "fully-qualified syntax is unsupported"
2424 }
2425 MalformedGenerics::InvalidPathSeparator => "invalid path separator",
2426 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2427 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2428 };
2429 if let Some(span) = sp {
2430 diag.span_label(span, note);
2431 } else {
2432 diag.note(note);
2433 }
2434 },
2435 );
2436}
2437
2438fn ambiguity_error(
2444 cx: &DocContext<'_>,
2445 diag_info: &DiagnosticInfo<'_>,
2446 path_str: &str,
2447 candidates: &[(Res, Option<DefId>)],
2448 emit_error: bool,
2449) -> bool {
2450 let mut descrs = FxHashSet::default();
2451 let mut possible_proc_macro_id = None;
2454 let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro];
2455 let mut kinds = candidates
2456 .iter()
2457 .map(|(res, def_id)| {
2458 let r =
2459 if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2460 if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2461 possible_proc_macro_id = Some(id);
2462 }
2463 r
2464 })
2465 .collect::<Vec<_>>();
2466 if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2475 kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2476 }
2477
2478 kinds.retain(|res| descrs.insert(res.descr()));
2479
2480 if descrs.len() == 1 {
2481 return false;
2484 } else if !emit_error {
2485 return true;
2486 }
2487
2488 let mut msg = format!("`{path_str}` is ");
2489 match kinds.as_slice() {
2490 [res1, res2] => {
2491 msg += &format!(
2492 "both {} {} and {} {}",
2493 res1.article(),
2494 res1.descr(),
2495 res2.article(),
2496 res2.descr()
2497 );
2498 }
2499 _ => {
2500 let mut kinds = kinds.iter().peekable();
2501 while let Some(res) = kinds.next() {
2502 if kinds.peek().is_some() {
2503 msg += &format!("{} {}, ", res.article(), res.descr());
2504 } else {
2505 msg += &format!("and {} {}", res.article(), res.descr());
2506 }
2507 }
2508 }
2509 }
2510
2511 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2512 if let Some(sp) = sp {
2513 diag.span_label(sp, "ambiguous link");
2514 } else {
2515 diag.note("ambiguous link");
2516 }
2517
2518 for res in kinds {
2519 suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2520 }
2521 });
2522 true
2523}
2524
2525fn suggest_disambiguator(
2528 res: Res,
2529 diag: &mut Diag<'_, ()>,
2530 path_str: &str,
2531 link_range: MarkdownLinkRange,
2532 sp: Option<rustc_span::Span>,
2533 diag_info: &DiagnosticInfo<'_>,
2534) {
2535 let suggestion = res.disambiguator_suggestion();
2536 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2537
2538 let ori_link = match link_range {
2539 MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2540 MarkdownLinkRange::WholeLink(_) => None,
2541 };
2542
2543 if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2544 let mut spans = suggestion.as_help_span(ori_link, sp);
2545 if spans.len() > 1 {
2546 diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2547 } else {
2548 let (sp, suggestion_text) = spans.pop().unwrap();
2549 diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2550 }
2551 } else {
2552 diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2553 }
2554}
2555
2556fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2558 let sym;
2559 let item_name = match diag_info.item.name {
2560 Some(name) => {
2561 sym = name;
2562 sym.as_str()
2563 }
2564 None => "<unknown>",
2565 };
2566 let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2567
2568 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2569 if let Some(sp) = sp {
2570 diag.span_label(sp, "this item is private");
2571 }
2572
2573 let note_msg = if cx.document_private() {
2574 "this link resolves only because you passed `--document-private-items`, but will break without"
2575 } else {
2576 "this link will resolve properly if you pass `--document-private-items`"
2577 };
2578 diag.note(note_msg);
2579 });
2580}
2581
2582fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2584 if ns != TypeNS {
2585 return None;
2586 }
2587 use PrimitiveType::*;
2588 let prim = match path_str {
2589 "isize" => Isize,
2590 "i8" => I8,
2591 "i16" => I16,
2592 "i32" => I32,
2593 "i64" => I64,
2594 "i128" => I128,
2595 "usize" => Usize,
2596 "u8" => U8,
2597 "u16" => U16,
2598 "u32" => U32,
2599 "u64" => U64,
2600 "u128" => U128,
2601 "f16" => F16,
2602 "f32" => F32,
2603 "f64" => F64,
2604 "f128" => F128,
2605 "char" => Char,
2606 "bool" | "true" | "false" => Bool,
2607 "str" | "&str" => Str,
2608 "slice" => Slice,
2610 "array" => Array,
2611 "tuple" => Tuple,
2612 "unit" => Unit,
2613 "pointer" | "*const" | "*mut" => RawPointer,
2614 "reference" | "&" | "&mut" => Reference,
2615 "fn" => Fn,
2616 "never" | "!" => Never,
2617 _ => return None,
2618 };
2619 debug!("resolved primitives {prim:?}");
2620 Some(Res::Primitive(prim))
2621}