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