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