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