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