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