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 | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
129 "const"
130 }
131 DefKind::Static { .. } => "static",
132 DefKind::Field => "field",
133 DefKind::Variant | DefKind::Ctor(..) => "variant",
134 DefKind::TyAlias => "tyalias",
135 _ => match kind
137 .ns()
138 .expect("tried to calculate a disambiguator for a def without a namespace?")
139 {
140 Namespace::TypeNS => "type",
141 Namespace::ValueNS => "value",
142 Namespace::MacroNS => "macro",
143 },
144 };
145
146 Suggestion::Prefix(prefix)
147 }
148}
149
150impl TryFrom<ResolveRes> for Res {
151 type Error = ();
152
153 fn try_from(res: ResolveRes) -> Result<Self, ()> {
154 use rustc_hir::def::Res::*;
155 match res {
156 Def(kind, id) => Ok(Res::Def(kind, id)),
157 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
158 ToolMod | NonMacroAttr(..) | Err => Result::Err(()),
160 other => bug!("unrecognized res {other:?}"),
161 }
162 }
163}
164
165#[derive(Debug)]
168struct UnresolvedPath<'a> {
169 item_id: DefId,
171 module_id: DefId,
173 partial_res: Option<Res>,
177 unresolved: Cow<'a, str>,
181}
182
183#[derive(Debug)]
184enum ResolutionFailure<'a> {
185 WrongNamespace {
187 res: Res,
189 expected_ns: Namespace,
194 },
195 NotResolved(UnresolvedPath<'a>),
196}
197
198#[derive(Clone, Debug, Hash, PartialEq, Eq)]
199pub(crate) enum UrlFragment {
200 Item(DefId),
201 UserWritten(String),
205}
206
207#[derive(Clone, Debug, Hash, PartialEq, Eq)]
208pub(crate) struct ResolutionInfo {
209 item_id: DefId,
210 module_id: DefId,
211 dis: Option<Disambiguator>,
212 path_str: Box<str>,
213 extra_fragment: Option<String>,
214}
215
216#[derive(Clone)]
217pub(crate) struct DiagnosticInfo<'a> {
218 item: &'a Item,
219 dox: &'a str,
220 ori_link: &'a str,
221 link_range: MarkdownLinkRange,
222}
223
224pub(crate) struct OwnedDiagnosticInfo {
225 item: Item,
226 dox: String,
227 ori_link: String,
228 link_range: MarkdownLinkRange,
229}
230
231impl From<DiagnosticInfo<'_>> for OwnedDiagnosticInfo {
232 fn from(f: DiagnosticInfo<'_>) -> Self {
233 Self {
234 item: f.item.clone(),
235 dox: f.dox.to_string(),
236 ori_link: f.ori_link.to_string(),
237 link_range: f.link_range.clone(),
238 }
239 }
240}
241
242impl OwnedDiagnosticInfo {
243 pub(crate) fn as_info(&self) -> DiagnosticInfo<'_> {
244 DiagnosticInfo {
245 item: &self.item,
246 ori_link: &self.ori_link,
247 dox: &self.dox,
248 link_range: self.link_range.clone(),
249 }
250 }
251}
252
253pub(crate) struct LinkCollector<'a, 'tcx> {
254 pub(crate) cx: &'a mut DocContext<'tcx>,
255 pub(crate) visited_links: FxHashMap<ResolutionInfo, Option<(Res, Option<UrlFragment>)>>,
258 pub(crate) ambiguous_links: FxIndexMap<(ItemId, String), Vec<AmbiguousLinks>>,
269}
270
271pub(crate) struct AmbiguousLinks {
272 link_text: Box<str>,
273 diag_info: OwnedDiagnosticInfo,
274 resolved: Vec<(Res, Option<UrlFragment>)>,
275}
276
277impl<'tcx> LinkCollector<'_, 'tcx> {
278 fn variant_field<'path>(
285 &self,
286 path_str: &'path str,
287 item_id: DefId,
288 module_id: DefId,
289 ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
290 let tcx = self.cx.tcx;
291 let no_res = || UnresolvedPath {
292 item_id,
293 module_id,
294 partial_res: None,
295 unresolved: path_str.into(),
296 };
297
298 debug!("looking for enum variant {path_str}");
299 let mut split = path_str.rsplitn(3, "::");
300 let variant_field_name = Symbol::intern(split.next().unwrap());
301 let variant_name = Symbol::intern(split.next().ok_or_else(no_res)?);
305
306 let path = split.next().ok_or_else(no_res)?;
309 let ty_res = self.resolve_path(path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
310
311 match ty_res {
312 Res::Def(DefKind::Enum | DefKind::TyAlias, did) => {
313 match tcx.type_of(did).instantiate_identity().kind() {
314 ty::Adt(def, _) if def.is_enum() => {
315 if let Some(variant) =
316 def.variants().iter().find(|v| v.name == variant_name)
317 && let Some(field) =
318 variant.fields.iter().find(|f| f.name == variant_field_name)
319 {
320 Ok((ty_res, field.did))
321 } else {
322 Err(UnresolvedPath {
323 item_id,
324 module_id,
325 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
326 unresolved: variant_field_name.to_string().into(),
327 })
328 }
329 }
330 _ => unreachable!(),
331 }
332 }
333 _ => Err(UnresolvedPath {
334 item_id,
335 module_id,
336 partial_res: Some(ty_res),
337 unresolved: variant_name.to_string().into(),
338 }),
339 }
340 }
341
342 fn resolve_path(
348 &self,
349 path_str: &str,
350 ns: Namespace,
351 item_id: DefId,
352 module_id: DefId,
353 ) -> Option<Res> {
354 if let res @ Some(..) = resolve_self_ty(self.cx.tcx, path_str, ns, item_id) {
355 return res;
356 }
357
358 let result = self
360 .cx
361 .tcx
362 .doc_link_resolutions(module_id)
363 .get(&(Symbol::intern(path_str), ns))
364 .copied()
365 .unwrap_or_else(|| {
370 span_bug!(
371 self.cx.tcx.def_span(item_id),
372 "no resolution for {path_str:?} {ns:?} {module_id:?}",
373 )
374 })
375 .and_then(|res| res.try_into().ok())
376 .or_else(|| resolve_primitive(path_str, ns));
377 debug!("{path_str} resolved to {result:?} in namespace {ns:?}");
378 result
379 }
380
381 fn resolve<'path>(
384 &self,
385 path_str: &'path str,
386 ns: Namespace,
387 disambiguator: Option<Disambiguator>,
388 item_id: DefId,
389 module_id: DefId,
390 ) -> Result<Vec<(Res, Option<DefId>)>, UnresolvedPath<'path>> {
391 let tcx = self.cx.tcx;
392
393 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
394 return Ok(match res {
395 Res::Def(
396 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Variant,
397 def_id,
398 ) => {
399 vec![(Res::from_def_id(self.cx.tcx, self.cx.tcx.parent(def_id)), Some(def_id))]
400 }
401 _ => vec![(res, None)],
402 });
403 } else if ns == MacroNS {
404 return Err(UnresolvedPath {
405 item_id,
406 module_id,
407 partial_res: None,
408 unresolved: path_str.into(),
409 });
410 }
411
412 let (path_root, item_str) = match path_str.rsplit_once("::") {
415 Some(res @ (_path_root, item_str)) if !item_str.is_empty() => res,
416 _ => {
417 debug!("`::` missing or at end, assuming {path_str} was not in scope");
421 return Err(UnresolvedPath {
422 item_id,
423 module_id,
424 partial_res: None,
425 unresolved: path_str.into(),
426 });
427 }
428 };
429 let item_name = Symbol::intern(item_str);
430
431 match resolve_primitive(path_root, TypeNS)
436 .or_else(|| self.resolve_path(path_root, TypeNS, item_id, module_id))
437 .map(|ty_res| {
438 resolve_associated_item(tcx, ty_res, item_name, ns, disambiguator, module_id)
439 .into_iter()
440 .map(|(res, def_id)| (res, Some(def_id)))
441 .collect::<Vec<_>>()
442 }) {
443 Some(r) if !r.is_empty() => Ok(r),
444 _ => {
445 if ns == Namespace::ValueNS {
446 self.variant_field(path_str, item_id, module_id)
447 .map(|(res, def_id)| vec![(res, Some(def_id))])
448 } else {
449 Err(UnresolvedPath {
450 item_id,
451 module_id,
452 partial_res: None,
453 unresolved: path_root.into(),
454 })
455 }
456 }
457 }
458 }
459}
460
461fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
462 assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
463}
464
465fn resolve_primitive_inherent_assoc_item<'tcx>(
467 tcx: TyCtxt<'tcx>,
468 prim_ty: PrimitiveType,
469 ns: Namespace,
470 item_ident: Ident,
471) -> Vec<(Res, DefId)> {
472 prim_ty
473 .impls(tcx)
474 .flat_map(|impl_| {
475 filter_assoc_items_by_name_and_namespace(tcx, impl_, item_ident, ns)
476 .map(|item| (Res::Primitive(prim_ty), item.def_id))
477 })
478 .collect::<Vec<_>>()
479}
480
481fn resolve_self_ty<'tcx>(
482 tcx: TyCtxt<'tcx>,
483 path_str: &str,
484 ns: Namespace,
485 item_id: DefId,
486) -> Option<Res> {
487 if ns != TypeNS || path_str != "Self" {
488 return None;
489 }
490
491 let self_id = match tcx.def_kind(item_id) {
492 def_kind @ (DefKind::AssocFn
493 | DefKind::AssocConst
494 | DefKind::AssocTy
495 | DefKind::Variant
496 | DefKind::Field) => {
497 let parent_def_id = tcx.parent(item_id);
498 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant {
499 tcx.parent(parent_def_id)
500 } else {
501 parent_def_id
502 }
503 }
504 _ => item_id,
505 };
506
507 match tcx.def_kind(self_id) {
508 DefKind::Impl { .. } => ty_to_res(tcx, tcx.type_of(self_id).instantiate_identity()),
509 DefKind::Use => None,
510 def_kind => Some(Res::Def(def_kind, self_id)),
511 }
512}
513
514fn ty_to_res<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Res> {
518 use PrimitiveType::*;
519 Some(match *ty.kind() {
520 ty::Bool => Res::Primitive(Bool),
521 ty::Char => Res::Primitive(Char),
522 ty::Int(ity) => Res::Primitive(ity.into()),
523 ty::Uint(uty) => Res::Primitive(uty.into()),
524 ty::Float(fty) => Res::Primitive(fty.into()),
525 ty::Str => Res::Primitive(Str),
526 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
527 ty::Tuple(_) => Res::Primitive(Tuple),
528 ty::Pat(..) => Res::Primitive(Pat),
529 ty::Array(..) => Res::Primitive(Array),
530 ty::Slice(_) => Res::Primitive(Slice),
531 ty::RawPtr(_, _) => Res::Primitive(RawPointer),
532 ty::Ref(..) => Res::Primitive(Reference),
533 ty::FnDef(..) => panic!("type alias to a function definition"),
534 ty::FnPtr(..) => Res::Primitive(Fn),
535 ty::Never => Res::Primitive(Never),
536 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
537 Res::from_def_id(tcx, did)
538 }
539 ty::Alias(..)
540 | ty::Closure(..)
541 | ty::CoroutineClosure(..)
542 | ty::Coroutine(..)
543 | ty::CoroutineWitness(..)
544 | ty::Dynamic(..)
545 | ty::UnsafeBinder(_)
546 | ty::Param(_)
547 | ty::Bound(..)
548 | ty::Placeholder(_)
549 | ty::Infer(_)
550 | ty::Error(_) => return None,
551 })
552}
553
554fn primitive_type_to_ty<'tcx>(tcx: TyCtxt<'tcx>, prim: PrimitiveType) -> Option<Ty<'tcx>> {
558 use PrimitiveType::*;
559
560 Some(match prim {
564 Bool => tcx.types.bool,
565 Str => tcx.types.str_,
566 Char => tcx.types.char,
567 Never => tcx.types.never,
568 I8 => tcx.types.i8,
569 I16 => tcx.types.i16,
570 I32 => tcx.types.i32,
571 I64 => tcx.types.i64,
572 I128 => tcx.types.i128,
573 Isize => tcx.types.isize,
574 F16 => tcx.types.f16,
575 F32 => tcx.types.f32,
576 F64 => tcx.types.f64,
577 F128 => tcx.types.f128,
578 U8 => tcx.types.u8,
579 U16 => tcx.types.u16,
580 U32 => tcx.types.u32,
581 U64 => tcx.types.u64,
582 U128 => tcx.types.u128,
583 Usize => tcx.types.usize,
584 _ => return None,
585 })
586}
587
588fn resolve_associated_item<'tcx>(
591 tcx: TyCtxt<'tcx>,
592 root_res: Res,
593 item_name: Symbol,
594 ns: Namespace,
595 disambiguator: Option<Disambiguator>,
596 module_id: DefId,
597) -> Vec<(Res, DefId)> {
598 let item_ident = Ident::with_dummy_span(item_name);
599
600 match root_res {
601 Res::Def(DefKind::TyAlias, alias_did) => {
602 let Some(aliased_res) = ty_to_res(tcx, tcx.type_of(alias_did).instantiate_identity())
606 else {
607 return vec![];
608 };
609 let aliased_items =
610 resolve_associated_item(tcx, aliased_res, item_name, ns, disambiguator, module_id);
611 aliased_items
612 .into_iter()
613 .map(|(res, assoc_did)| {
614 if is_assoc_item_on_alias_page(tcx, assoc_did) {
615 (root_res, assoc_did)
616 } else {
617 (res, assoc_did)
618 }
619 })
620 .collect()
621 }
622 Res::Primitive(prim) => resolve_assoc_on_primitive(tcx, prim, ns, item_ident, module_id),
623 Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, did) => {
624 resolve_assoc_on_adt(tcx, did, item_ident, ns, disambiguator, module_id)
625 }
626 Res::Def(DefKind::ForeignTy, did) => {
627 resolve_assoc_on_simple_type(tcx, did, item_ident, ns, module_id)
628 }
629 Res::Def(DefKind::Trait, did) => filter_assoc_items_by_name_and_namespace(
630 tcx,
631 did,
632 Ident::with_dummy_span(item_name),
633 ns,
634 )
635 .map(|item| (root_res, item.def_id))
636 .collect::<Vec<_>>(),
637 _ => Vec::new(),
638 }
639}
640
641fn is_assoc_item_on_alias_page<'tcx>(tcx: TyCtxt<'tcx>, assoc_did: DefId) -> bool {
644 match tcx.def_kind(assoc_did) {
645 DefKind::Variant | DefKind::Field => true,
647 _ => false,
648 }
649}
650
651fn resolve_assoc_on_primitive<'tcx>(
652 tcx: TyCtxt<'tcx>,
653 prim: PrimitiveType,
654 ns: Namespace,
655 item_ident: Ident,
656 module_id: DefId,
657) -> Vec<(Res, DefId)> {
658 let root_res = Res::Primitive(prim);
659 let items = resolve_primitive_inherent_assoc_item(tcx, prim, ns, item_ident);
660 if !items.is_empty() {
661 items
662 } else {
664 primitive_type_to_ty(tcx, prim)
665 .map(|ty| {
666 resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
667 .iter()
668 .map(|item| (root_res, item.def_id))
669 .collect::<Vec<_>>()
670 })
671 .unwrap_or_default()
672 }
673}
674
675fn resolve_assoc_on_adt<'tcx>(
676 tcx: TyCtxt<'tcx>,
677 adt_def_id: DefId,
678 item_ident: Ident,
679 ns: Namespace,
680 disambiguator: Option<Disambiguator>,
681 module_id: DefId,
682) -> Vec<(Res, DefId)> {
683 debug!("looking for associated item named {item_ident} for item {adt_def_id:?}");
684 let root_res = Res::from_def_id(tcx, adt_def_id);
685 let adt_ty = tcx.type_of(adt_def_id).instantiate_identity();
686 let adt_def = adt_ty.ty_adt_def().expect("must be ADT");
687 if ns == TypeNS && adt_def.is_enum() {
689 for variant in adt_def.variants() {
690 if variant.name == item_ident.name {
691 return vec![(root_res, variant.def_id)];
692 }
693 }
694 }
695
696 if let Some(Disambiguator::Kind(DefKind::Field)) = disambiguator
697 && (adt_def.is_struct() || adt_def.is_union())
698 {
699 return resolve_structfield(adt_def, item_ident.name)
700 .into_iter()
701 .map(|did| (root_res, did))
702 .collect();
703 }
704
705 let assoc_items = resolve_assoc_on_simple_type(tcx, adt_def_id, item_ident, ns, module_id);
706 if !assoc_items.is_empty() {
707 return assoc_items;
708 }
709
710 if ns == Namespace::ValueNS && (adt_def.is_struct() || adt_def.is_union()) {
711 return resolve_structfield(adt_def, item_ident.name)
712 .into_iter()
713 .map(|did| (root_res, did))
714 .collect();
715 }
716
717 vec![]
718}
719
720fn resolve_assoc_on_simple_type<'tcx>(
722 tcx: TyCtxt<'tcx>,
723 ty_def_id: DefId,
724 item_ident: Ident,
725 ns: Namespace,
726 module_id: DefId,
727) -> Vec<(Res, DefId)> {
728 let root_res = Res::from_def_id(tcx, ty_def_id);
729 let inherent_assoc_items: Vec<_> = tcx
731 .inherent_impls(ty_def_id)
732 .iter()
733 .flat_map(|&imp| filter_assoc_items_by_name_and_namespace(tcx, imp, item_ident, ns))
734 .map(|item| (root_res, item.def_id))
735 .collect();
736 debug!("got inherent assoc items {inherent_assoc_items:?}");
737 if !inherent_assoc_items.is_empty() {
738 return inherent_assoc_items;
739 }
740
741 let ty = tcx.type_of(ty_def_id).instantiate_identity();
747 let trait_assoc_items = resolve_associated_trait_item(ty, module_id, item_ident, ns, tcx)
748 .into_iter()
749 .map(|item| (root_res, item.def_id))
750 .collect::<Vec<_>>();
751 debug!("got trait assoc items {trait_assoc_items:?}");
752 trait_assoc_items
753}
754
755fn resolve_structfield<'tcx>(adt_def: ty::AdtDef<'tcx>, item_name: Symbol) -> Option<DefId> {
756 debug!("looking for fields named {item_name} for {adt_def:?}");
757 adt_def
758 .non_enum_variant()
759 .fields
760 .iter()
761 .find(|field| field.name == item_name)
762 .map(|field| field.did)
763}
764
765fn resolve_associated_trait_item<'tcx>(
771 ty: Ty<'tcx>,
772 module: DefId,
773 item_ident: Ident,
774 ns: Namespace,
775 tcx: TyCtxt<'tcx>,
776) -> Vec<ty::AssocItem> {
777 let traits = trait_impls_for(tcx, ty, module);
784 debug!("considering traits {traits:?}");
785 let candidates = traits
786 .iter()
787 .flat_map(|&(impl_, trait_)| {
788 filter_assoc_items_by_name_and_namespace(tcx, trait_, item_ident, ns).map(
789 move |trait_assoc| {
790 trait_assoc_to_impl_assoc_item(tcx, impl_, trait_assoc.def_id)
791 .unwrap_or(*trait_assoc)
792 },
793 )
794 })
795 .collect::<Vec<_>>();
796 debug!("the candidates were {candidates:?}");
798 candidates
799}
800
801#[instrument(level = "debug", skip(tcx), ret)]
811fn trait_assoc_to_impl_assoc_item<'tcx>(
812 tcx: TyCtxt<'tcx>,
813 impl_id: DefId,
814 trait_assoc_id: DefId,
815) -> Option<ty::AssocItem> {
816 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
817 debug!(?trait_to_impl_assoc_map);
818 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
819 debug!(?impl_assoc_id);
820 Some(tcx.associated_item(impl_assoc_id))
821}
822
823#[instrument(level = "debug", skip(tcx))]
829fn trait_impls_for<'tcx>(
830 tcx: TyCtxt<'tcx>,
831 ty: Ty<'tcx>,
832 module: DefId,
833) -> FxIndexSet<(DefId, DefId)> {
834 let mut impls = FxIndexSet::default();
835
836 for &trait_ in tcx.doc_link_traits_in_scope(module) {
837 tcx.for_each_relevant_impl(trait_, ty, |impl_| {
838 let trait_ref = tcx.impl_trait_ref(impl_);
839 let impl_type = trait_ref.skip_binder().self_ty();
841 trace!(
842 "comparing type {impl_type} with kind {kind:?} against type {ty:?}",
843 kind = impl_type.kind(),
844 );
845 let saw_impl = impl_type == ty
851 || match (impl_type.kind(), ty.kind()) {
852 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
853 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
854 impl_def.did() == ty_def.did()
855 }
856 _ => false,
857 };
858
859 if saw_impl {
860 impls.insert((impl_, trait_));
861 }
862 });
863 }
864
865 impls
866}
867
868fn is_derive_trait_collision<T>(ns: &PerNS<Result<Vec<(Res, T)>, ResolutionFailure<'_>>>) -> bool {
872 if let (Ok(type_ns), Ok(macro_ns)) = (&ns.type_ns, &ns.macro_ns) {
873 type_ns.iter().any(|(res, _)| matches!(res, Res::Def(DefKind::Trait, _)))
874 && macro_ns.iter().any(|(res, _)| {
875 matches!(
876 res,
877 Res::Def(DefKind::Macro(kinds), _) if kinds.contains(MacroKinds::DERIVE)
878 )
879 })
880 } else {
881 false
882 }
883}
884
885impl DocVisitor<'_> for LinkCollector<'_, '_> {
886 fn visit_item(&mut self, item: &Item) {
887 self.resolve_links(item);
888 self.visit_item_recur(item)
889 }
890}
891
892enum PreprocessingError {
893 MultipleAnchors,
895 Disambiguator(MarkdownLinkRange, String),
896 MalformedGenerics(MalformedGenerics, String),
897}
898
899impl PreprocessingError {
900 fn report(&self, cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
901 match self {
902 PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info),
903 PreprocessingError::Disambiguator(range, msg) => {
904 disambiguator_error(cx, diag_info, range.clone(), msg.clone())
905 }
906 PreprocessingError::MalformedGenerics(err, path_str) => {
907 report_malformed_generics(cx, diag_info, *err, path_str)
908 }
909 }
910 }
911}
912
913#[derive(Clone)]
914struct PreprocessingInfo {
915 path_str: Box<str>,
916 disambiguator: Option<Disambiguator>,
917 extra_fragment: Option<String>,
918 link_text: Box<str>,
919}
920
921pub(crate) struct PreprocessedMarkdownLink(
923 Result<PreprocessingInfo, PreprocessingError>,
924 MarkdownLink,
925);
926
927fn preprocess_link(
934 ori_link: &MarkdownLink,
935 dox: &str,
936) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
937 let can_be_url = !matches!(
945 ori_link.kind,
946 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown | LinkType::ReferenceUnknown
947 );
948
949 if ori_link.link.is_empty() {
951 return None;
952 }
953
954 if can_be_url && ori_link.link.contains('/') {
956 return None;
957 }
958
959 let stripped = ori_link.link.replace('`', "");
960 let mut parts = stripped.split('#');
961
962 let link = parts.next().unwrap();
963 let link = link.trim();
964 if link.is_empty() {
965 return None;
967 }
968 let extra_fragment = parts.next();
969 if parts.next().is_some() {
970 return Some(Err(PreprocessingError::MultipleAnchors));
972 }
973
974 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
976 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
977 Ok(None) => (None, link, link),
978 Err((err_msg, relative_range)) => {
979 if !(can_be_url && should_ignore_link_with_disambiguators(link)) {
981 let disambiguator_range = match range_between_backticks(&ori_link.range, dox) {
982 MarkdownLinkRange::Destination(no_backticks_range) => {
983 MarkdownLinkRange::Destination(
984 (no_backticks_range.start + relative_range.start)
985 ..(no_backticks_range.start + relative_range.end),
986 )
987 }
988 mdlr @ MarkdownLinkRange::WholeLink(_) => mdlr,
989 };
990 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
991 } else {
992 return None;
993 }
994 }
995 };
996
997 let is_shortcut_style = ori_link.kind == LinkType::ShortcutUnknown;
998 let ignore_urllike = can_be_url || (is_shortcut_style && !ori_link.link.contains('`'));
1015 if ignore_urllike && should_ignore_link(path_str) {
1016 return None;
1017 }
1018 if is_shortcut_style
1024 && let Some(suffix) = ori_link.link.strip_prefix('!')
1025 && !suffix.is_empty()
1026 && suffix.chars().all(|c| c.is_ascii_alphabetic())
1027 {
1028 return None;
1029 }
1030
1031 let path_str = match strip_generics_from_path(path_str) {
1033 Ok(path) => path,
1034 Err(err) => {
1035 debug!("link has malformed generics: {path_str}");
1036 return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
1037 }
1038 };
1039
1040 assert!(!path_str.contains(['<', '>'].as_slice()));
1042
1043 if path_str.contains(' ') {
1045 return None;
1046 }
1047
1048 Some(Ok(PreprocessingInfo {
1049 path_str,
1050 disambiguator,
1051 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1052 link_text: Box::<str>::from(link_text),
1053 }))
1054}
1055
1056fn preprocessed_markdown_links(s: &str) -> Vec<PreprocessedMarkdownLink> {
1057 markdown_links(s, |link| {
1058 preprocess_link(&link, s).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1059 })
1060}
1061
1062impl LinkCollector<'_, '_> {
1063 #[instrument(level = "debug", skip_all)]
1064 fn resolve_links(&mut self, item: &Item) {
1065 let tcx = self.cx.tcx;
1066 if !self.cx.document_private()
1067 && let Some(def_id) = item.item_id.as_def_id()
1068 && let Some(def_id) = def_id.as_local()
1069 && !tcx.effective_visibilities(()).is_exported(def_id)
1070 && !has_primitive_or_keyword_or_attribute_docs(&item.attrs.other_attrs)
1071 {
1072 return;
1074 }
1075
1076 let mut insert_links = |item_id, doc: &str| {
1077 let module_id = match tcx.def_kind(item_id) {
1078 DefKind::Mod if item.inner_docs(tcx) => item_id,
1079 _ => find_nearest_parent_module(tcx, item_id).unwrap(),
1080 };
1081 for md_link in preprocessed_markdown_links(&doc) {
1082 let link = self.resolve_link(&doc, item, item_id, module_id, &md_link);
1083 if let Some(link) = link {
1084 self.cx
1085 .cache
1086 .intra_doc_links
1087 .entry(item.item_or_reexport_id())
1088 .or_default()
1089 .insert(link);
1090 }
1091 }
1092 };
1093
1094 for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
1099 if !may_have_doc_links(&doc) {
1100 continue;
1101 }
1102
1103 debug!("combined_docs={doc}");
1104 let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
1107 insert_links(item_id, &doc)
1108 }
1109
1110 for attr in &item.attrs.other_attrs {
1112 let Attribute::Parsed(AttributeKind::Deprecation { span: depr_span, deprecation }) =
1113 attr
1114 else {
1115 continue;
1116 };
1117 let Some(note_sym) = deprecation.note else { continue };
1118 let note = note_sym.as_str();
1119
1120 if !may_have_doc_links(note) {
1121 continue;
1122 }
1123
1124 debug!("deprecated_note={note}");
1125 let item_id = if let Some(inline_stmt_id) = item.inline_stmt_id
1130 && find_attr!(tcx, inline_stmt_id, Deprecation {span, ..} if span == depr_span)
1131 {
1132 inline_stmt_id.to_def_id()
1133 } else {
1134 item.item_id.expect_def_id()
1135 };
1136 insert_links(item_id, note)
1137 }
1138 }
1139
1140 pub(crate) fn save_link(&mut self, item_id: ItemId, link: ItemLink) {
1141 self.cx.cache.intra_doc_links.entry(item_id).or_default().insert(link);
1142 }
1143
1144 fn resolve_link(
1148 &mut self,
1149 dox: &str,
1150 item: &Item,
1151 item_id: DefId,
1152 module_id: DefId,
1153 PreprocessedMarkdownLink(pp_link, ori_link): &PreprocessedMarkdownLink,
1154 ) -> Option<ItemLink> {
1155 trace!("considering link '{}'", ori_link.link);
1156
1157 let diag_info = DiagnosticInfo {
1158 item,
1159 dox,
1160 ori_link: &ori_link.link,
1161 link_range: ori_link.range.clone(),
1162 };
1163 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1164 pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1165 let disambiguator = *disambiguator;
1166
1167 let mut resolved = self.resolve_with_disambiguator_cached(
1168 ResolutionInfo {
1169 item_id,
1170 module_id,
1171 dis: disambiguator,
1172 path_str: path_str.clone(),
1173 extra_fragment: extra_fragment.clone(),
1174 },
1175 diag_info.clone(), matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1180 )?;
1181
1182 if resolved.len() > 1 {
1183 let links = AmbiguousLinks {
1184 link_text: link_text.clone(),
1185 diag_info: diag_info.into(),
1186 resolved,
1187 };
1188
1189 self.ambiguous_links
1190 .entry((item.item_id, path_str.to_string()))
1191 .or_default()
1192 .push(links);
1193 None
1194 } else if let Some((res, fragment)) = resolved.pop() {
1195 self.compute_link(res, fragment, path_str, disambiguator, diag_info, link_text)
1196 } else {
1197 None
1198 }
1199 }
1200
1201 fn validate_link(&self, original_did: DefId) -> bool {
1210 let tcx = self.cx.tcx;
1211 let def_kind = tcx.def_kind(original_did);
1212 let did = match def_kind {
1213 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
1214 tcx.parent(original_did)
1216 }
1217 DefKind::Ctor(..) => return self.validate_link(tcx.parent(original_did)),
1220 DefKind::ExternCrate => {
1221 if let Some(local_did) = original_did.as_local() {
1223 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
1224 } else {
1225 original_did
1226 }
1227 }
1228 _ => original_did,
1229 };
1230
1231 let cache = &self.cx.cache;
1232 if !original_did.is_local()
1233 && !cache.effective_visibilities.is_directly_public(tcx, did)
1234 && !cache.document_private
1235 && !cache.primitive_locations.values().any(|&id| id == did)
1236 {
1237 return false;
1238 }
1239
1240 cache.paths.get(&did).is_some()
1241 || cache.external_paths.contains_key(&did)
1242 || !did.is_local()
1243 }
1244
1245 pub(crate) fn resolve_ambiguities(&mut self) {
1246 let mut ambiguous_links = mem::take(&mut self.ambiguous_links);
1247 for ((item_id, path_str), info_items) in ambiguous_links.iter_mut() {
1248 for info in info_items {
1249 info.resolved.retain(|(res, _)| match res {
1250 Res::Def(_, def_id) => self.validate_link(*def_id),
1251 Res::Primitive(_) => true,
1253 });
1254 let diag_info = info.diag_info.as_info();
1255 match info.resolved.len() {
1256 1 => {
1257 let (res, fragment) = info.resolved.pop().unwrap();
1258 if let Some(link) = self.compute_link(
1259 res,
1260 fragment,
1261 path_str,
1262 None,
1263 diag_info,
1264 &info.link_text,
1265 ) {
1266 self.save_link(*item_id, link);
1267 }
1268 }
1269 0 => {
1270 report_diagnostic(
1271 self.cx.tcx,
1272 BROKEN_INTRA_DOC_LINKS,
1273 format!("all items matching `{path_str}` are private or doc(hidden)"),
1274 &diag_info,
1275 |diag, sp, _| {
1276 if let Some(sp) = sp {
1277 diag.span_label(sp, "unresolved link");
1278 } else {
1279 diag.note("unresolved link");
1280 }
1281 },
1282 );
1283 }
1284 _ => {
1285 let candidates = info
1286 .resolved
1287 .iter()
1288 .map(|(res, fragment)| {
1289 let def_id = if let Some(UrlFragment::Item(def_id)) = fragment {
1290 Some(*def_id)
1291 } else {
1292 None
1293 };
1294 (*res, def_id)
1295 })
1296 .collect::<Vec<_>>();
1297 ambiguity_error(self.cx, &diag_info, path_str, &candidates, true);
1298 }
1299 }
1300 }
1301 }
1302 }
1303
1304 fn compute_link(
1305 &mut self,
1306 mut res: Res,
1307 fragment: Option<UrlFragment>,
1308 path_str: &str,
1309 disambiguator: Option<Disambiguator>,
1310 diag_info: DiagnosticInfo<'_>,
1311 link_text: &Box<str>,
1312 ) -> Option<ItemLink> {
1313 if matches!(
1317 disambiguator,
1318 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1319 ) && !matches!(res, Res::Primitive(_))
1320 && let Some(prim) = resolve_primitive(path_str, TypeNS)
1321 {
1322 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1324 res = prim;
1325 } else {
1326 let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)];
1328 ambiguity_error(self.cx, &diag_info, path_str, candidates, true);
1329 return None;
1330 }
1331 }
1332
1333 match res {
1334 Res::Primitive(_) => {
1335 if let Some(UrlFragment::Item(id)) = fragment {
1336 let kind = self.cx.tcx.def_kind(id);
1345 self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1346 } else {
1347 match disambiguator {
1348 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1349 Some(other) => {
1350 self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1351 return None;
1352 }
1353 }
1354 }
1355
1356 res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1357 link: Box::<str>::from(diag_info.ori_link),
1358 link_text: link_text.clone(),
1359 page_id,
1360 fragment,
1361 })
1362 }
1363 Res::Def(kind, id) => {
1364 let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1365 (self.cx.tcx.def_kind(id), id)
1366 } else {
1367 (kind, id)
1368 };
1369 self.verify_disambiguator(
1370 path_str,
1371 kind_for_dis,
1372 id_for_dis,
1373 disambiguator,
1374 &diag_info,
1375 )?;
1376
1377 let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1378 Some(ItemLink {
1379 link: Box::<str>::from(diag_info.ori_link),
1380 link_text: link_text.clone(),
1381 page_id,
1382 fragment,
1383 })
1384 }
1385 }
1386 }
1387
1388 fn verify_disambiguator(
1389 &self,
1390 path_str: &str,
1391 kind: DefKind,
1392 id: DefId,
1393 disambiguator: Option<Disambiguator>,
1394 diag_info: &DiagnosticInfo<'_>,
1395 ) -> Option<()> {
1396 debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1397
1398 debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1400 match (kind, disambiguator) {
1401 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1402 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1405 | (_, Some(Disambiguator::Namespace(_)))
1407 | (_, None)
1409 => {}
1411 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1412 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1413 self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1414 return None;
1415 }
1416 }
1417
1418 if let Some(dst_id) = id.as_local()
1420 && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1421 && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1422 && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1423 {
1424 privacy_error(self.cx, diag_info, path_str);
1425 }
1426
1427 Some(())
1428 }
1429
1430 fn report_disambiguator_mismatch(
1431 &self,
1432 path_str: &str,
1433 specified: Disambiguator,
1434 resolved: Res,
1435 diag_info: &DiagnosticInfo<'_>,
1436 ) {
1437 let msg = format!("incompatible link kind for `{path_str}`");
1439 let callback = |diag: &mut Diag<'_, ()>, sp: Option<rustc_span::Span>, link_range| {
1440 let note = format!(
1441 "this link resolved to {} {}, which is not {} {}",
1442 resolved.article(),
1443 resolved.descr(),
1444 specified.article(),
1445 specified.descr(),
1446 );
1447 if let Some(sp) = sp {
1448 diag.span_label(sp, note);
1449 } else {
1450 diag.note(note);
1451 }
1452 suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1453 };
1454 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1455 }
1456
1457 fn report_rawptr_assoc_feature_gate(
1458 &self,
1459 dox: &str,
1460 ori_link: &MarkdownLinkRange,
1461 item: &Item,
1462 ) {
1463 let span = match source_span_for_markdown_range(
1464 self.cx.tcx,
1465 dox,
1466 ori_link.inner_range(),
1467 &item.attrs.doc_strings,
1468 ) {
1469 Some((sp, _)) => sp,
1470 None => item.attr_span(self.cx.tcx),
1471 };
1472 rustc_session::parse::feature_err(
1473 self.cx.tcx.sess,
1474 sym::intra_doc_pointers,
1475 span,
1476 "linking to associated items of raw pointers is experimental",
1477 )
1478 .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1479 .emit();
1480 }
1481
1482 fn resolve_with_disambiguator_cached(
1483 &mut self,
1484 key: ResolutionInfo,
1485 diag: DiagnosticInfo<'_>,
1486 cache_errors: bool,
1489 ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1490 if let Some(res) = self.visited_links.get(&key)
1491 && (res.is_some() || cache_errors)
1492 {
1493 return res.clone().map(|r| vec![r]);
1494 }
1495
1496 let mut candidates = self.resolve_with_disambiguator(&key, diag.clone());
1497
1498 if let Some(candidate) = candidates.first()
1501 && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1502 && key.path_str.contains("::")
1503 {
1505 if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1506 self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1507 return None;
1508 } else {
1509 candidates = vec![*candidate];
1510 }
1511 }
1512
1513 if let [candidate, _candidate2, ..] = *candidates
1518 && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1519 {
1520 candidates = vec![candidate];
1521 }
1522
1523 let mut out = Vec::with_capacity(candidates.len());
1524 for (res, def_id) in candidates {
1525 let fragment = match (&key.extra_fragment, def_id) {
1526 (Some(_), Some(def_id)) => {
1527 report_anchor_conflict(self.cx, diag, def_id);
1528 return None;
1529 }
1530 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1531 (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1532 (None, None) => None,
1533 };
1534 out.push((res, fragment));
1535 }
1536 if let [r] = out.as_slice() {
1537 self.visited_links.insert(key, Some(r.clone()));
1538 } else if cache_errors {
1539 self.visited_links.insert(key, None);
1540 }
1541 Some(out)
1542 }
1543
1544 fn resolve_with_disambiguator(
1546 &mut self,
1547 key: &ResolutionInfo,
1548 diag: DiagnosticInfo<'_>,
1549 ) -> Vec<(Res, Option<DefId>)> {
1550 let disambiguator = key.dis;
1551 let path_str = &key.path_str;
1552 let item_id = key.item_id;
1553 let module_id = key.module_id;
1554
1555 match disambiguator.map(Disambiguator::ns) {
1556 Some(expected_ns) => {
1557 match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1558 Ok(candidates) => candidates,
1559 Err(err) => {
1560 let mut err = ResolutionFailure::NotResolved(err);
1564 for other_ns in [TypeNS, ValueNS, MacroNS] {
1565 if other_ns != expected_ns
1566 && let Ok(&[res, ..]) = self
1567 .resolve(path_str, other_ns, None, item_id, module_id)
1568 .as_deref()
1569 {
1570 err = ResolutionFailure::WrongNamespace {
1571 res: full_res(self.cx.tcx, res),
1572 expected_ns,
1573 };
1574 break;
1575 }
1576 }
1577 resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1578 vec![]
1579 }
1580 }
1581 }
1582 None => {
1583 let candidate = |ns| {
1585 self.resolve(path_str, ns, None, item_id, module_id)
1586 .map_err(ResolutionFailure::NotResolved)
1587 };
1588
1589 let candidates = PerNS {
1590 macro_ns: candidate(MacroNS),
1591 type_ns: candidate(TypeNS),
1592 value_ns: candidate(ValueNS).and_then(|v_res| {
1593 for (res, _) in v_res.iter() {
1594 if let Res::Def(DefKind::Ctor(..), _) = res {
1596 return Err(ResolutionFailure::WrongNamespace {
1597 res: *res,
1598 expected_ns: TypeNS,
1599 });
1600 }
1601 }
1602 Ok(v_res)
1603 }),
1604 };
1605
1606 let len = candidates
1607 .iter()
1608 .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1609
1610 if len == 0 {
1611 resolution_failure(
1612 self,
1613 diag,
1614 path_str,
1615 disambiguator,
1616 candidates.into_iter().filter_map(|res| res.err()).collect(),
1617 );
1618 vec![]
1619 } else if len == 1 {
1620 candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1621 } else {
1622 let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1623 if len == 2 && has_derive_trait_collision {
1624 candidates.type_ns.unwrap()
1625 } else {
1626 let mut candidates = candidates.map(|candidate| candidate.ok());
1628 if has_derive_trait_collision {
1630 candidates.macro_ns = None;
1631 }
1632 candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1633 }
1634 }
1635 }
1636 }
1637 }
1638}
1639
1640fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1652 let range = match ori_link_range {
1653 mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1654 MarkdownLinkRange::Destination(inner) => inner.clone(),
1655 };
1656 let ori_link_text = &dox[range.clone()];
1657 let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1658 let before_second_backtick_group = ori_link_text
1659 .bytes()
1660 .skip(after_first_backtick_group)
1661 .position(|b| b == b'`')
1662 .unwrap_or(ori_link_text.len());
1663 MarkdownLinkRange::Destination(
1664 (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1665 )
1666}
1667
1668fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1675 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1676}
1677
1678fn should_ignore_link(path_str: &str) -> bool {
1681 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1682}
1683
1684#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1685enum Disambiguator {
1687 Primitive,
1691 Kind(DefKind),
1693 Namespace(Namespace),
1695}
1696
1697impl Disambiguator {
1698 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1704 use Disambiguator::{Kind, Namespace as NS, Primitive};
1705
1706 let suffixes = [
1707 ("!()", DefKind::Macro(MacroKinds::BANG)),
1709 ("!{}", DefKind::Macro(MacroKinds::BANG)),
1710 ("![]", DefKind::Macro(MacroKinds::BANG)),
1711 ("()", DefKind::Fn),
1712 ("!", DefKind::Macro(MacroKinds::BANG)),
1713 ];
1714
1715 if let Some(idx) = link.find('@') {
1716 let (prefix, rest) = link.split_at(idx);
1717 let d = match prefix {
1718 "struct" => Kind(DefKind::Struct),
1720 "enum" => Kind(DefKind::Enum),
1721 "trait" => Kind(DefKind::Trait),
1722 "union" => Kind(DefKind::Union),
1723 "module" | "mod" => Kind(DefKind::Mod),
1724 "const" | "constant" => Kind(DefKind::Const),
1725 "static" => Kind(DefKind::Static {
1726 mutability: Mutability::Not,
1727 nested: false,
1728 safety: Safety::Safe,
1729 }),
1730 "function" | "fn" | "method" => Kind(DefKind::Fn),
1731 "derive" => Kind(DefKind::Macro(MacroKinds::DERIVE)),
1732 "field" => Kind(DefKind::Field),
1733 "variant" => Kind(DefKind::Variant),
1734 "type" => NS(Namespace::TypeNS),
1735 "value" => NS(Namespace::ValueNS),
1736 "macro" => NS(Namespace::MacroNS),
1737 "prim" | "primitive" => Primitive,
1738 "tyalias" | "typealias" => Kind(DefKind::TyAlias),
1739 _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1740 };
1741
1742 for (suffix, kind) in suffixes {
1743 if let Some(path_str) = rest.strip_suffix(suffix) {
1744 if d.ns() != Kind(kind).ns() {
1745 return Err((
1746 format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1747 0..idx,
1748 ));
1749 } else if path_str.len() > 1 {
1750 return Ok(Some((d, &path_str[1..], &rest[1..])));
1752 }
1753 }
1754 }
1755
1756 Ok(Some((d, &rest[1..], &rest[1..])))
1757 } else {
1758 for (suffix, kind) in suffixes {
1759 if let Some(path_str) = link.strip_suffix(suffix)
1761 && !path_str.is_empty()
1762 {
1763 return Ok(Some((Kind(kind), path_str, link)));
1764 }
1765 }
1766 Ok(None)
1767 }
1768 }
1769
1770 fn ns(self) -> Namespace {
1771 match self {
1772 Self::Namespace(n) => n,
1773 Self::Kind(DefKind::Field) => ValueNS,
1775 Self::Kind(k) => {
1776 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1777 }
1778 Self::Primitive => TypeNS,
1779 }
1780 }
1781
1782 fn article(self) -> &'static str {
1783 match self {
1784 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1785 Self::Kind(k) => k.article(),
1786 Self::Primitive => "a",
1787 }
1788 }
1789
1790 fn descr(self) -> &'static str {
1791 match self {
1792 Self::Namespace(n) => n.descr(),
1793 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1796 Self::Primitive => "builtin type",
1797 }
1798 }
1799}
1800
1801enum Suggestion {
1803 Prefix(&'static str),
1805 Function,
1807 Macro,
1809}
1810
1811impl Suggestion {
1812 fn descr(&self) -> Cow<'static, str> {
1813 match self {
1814 Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1815 Self::Function => "add parentheses".into(),
1816 Self::Macro => "add an exclamation mark".into(),
1817 }
1818 }
1819
1820 fn as_help(&self, path_str: &str) -> String {
1821 match self {
1823 Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1824 Self::Function => format!("{path_str}()"),
1825 Self::Macro => format!("{path_str}!"),
1826 }
1827 }
1828
1829 fn as_help_span(
1830 &self,
1831 ori_link: &str,
1832 sp: rustc_span::Span,
1833 ) -> Vec<(rustc_span::Span, String)> {
1834 let inner_sp = match ori_link.find('(') {
1835 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1836 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1837 }
1838 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1839 None => sp,
1840 };
1841 let inner_sp = match ori_link.find('!') {
1842 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1843 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1844 }
1845 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1846 None => inner_sp,
1847 };
1848 let inner_sp = match ori_link.find('@') {
1849 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1850 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1851 }
1852 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1853 None => inner_sp,
1854 };
1855 match self {
1856 Self::Prefix(prefix) => {
1857 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
1859 if sp.hi() != inner_sp.hi() {
1860 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1861 }
1862 sugg
1863 }
1864 Self::Function => {
1865 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1866 if sp.lo() != inner_sp.lo() {
1867 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1868 }
1869 sugg
1870 }
1871 Self::Macro => {
1872 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1873 if sp.lo() != inner_sp.lo() {
1874 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1875 }
1876 sugg
1877 }
1878 }
1879 }
1880}
1881
1882fn report_diagnostic(
1893 tcx: TyCtxt<'_>,
1894 lint: &'static Lint,
1895 msg: impl Into<DiagMessage> + Display,
1896 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1897 decorate: impl FnOnce(&mut Diag<'_, ()>, Option<rustc_span::Span>, MarkdownLinkRange),
1898) {
1899 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
1900 info!("ignoring warning from parent crate: {msg}");
1902 return;
1903 };
1904
1905 let sp = item.attr_span(tcx);
1906
1907 tcx.node_span_lint(lint, hir_id, sp, |lint| {
1908 lint.primary_message(msg);
1909
1910 let (span, link_range) = match link_range {
1911 MarkdownLinkRange::Destination(md_range) => {
1912 let mut md_range = md_range.clone();
1913 let sp =
1914 source_span_for_markdown_range(tcx, dox, &md_range, &item.attrs.doc_strings)
1915 .map(|(mut sp, _)| {
1916 while dox.as_bytes().get(md_range.start) == Some(&b' ')
1917 || dox.as_bytes().get(md_range.start) == Some(&b'`')
1918 {
1919 md_range.start += 1;
1920 sp = sp.with_lo(sp.lo() + BytePos(1));
1921 }
1922 while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
1923 || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
1924 {
1925 md_range.end -= 1;
1926 sp = sp.with_hi(sp.hi() - BytePos(1));
1927 }
1928 sp
1929 });
1930 (sp, MarkdownLinkRange::Destination(md_range))
1931 }
1932 MarkdownLinkRange::WholeLink(md_range) => (
1933 source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
1934 .map(|(sp, _)| sp),
1935 link_range.clone(),
1936 ),
1937 };
1938
1939 if let Some(sp) = span {
1940 lint.span(sp);
1941 } else {
1942 let md_range = link_range.inner_range().clone();
1947 let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
1948 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1949
1950 lint.note(format!(
1952 "the link appears in this line:\n\n{line}\n\
1953 {indicator: <before$}{indicator:^<found$}",
1954 indicator = "",
1955 before = md_range.start - last_new_line_offset,
1956 found = md_range.len(),
1957 ));
1958 }
1959
1960 decorate(lint, span, link_range);
1961 });
1962}
1963
1964fn resolution_failure(
1970 collector: &LinkCollector<'_, '_>,
1971 diag_info: DiagnosticInfo<'_>,
1972 path_str: &str,
1973 disambiguator: Option<Disambiguator>,
1974 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1975) {
1976 let tcx = collector.cx.tcx;
1977 report_diagnostic(
1978 tcx,
1979 BROKEN_INTRA_DOC_LINKS,
1980 format!("unresolved link to `{path_str}`"),
1981 &diag_info,
1982 |diag, sp, link_range| {
1983 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
1984 let assoc_item_not_allowed = |res: Res| {
1985 let name = res.name(tcx);
1986 format!(
1987 "`{name}` is {} {}, not a module or type, and cannot have associated items",
1988 res.article(),
1989 res.descr()
1990 )
1991 };
1992 let mut variants_seen = SmallVec::<[_; 3]>::new();
1994 for mut failure in kinds {
1995 let variant = mem::discriminant(&failure);
1996 if variants_seen.contains(&variant) {
1997 continue;
1998 }
1999 variants_seen.push(variant);
2000
2001 if let ResolutionFailure::NotResolved(UnresolvedPath {
2002 item_id,
2003 module_id,
2004 partial_res,
2005 unresolved,
2006 }) = &mut failure
2007 {
2008 use DefKind::*;
2009
2010 let item_id = *item_id;
2011 let module_id = *module_id;
2012
2013 let mut name = path_str;
2016 'outer: loop {
2017 let Some((start, end)) = name.rsplit_once("::") else {
2019 if partial_res.is_none() {
2021 *unresolved = name.into();
2022 }
2023 break;
2024 };
2025 name = start;
2026 for ns in [TypeNS, ValueNS, MacroNS] {
2027 if let Ok(v_res) =
2028 collector.resolve(start, ns, None, item_id, module_id)
2029 {
2030 debug!("found partial_res={v_res:?}");
2031 if let Some(&res) = v_res.first() {
2032 *partial_res = Some(full_res(tcx, res));
2033 *unresolved = end.into();
2034 break 'outer;
2035 }
2036 }
2037 }
2038 *unresolved = end.into();
2039 }
2040
2041 let last_found_module = match *partial_res {
2042 Some(Res::Def(DefKind::Mod, id)) => Some(id),
2043 None => Some(module_id),
2044 _ => None,
2045 };
2046 if let Some(module) = last_found_module {
2048 let note = if partial_res.is_some() {
2049 let module_name = tcx.item_name(module);
2051 format!("no item named `{unresolved}` in module `{module_name}`")
2052 } else {
2053 format!("no item named `{unresolved}` in scope")
2055 };
2056 if let Some(span) = sp {
2057 diag.span_label(span, note);
2058 } else {
2059 diag.note(note);
2060 }
2061
2062 if !path_str.contains("::") {
2063 if disambiguator.is_none_or(|d| d.ns() == MacroNS)
2064 && collector
2065 .cx
2066 .tcx
2067 .resolutions(())
2068 .all_macro_rules
2069 .contains(&Symbol::intern(path_str))
2070 {
2071 diag.note(format!(
2072 "`macro_rules` named `{path_str}` exists in this crate, \
2073 but it is not in scope at this link's location"
2074 ));
2075 } else {
2076 diag.help(
2079 "to escape `[` and `]` characters, \
2080 add '\\' before them like `\\[` or `\\]`",
2081 );
2082 }
2083 }
2084
2085 continue;
2086 }
2087
2088 let res = partial_res.expect("None case was handled by `last_found_module`");
2090 let kind_did = match res {
2091 Res::Def(kind, did) => Some((kind, did)),
2092 Res::Primitive(_) => None,
2093 };
2094 let is_struct_variant = |did| {
2095 if let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind()
2096 && def.is_enum()
2097 && let Some(variant) =
2098 def.variants().iter().find(|v| v.name == res.name(tcx))
2099 {
2100 variant.ctor.is_none()
2102 } else {
2103 false
2104 }
2105 };
2106 let path_description = if let Some((kind, did)) = kind_did {
2107 match kind {
2108 Mod | ForeignMod => "inner item",
2109 Struct => "field or associated item",
2110 Enum | Union => "variant or associated item",
2111 Variant if is_struct_variant(did) => {
2112 let variant = res.name(tcx);
2113 let note = format!("variant `{variant}` has no such field");
2114 if let Some(span) = sp {
2115 diag.span_label(span, note);
2116 } else {
2117 diag.note(note);
2118 }
2119 return;
2120 }
2121 Variant
2122 | Field
2123 | Closure
2124 | AssocTy
2125 | AssocConst
2126 | AssocFn
2127 | Fn
2128 | Macro(_)
2129 | Const
2130 | ConstParam
2131 | ExternCrate
2132 | Use
2133 | LifetimeParam
2134 | Ctor(_, _)
2135 | AnonConst
2136 | InlineConst => {
2137 let note = assoc_item_not_allowed(res);
2138 if let Some(span) = sp {
2139 diag.span_label(span, note);
2140 } else {
2141 diag.note(note);
2142 }
2143 return;
2144 }
2145 Trait
2146 | TyAlias
2147 | ForeignTy
2148 | OpaqueTy
2149 | TraitAlias
2150 | TyParam
2151 | Static { .. } => "associated item",
2152 Impl { .. } | GlobalAsm | SyntheticCoroutineBody => {
2153 unreachable!("not a path")
2154 }
2155 }
2156 } else {
2157 "associated item"
2158 };
2159 let name = res.name(tcx);
2160 let note = format!(
2161 "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2162 res = res.descr(),
2163 disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2164 );
2165 if let Some(span) = sp {
2166 diag.span_label(span, note);
2167 } else {
2168 diag.note(note);
2169 }
2170
2171 continue;
2172 }
2173 let note = match failure {
2174 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2175 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2176 suggest_disambiguator(
2177 res,
2178 diag,
2179 path_str,
2180 link_range.clone(),
2181 sp,
2182 &diag_info,
2183 );
2184
2185 if let Some(disambiguator) = disambiguator
2186 && !matches!(disambiguator, Disambiguator::Namespace(..))
2187 {
2188 format!(
2189 "this link resolves to {}, which is not {} {}",
2190 item(res),
2191 disambiguator.article(),
2192 disambiguator.descr()
2193 )
2194 } else {
2195 format!(
2196 "this link resolves to {}, which is not in the {} namespace",
2197 item(res),
2198 expected_ns.descr()
2199 )
2200 }
2201 }
2202 };
2203 if let Some(span) = sp {
2204 diag.span_label(span, note);
2205 } else {
2206 diag.note(note);
2207 }
2208 }
2209 },
2210 );
2211}
2212
2213fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2214 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2215 anchor_failure(cx, diag_info, msg, 1)
2216}
2217
2218fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2219 let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2220 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2221 anchor_failure(cx, diag_info, msg, 0)
2222}
2223
2224fn anchor_failure(
2226 cx: &DocContext<'_>,
2227 diag_info: DiagnosticInfo<'_>,
2228 msg: String,
2229 anchor_idx: usize,
2230) {
2231 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2232 if let Some(mut sp) = sp {
2233 if let Some((fragment_offset, _)) =
2234 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2235 {
2236 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2237 }
2238 diag.span_label(sp, "invalid anchor");
2239 }
2240 });
2241}
2242
2243fn disambiguator_error(
2245 cx: &DocContext<'_>,
2246 mut diag_info: DiagnosticInfo<'_>,
2247 disambiguator_range: MarkdownLinkRange,
2248 msg: impl Into<DiagMessage> + Display,
2249) {
2250 diag_info.link_range = disambiguator_range;
2251 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2252 let msg = format!(
2253 "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2254 crate::DOC_RUST_LANG_ORG_VERSION
2255 );
2256 diag.note(msg);
2257 });
2258}
2259
2260fn report_malformed_generics(
2261 cx: &DocContext<'_>,
2262 diag_info: DiagnosticInfo<'_>,
2263 err: MalformedGenerics,
2264 path_str: &str,
2265) {
2266 report_diagnostic(
2267 cx.tcx,
2268 BROKEN_INTRA_DOC_LINKS,
2269 format!("unresolved link to `{path_str}`"),
2270 &diag_info,
2271 |diag, sp, _link_range| {
2272 let note = match err {
2273 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2274 MalformedGenerics::MissingType => "missing type for generic parameters",
2275 MalformedGenerics::HasFullyQualifiedSyntax => {
2276 diag.note(
2277 "see https://github.com/rust-lang/rust/issues/74563 for more information",
2278 );
2279 "fully-qualified syntax is unsupported"
2280 }
2281 MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
2282 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2283 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2284 };
2285 if let Some(span) = sp {
2286 diag.span_label(span, note);
2287 } else {
2288 diag.note(note);
2289 }
2290 },
2291 );
2292}
2293
2294fn ambiguity_error(
2300 cx: &DocContext<'_>,
2301 diag_info: &DiagnosticInfo<'_>,
2302 path_str: &str,
2303 candidates: &[(Res, Option<DefId>)],
2304 emit_error: bool,
2305) -> bool {
2306 let mut descrs = FxHashSet::default();
2307 let mut possible_proc_macro_id = None;
2310 let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro];
2311 let mut kinds = candidates
2312 .iter()
2313 .map(|(res, def_id)| {
2314 let r =
2315 if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2316 if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2317 possible_proc_macro_id = Some(id);
2318 }
2319 r
2320 })
2321 .collect::<Vec<_>>();
2322 if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2331 kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2332 }
2333
2334 kinds.retain(|res| descrs.insert(res.descr()));
2335
2336 if descrs.len() == 1 {
2337 return false;
2340 } else if !emit_error {
2341 return true;
2342 }
2343
2344 let mut msg = format!("`{path_str}` is ");
2345 match kinds.as_slice() {
2346 [res1, res2] => {
2347 msg += &format!(
2348 "both {} {} and {} {}",
2349 res1.article(),
2350 res1.descr(),
2351 res2.article(),
2352 res2.descr()
2353 );
2354 }
2355 _ => {
2356 let mut kinds = kinds.iter().peekable();
2357 while let Some(res) = kinds.next() {
2358 if kinds.peek().is_some() {
2359 msg += &format!("{} {}, ", res.article(), res.descr());
2360 } else {
2361 msg += &format!("and {} {}", res.article(), res.descr());
2362 }
2363 }
2364 }
2365 }
2366
2367 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2368 if let Some(sp) = sp {
2369 diag.span_label(sp, "ambiguous link");
2370 } else {
2371 diag.note("ambiguous link");
2372 }
2373
2374 for res in kinds {
2375 suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2376 }
2377 });
2378 true
2379}
2380
2381fn suggest_disambiguator(
2384 res: Res,
2385 diag: &mut Diag<'_, ()>,
2386 path_str: &str,
2387 link_range: MarkdownLinkRange,
2388 sp: Option<rustc_span::Span>,
2389 diag_info: &DiagnosticInfo<'_>,
2390) {
2391 let suggestion = res.disambiguator_suggestion();
2392 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2393
2394 let ori_link = match link_range {
2395 MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2396 MarkdownLinkRange::WholeLink(_) => None,
2397 };
2398
2399 if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2400 let mut spans = suggestion.as_help_span(ori_link, sp);
2401 if spans.len() > 1 {
2402 diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2403 } else {
2404 let (sp, suggestion_text) = spans.pop().unwrap();
2405 diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2406 }
2407 } else {
2408 diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2409 }
2410}
2411
2412fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2414 let sym;
2415 let item_name = match diag_info.item.name {
2416 Some(name) => {
2417 sym = name;
2418 sym.as_str()
2419 }
2420 None => "<unknown>",
2421 };
2422 let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2423
2424 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2425 if let Some(sp) = sp {
2426 diag.span_label(sp, "this item is private");
2427 }
2428
2429 let note_msg = if cx.document_private() {
2430 "this link resolves only because you passed `--document-private-items`, but will break without"
2431 } else {
2432 "this link will resolve properly if you pass `--document-private-items`"
2433 };
2434 diag.note(note_msg);
2435 });
2436}
2437
2438fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2440 if ns != TypeNS {
2441 return None;
2442 }
2443 use PrimitiveType::*;
2444 let prim = match path_str {
2445 "isize" => Isize,
2446 "i8" => I8,
2447 "i16" => I16,
2448 "i32" => I32,
2449 "i64" => I64,
2450 "i128" => I128,
2451 "usize" => Usize,
2452 "u8" => U8,
2453 "u16" => U16,
2454 "u32" => U32,
2455 "u64" => U64,
2456 "u128" => U128,
2457 "f16" => F16,
2458 "f32" => F32,
2459 "f64" => F64,
2460 "f128" => F128,
2461 "char" => Char,
2462 "bool" | "true" | "false" => Bool,
2463 "str" | "&str" => Str,
2464 "slice" => Slice,
2466 "array" => Array,
2467 "tuple" => Tuple,
2468 "unit" => Unit,
2469 "pointer" | "*const" | "*mut" => RawPointer,
2470 "reference" | "&" | "&mut" => Reference,
2471 "fn" => Fn,
2472 "never" | "!" => Never,
2473 _ => return None,
2474 };
2475 debug!("resolved primitives {prim:?}");
2476 Some(Res::Primitive(prim))
2477}