1use std::borrow::Cow;
6use std::fmt::Display;
7use std::mem;
8use std::ops::Range;
9
10use pulldown_cmark::LinkType;
11use rustc_ast::util::comments::may_have_doc_links;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
13use rustc_data_structures::intern::Interned;
14use rustc_errors::{Applicability, Diag, DiagMessage};
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::{Mutability, Safety};
19use rustc_middle::ty::{Ty, TyCtxt};
20use rustc_middle::{bug, span_bug, ty};
21use rustc_resolve::rustdoc::{
22 MalformedGenerics, has_primitive_or_keyword_or_attribute_docs, prepare_to_doc_link_resolution,
23 source_span_for_markdown_range, strip_generics_from_path,
24};
25use rustc_session::config::CrateType;
26use rustc_session::lint::Lint;
27use rustc_span::BytePos;
28use rustc_span::symbol::{Ident, Symbol, sym};
29use smallvec::{SmallVec, smallvec};
30use tracing::{debug, info, instrument, trace};
31
32use crate::clean::utils::find_nearest_parent_module;
33use crate::clean::{self, Crate, Item, ItemId, ItemLink, PrimitiveType};
34use crate::core::DocContext;
35use crate::html::markdown::{MarkdownLink, MarkdownLinkRange, markdown_links};
36use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
37use crate::passes::Pass;
38use crate::visit::DocVisitor;
39
40pub(crate) const COLLECT_INTRA_DOC_LINKS: Pass =
41 Pass { name: "collect-intra-doc-links", run: None, description: "resolves intra-doc links" };
42
43pub(crate) fn collect_intra_doc_links<'a, 'tcx>(
44 krate: Crate,
45 cx: &'a mut DocContext<'tcx>,
46) -> (Crate, LinkCollector<'a, 'tcx>) {
47 let mut collector = LinkCollector {
48 cx,
49 visited_links: FxHashMap::default(),
50 ambiguous_links: FxIndexMap::default(),
51 };
52 collector.visit_crate(&krate);
53 (krate, collector)
54}
55
56fn filter_assoc_items_by_name_and_namespace(
57 tcx: TyCtxt<'_>,
58 assoc_items_of: DefId,
59 ident: Ident,
60 ns: Namespace,
61) -> impl Iterator<Item = &ty::AssocItem> {
62 tcx.associated_items(assoc_items_of).filter_by_name_unhygienic(ident.name).filter(move |item| {
63 item.namespace() == ns && tcx.hygienic_eq(ident, item.ident(tcx), assoc_items_of)
64 })
65}
66
67#[derive(Copy, Clone, Debug, Hash, PartialEq)]
68pub(crate) enum Res {
69 Def(DefKind, DefId),
70 Primitive(PrimitiveType),
71}
72
73type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
74
75impl Res {
76 fn descr(self) -> &'static str {
77 match self {
78 Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
79 Res::Primitive(_) => "primitive type",
80 }
81 }
82
83 fn article(self) -> &'static str {
84 match self {
85 Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
86 Res::Primitive(_) => "a",
87 }
88 }
89
90 fn name(self, tcx: TyCtxt<'_>) -> Symbol {
91 match self {
92 Res::Def(_, id) => tcx.item_name(id),
93 Res::Primitive(prim) => prim.as_sym(),
94 }
95 }
96
97 fn def_id(self, tcx: TyCtxt<'_>) -> Option<DefId> {
98 match self {
99 Res::Def(_, id) => Some(id),
100 Res::Primitive(prim) => PrimitiveType::primitive_locations(tcx).get(&prim).copied(),
101 }
102 }
103
104 fn from_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Res {
105 Res::Def(tcx.def_kind(def_id), def_id)
106 }
107
108 fn disambiguator_suggestion(self) -> Suggestion {
110 let kind = match self {
111 Res::Primitive(_) => return Suggestion::Prefix("prim"),
112 Res::Def(kind, _) => kind,
113 };
114
115 let prefix = match kind {
116 DefKind::Fn | DefKind::AssocFn => return Suggestion::Function,
117 DefKind::Macro(MacroKinds::BANG) => return Suggestion::Macro,
120
121 DefKind::Macro(MacroKinds::DERIVE) => "derive",
122 DefKind::Struct => "struct",
123 DefKind::Enum => "enum",
124 DefKind::Trait => "trait",
125 DefKind::Union => "union",
126 DefKind::Mod => "mod",
127 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
128 "const"
129 }
130 DefKind::Static { .. } => "static",
131 DefKind::Field => "field",
132 DefKind::Variant | DefKind::Ctor(..) => "variant",
133 _ => match kind
135 .ns()
136 .expect("tried to calculate a disambiguator for a def without a namespace?")
137 {
138 Namespace::TypeNS => "type",
139 Namespace::ValueNS => "value",
140 Namespace::MacroNS => "macro",
141 },
142 };
143
144 Suggestion::Prefix(prefix)
145 }
146}
147
148impl TryFrom<ResolveRes> for Res {
149 type Error = ();
150
151 fn try_from(res: ResolveRes) -> Result<Self, ()> {
152 use rustc_hir::def::Res::*;
153 match res {
154 Def(kind, id) => Ok(Res::Def(kind, id)),
155 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
156 ToolMod | NonMacroAttr(..) | Err => Result::Err(()),
158 other => bug!("unrecognized res {other:?}"),
159 }
160 }
161}
162
163#[derive(Debug)]
166struct UnresolvedPath<'a> {
167 item_id: DefId,
169 module_id: DefId,
171 partial_res: Option<Res>,
175 unresolved: Cow<'a, str>,
179}
180
181#[derive(Debug)]
182enum ResolutionFailure<'a> {
183 WrongNamespace {
185 res: Res,
187 expected_ns: Namespace,
192 },
193 NotResolved(UnresolvedPath<'a>),
194}
195
196#[derive(Clone, Debug, Hash, PartialEq, Eq)]
197pub(crate) enum UrlFragment {
198 Item(DefId),
199 UserWritten(String),
203}
204
205impl UrlFragment {
206 pub(crate) fn render(&self, s: &mut String, tcx: TyCtxt<'_>) {
208 s.push('#');
209 match self {
210 &UrlFragment::Item(def_id) => {
211 let kind = match tcx.def_kind(def_id) {
212 DefKind::AssocFn => {
213 if tcx.associated_item(def_id).defaultness(tcx).has_value() {
214 "method."
215 } else {
216 "tymethod."
217 }
218 }
219 DefKind::AssocConst => "associatedconstant.",
220 DefKind::AssocTy => "associatedtype.",
221 DefKind::Variant => "variant.",
222 DefKind::Field => {
223 let parent_id = tcx.parent(def_id);
224 if tcx.def_kind(parent_id) == DefKind::Variant {
225 s.push_str("variant.");
226 s.push_str(tcx.item_name(parent_id).as_str());
227 ".field."
228 } else {
229 "structfield."
230 }
231 }
232 kind => bug!("unexpected associated item kind: {kind:?}"),
233 };
234 s.push_str(kind);
235 s.push_str(tcx.item_name(def_id).as_str());
236 }
237 UrlFragment::UserWritten(raw) => s.push_str(raw),
238 }
239 }
240}
241
242#[derive(Clone, Debug, Hash, PartialEq, Eq)]
243pub(crate) struct ResolutionInfo {
244 item_id: DefId,
245 module_id: DefId,
246 dis: Option<Disambiguator>,
247 path_str: Box<str>,
248 extra_fragment: Option<String>,
249}
250
251#[derive(Clone)]
252pub(crate) struct DiagnosticInfo<'a> {
253 item: &'a Item,
254 dox: &'a str,
255 ori_link: &'a str,
256 link_range: MarkdownLinkRange,
257}
258
259pub(crate) struct OwnedDiagnosticInfo {
260 item: Item,
261 dox: String,
262 ori_link: String,
263 link_range: MarkdownLinkRange,
264}
265
266impl From<DiagnosticInfo<'_>> for OwnedDiagnosticInfo {
267 fn from(f: DiagnosticInfo<'_>) -> Self {
268 Self {
269 item: f.item.clone(),
270 dox: f.dox.to_string(),
271 ori_link: f.ori_link.to_string(),
272 link_range: f.link_range.clone(),
273 }
274 }
275}
276
277impl OwnedDiagnosticInfo {
278 pub(crate) fn as_info(&self) -> DiagnosticInfo<'_> {
279 DiagnosticInfo {
280 item: &self.item,
281 ori_link: &self.ori_link,
282 dox: &self.dox,
283 link_range: self.link_range.clone(),
284 }
285 }
286}
287
288pub(crate) struct LinkCollector<'a, 'tcx> {
289 pub(crate) cx: &'a mut DocContext<'tcx>,
290 pub(crate) visited_links: FxHashMap<ResolutionInfo, Option<(Res, Option<UrlFragment>)>>,
293 pub(crate) ambiguous_links: FxIndexMap<(ItemId, String), Vec<AmbiguousLinks>>,
304}
305
306pub(crate) struct AmbiguousLinks {
307 link_text: Box<str>,
308 diag_info: OwnedDiagnosticInfo,
309 resolved: Vec<(Res, Option<UrlFragment>)>,
310}
311
312impl<'tcx> LinkCollector<'_, 'tcx> {
313 fn variant_field<'path>(
320 &self,
321 path_str: &'path str,
322 item_id: DefId,
323 module_id: DefId,
324 ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
325 let tcx = self.cx.tcx;
326 let no_res = || UnresolvedPath {
327 item_id,
328 module_id,
329 partial_res: None,
330 unresolved: path_str.into(),
331 };
332
333 debug!("looking for enum variant {path_str}");
334 let mut split = path_str.rsplitn(3, "::");
335 let variant_field_name = Symbol::intern(split.next().unwrap());
336 let variant_name = Symbol::intern(split.next().ok_or_else(no_res)?);
340
341 let path = split.next().ok_or_else(no_res)?;
344 let ty_res = self.resolve_path(path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
345
346 match ty_res {
347 Res::Def(DefKind::Enum, did) => match tcx.type_of(did).instantiate_identity().kind() {
348 ty::Adt(def, _) if def.is_enum() => {
349 if let Some(variant) = def.variants().iter().find(|v| v.name == variant_name)
350 && let Some(field) =
351 variant.fields.iter().find(|f| f.name == variant_field_name)
352 {
353 Ok((ty_res, field.did))
354 } else {
355 Err(UnresolvedPath {
356 item_id,
357 module_id,
358 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
359 unresolved: variant_field_name.to_string().into(),
360 })
361 }
362 }
363 _ => unreachable!(),
364 },
365 _ => Err(UnresolvedPath {
366 item_id,
367 module_id,
368 partial_res: Some(ty_res),
369 unresolved: variant_name.to_string().into(),
370 }),
371 }
372 }
373
374 fn resolve_primitive_associated_item(
376 &self,
377 prim_ty: PrimitiveType,
378 ns: Namespace,
379 item_name: Symbol,
380 ) -> Vec<(Res, DefId)> {
381 let tcx = self.cx.tcx;
382
383 prim_ty
384 .impls(tcx)
385 .flat_map(|impl_| {
386 filter_assoc_items_by_name_and_namespace(
387 tcx,
388 impl_,
389 Ident::with_dummy_span(item_name),
390 ns,
391 )
392 .map(|item| (Res::Primitive(prim_ty), item.def_id))
393 })
394 .collect::<Vec<_>>()
395 }
396
397 fn resolve_self_ty(&self, path_str: &str, ns: Namespace, item_id: DefId) -> Option<Res> {
398 if ns != TypeNS || path_str != "Self" {
399 return None;
400 }
401
402 let tcx = self.cx.tcx;
403 let self_id = match tcx.def_kind(item_id) {
404 def_kind @ (DefKind::AssocFn
405 | DefKind::AssocConst
406 | DefKind::AssocTy
407 | DefKind::Variant
408 | DefKind::Field) => {
409 let parent_def_id = tcx.parent(item_id);
410 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant {
411 tcx.parent(parent_def_id)
412 } else {
413 parent_def_id
414 }
415 }
416 _ => item_id,
417 };
418
419 match tcx.def_kind(self_id) {
420 DefKind::Impl { .. } => self.def_id_to_res(self_id),
421 DefKind::Use => None,
422 def_kind => Some(Res::Def(def_kind, self_id)),
423 }
424 }
425
426 fn resolve_path(
432 &self,
433 path_str: &str,
434 ns: Namespace,
435 item_id: DefId,
436 module_id: DefId,
437 ) -> Option<Res> {
438 if let res @ Some(..) = self.resolve_self_ty(path_str, ns, item_id) {
439 return res;
440 }
441
442 let result = self
444 .cx
445 .tcx
446 .doc_link_resolutions(module_id)
447 .get(&(Symbol::intern(path_str), ns))
448 .copied()
449 .unwrap_or_else(|| {
454 span_bug!(
455 self.cx.tcx.def_span(item_id),
456 "no resolution for {path_str:?} {ns:?} {module_id:?}",
457 )
458 })
459 .and_then(|res| res.try_into().ok())
460 .or_else(|| resolve_primitive(path_str, ns));
461 debug!("{path_str} resolved to {result:?} in namespace {ns:?}");
462 result
463 }
464
465 fn resolve<'path>(
468 &mut self,
469 path_str: &'path str,
470 ns: Namespace,
471 disambiguator: Option<Disambiguator>,
472 item_id: DefId,
473 module_id: DefId,
474 ) -> Result<Vec<(Res, Option<DefId>)>, UnresolvedPath<'path>> {
475 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
476 return Ok(match res {
477 Res::Def(
478 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Variant,
479 def_id,
480 ) => {
481 vec![(Res::from_def_id(self.cx.tcx, self.cx.tcx.parent(def_id)), Some(def_id))]
482 }
483 _ => vec![(res, None)],
484 });
485 } else if ns == MacroNS {
486 return Err(UnresolvedPath {
487 item_id,
488 module_id,
489 partial_res: None,
490 unresolved: path_str.into(),
491 });
492 }
493
494 let (path_root, item_str) = match path_str.rsplit_once("::") {
497 Some(res @ (_path_root, item_str)) if !item_str.is_empty() => res,
498 _ => {
499 debug!("`::` missing or at end, assuming {path_str} was not in scope");
503 return Err(UnresolvedPath {
504 item_id,
505 module_id,
506 partial_res: None,
507 unresolved: path_str.into(),
508 });
509 }
510 };
511 let item_name = Symbol::intern(item_str);
512
513 match resolve_primitive(path_root, TypeNS)
518 .or_else(|| self.resolve_path(path_root, TypeNS, item_id, module_id))
519 .map(|ty_res| {
520 self.resolve_associated_item(ty_res, item_name, ns, disambiguator, module_id)
521 .into_iter()
522 .map(|(res, def_id)| (res, Some(def_id)))
523 .collect::<Vec<_>>()
524 }) {
525 Some(r) if !r.is_empty() => Ok(r),
526 _ => {
527 if ns == Namespace::ValueNS {
528 self.variant_field(path_str, item_id, module_id)
529 .map(|(res, def_id)| vec![(res, Some(def_id))])
530 } else {
531 Err(UnresolvedPath {
532 item_id,
533 module_id,
534 partial_res: None,
535 unresolved: path_root.into(),
536 })
537 }
538 }
539 }
540 }
541
542 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
546 use PrimitiveType::*;
547 Some(match *self.cx.tcx.type_of(ty_id).instantiate_identity().kind() {
548 ty::Bool => Res::Primitive(Bool),
549 ty::Char => Res::Primitive(Char),
550 ty::Int(ity) => Res::Primitive(ity.into()),
551 ty::Uint(uty) => Res::Primitive(uty.into()),
552 ty::Float(fty) => Res::Primitive(fty.into()),
553 ty::Str => Res::Primitive(Str),
554 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
555 ty::Tuple(_) => Res::Primitive(Tuple),
556 ty::Pat(..) => Res::Primitive(Pat),
557 ty::Array(..) => Res::Primitive(Array),
558 ty::Slice(_) => Res::Primitive(Slice),
559 ty::RawPtr(_, _) => Res::Primitive(RawPointer),
560 ty::Ref(..) => Res::Primitive(Reference),
561 ty::FnDef(..) => panic!("type alias to a function definition"),
562 ty::FnPtr(..) => Res::Primitive(Fn),
563 ty::Never => Res::Primitive(Never),
564 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
565 Res::from_def_id(self.cx.tcx, did)
566 }
567 ty::Alias(..)
568 | ty::Closure(..)
569 | ty::CoroutineClosure(..)
570 | ty::Coroutine(..)
571 | ty::CoroutineWitness(..)
572 | ty::Dynamic(..)
573 | ty::UnsafeBinder(_)
574 | ty::Param(_)
575 | ty::Bound(..)
576 | ty::Placeholder(_)
577 | ty::Infer(_)
578 | ty::Error(_) => return None,
579 })
580 }
581
582 fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
586 use PrimitiveType::*;
587 let tcx = self.cx.tcx;
588
589 Some(match prim {
593 Bool => tcx.types.bool,
594 Str => tcx.types.str_,
595 Char => tcx.types.char,
596 Never => tcx.types.never,
597 I8 => tcx.types.i8,
598 I16 => tcx.types.i16,
599 I32 => tcx.types.i32,
600 I64 => tcx.types.i64,
601 I128 => tcx.types.i128,
602 Isize => tcx.types.isize,
603 F16 => tcx.types.f16,
604 F32 => tcx.types.f32,
605 F64 => tcx.types.f64,
606 F128 => tcx.types.f128,
607 U8 => tcx.types.u8,
608 U16 => tcx.types.u16,
609 U32 => tcx.types.u32,
610 U64 => tcx.types.u64,
611 U128 => tcx.types.u128,
612 Usize => tcx.types.usize,
613 _ => return None,
614 })
615 }
616
617 fn resolve_associated_item(
620 &mut self,
621 root_res: Res,
622 item_name: Symbol,
623 ns: Namespace,
624 disambiguator: Option<Disambiguator>,
625 module_id: DefId,
626 ) -> Vec<(Res, DefId)> {
627 let tcx = self.cx.tcx;
628
629 match root_res {
630 Res::Primitive(prim) => {
631 let items = self.resolve_primitive_associated_item(prim, ns, item_name);
632 if !items.is_empty() {
633 items
634 } else {
636 self.primitive_type_to_ty(prim)
637 .map(|ty| {
638 resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
639 .iter()
640 .map(|item| (root_res, item.def_id))
641 .collect::<Vec<_>>()
642 })
643 .unwrap_or_default()
644 }
645 }
646 Res::Def(DefKind::TyAlias, did) => {
647 let Some(res) = self.def_id_to_res(did) else { return Vec::new() };
651 self.resolve_associated_item(res, item_name, ns, disambiguator, module_id)
652 }
653 Res::Def(
654 def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
655 did,
656 ) => {
657 debug!("looking for associated item named {item_name} for item {did:?}");
658 if ns == TypeNS && def_kind == DefKind::Enum {
660 match tcx.type_of(did).instantiate_identity().kind() {
661 ty::Adt(adt_def, _) => {
662 for variant in adt_def.variants() {
663 if variant.name == item_name {
664 return vec![(root_res, variant.def_id)];
665 }
666 }
667 }
668 _ => unreachable!(),
669 }
670 }
671
672 let search_for_field = || {
673 let (DefKind::Struct | DefKind::Union) = def_kind else { return vec![] };
674 debug!("looking for fields named {item_name} for {did:?}");
675 let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind() else {
691 unreachable!()
692 };
693 def.non_enum_variant()
694 .fields
695 .iter()
696 .filter(|field| field.name == item_name)
697 .map(|field| (root_res, field.did))
698 .collect::<Vec<_>>()
699 };
700
701 if let Some(Disambiguator::Kind(DefKind::Field)) = disambiguator {
702 return search_for_field();
703 }
704
705 let mut assoc_items: Vec<_> = tcx
707 .inherent_impls(did)
708 .iter()
709 .flat_map(|&imp| {
710 filter_assoc_items_by_name_and_namespace(
711 tcx,
712 imp,
713 Ident::with_dummy_span(item_name),
714 ns,
715 )
716 })
717 .map(|item| (root_res, item.def_id))
718 .collect();
719
720 if assoc_items.is_empty() {
721 assoc_items = resolve_associated_trait_item(
727 tcx.type_of(did).instantiate_identity(),
728 module_id,
729 item_name,
730 ns,
731 self.cx,
732 )
733 .into_iter()
734 .map(|item| (root_res, item.def_id))
735 .collect::<Vec<_>>();
736 }
737
738 debug!("got associated item {assoc_items:?}");
739
740 if !assoc_items.is_empty() {
741 return assoc_items;
742 }
743
744 if ns != Namespace::ValueNS {
745 return Vec::new();
746 }
747
748 search_for_field()
749 }
750 Res::Def(DefKind::Trait, did) => filter_assoc_items_by_name_and_namespace(
751 tcx,
752 did,
753 Ident::with_dummy_span(item_name),
754 ns,
755 )
756 .map(|item| {
757 let res = Res::Def(item.as_def_kind(), item.def_id);
758 (res, item.def_id)
759 })
760 .collect::<Vec<_>>(),
761 _ => Vec::new(),
762 }
763 }
764}
765
766fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
767 assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
768}
769
770fn resolve_associated_trait_item<'a>(
776 ty: Ty<'a>,
777 module: DefId,
778 item_name: Symbol,
779 ns: Namespace,
780 cx: &mut DocContext<'a>,
781) -> Vec<ty::AssocItem> {
782 let traits = trait_impls_for(cx, ty, module);
789 let tcx = cx.tcx;
790 debug!("considering traits {traits:?}");
791 let candidates = traits
792 .iter()
793 .flat_map(|&(impl_, trait_)| {
794 filter_assoc_items_by_name_and_namespace(
795 tcx,
796 trait_,
797 Ident::with_dummy_span(item_name),
798 ns,
799 )
800 .map(move |trait_assoc| {
801 trait_assoc_to_impl_assoc_item(tcx, impl_, trait_assoc.def_id)
802 .unwrap_or(*trait_assoc)
803 })
804 })
805 .collect::<Vec<_>>();
806 debug!("the candidates were {candidates:?}");
808 candidates
809}
810
811#[instrument(level = "debug", skip(tcx), ret)]
821fn trait_assoc_to_impl_assoc_item<'tcx>(
822 tcx: TyCtxt<'tcx>,
823 impl_id: DefId,
824 trait_assoc_id: DefId,
825) -> Option<ty::AssocItem> {
826 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
827 debug!(?trait_to_impl_assoc_map);
828 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
829 debug!(?impl_assoc_id);
830 Some(tcx.associated_item(impl_assoc_id))
831}
832
833#[instrument(level = "debug", skip(cx))]
839fn trait_impls_for<'a>(
840 cx: &mut DocContext<'a>,
841 ty: Ty<'a>,
842 module: DefId,
843) -> FxIndexSet<(DefId, DefId)> {
844 let tcx = cx.tcx;
845 let mut impls = FxIndexSet::default();
846
847 for &trait_ in tcx.doc_link_traits_in_scope(module) {
848 tcx.for_each_relevant_impl(trait_, ty, |impl_| {
849 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
850 let impl_type = trait_ref.skip_binder().self_ty();
852 trace!(
853 "comparing type {impl_type} with kind {kind:?} against type {ty:?}",
854 kind = impl_type.kind(),
855 );
856 let saw_impl = impl_type == ty
862 || match (impl_type.kind(), ty.kind()) {
863 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
864 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
865 impl_def.did() == ty_def.did()
866 }
867 _ => false,
868 };
869
870 if saw_impl {
871 impls.insert((impl_, trait_));
872 }
873 });
874 }
875
876 impls
877}
878
879fn is_derive_trait_collision<T>(ns: &PerNS<Result<Vec<(Res, T)>, ResolutionFailure<'_>>>) -> bool {
883 if let (Ok(type_ns), Ok(macro_ns)) = (&ns.type_ns, &ns.macro_ns) {
884 type_ns.iter().any(|(res, _)| matches!(res, Res::Def(DefKind::Trait, _)))
885 && macro_ns.iter().any(|(res, _)| {
886 matches!(
887 res,
888 Res::Def(DefKind::Macro(kinds), _) if kinds.contains(MacroKinds::DERIVE)
889 )
890 })
891 } else {
892 false
893 }
894}
895
896impl DocVisitor<'_> for LinkCollector<'_, '_> {
897 fn visit_item(&mut self, item: &Item) {
898 self.resolve_links(item);
899 self.visit_item_recur(item)
900 }
901}
902
903enum PreprocessingError {
904 MultipleAnchors,
906 Disambiguator(MarkdownLinkRange, String),
907 MalformedGenerics(MalformedGenerics, String),
908}
909
910impl PreprocessingError {
911 fn report(&self, cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
912 match self {
913 PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info),
914 PreprocessingError::Disambiguator(range, msg) => {
915 disambiguator_error(cx, diag_info, range.clone(), msg.clone())
916 }
917 PreprocessingError::MalformedGenerics(err, path_str) => {
918 report_malformed_generics(cx, diag_info, *err, path_str)
919 }
920 }
921 }
922}
923
924#[derive(Clone)]
925struct PreprocessingInfo {
926 path_str: Box<str>,
927 disambiguator: Option<Disambiguator>,
928 extra_fragment: Option<String>,
929 link_text: Box<str>,
930}
931
932pub(crate) struct PreprocessedMarkdownLink(
934 Result<PreprocessingInfo, PreprocessingError>,
935 MarkdownLink,
936);
937
938fn preprocess_link(
945 ori_link: &MarkdownLink,
946 dox: &str,
947) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
948 let can_be_url = !matches!(
952 ori_link.kind,
953 LinkType::ShortcutUnknown | LinkType::CollapsedUnknown | LinkType::ReferenceUnknown
954 );
955
956 if ori_link.link.is_empty() {
958 return None;
959 }
960
961 if can_be_url && ori_link.link.contains('/') {
963 return None;
964 }
965
966 let stripped = ori_link.link.replace('`', "");
967 let mut parts = stripped.split('#');
968
969 let link = parts.next().unwrap();
970 let link = link.trim();
971 if link.is_empty() {
972 return None;
974 }
975 let extra_fragment = parts.next();
976 if parts.next().is_some() {
977 return Some(Err(PreprocessingError::MultipleAnchors));
979 }
980
981 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
983 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
984 Ok(None) => (None, link, link),
985 Err((err_msg, relative_range)) => {
986 if !(can_be_url && should_ignore_link_with_disambiguators(link)) {
988 let disambiguator_range = match range_between_backticks(&ori_link.range, dox) {
989 MarkdownLinkRange::Destination(no_backticks_range) => {
990 MarkdownLinkRange::Destination(
991 (no_backticks_range.start + relative_range.start)
992 ..(no_backticks_range.start + relative_range.end),
993 )
994 }
995 mdlr @ MarkdownLinkRange::WholeLink(_) => mdlr,
996 };
997 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
998 } else {
999 return None;
1000 }
1001 }
1002 };
1003
1004 let is_shortcut_style = ori_link.kind == LinkType::ShortcutUnknown;
1005 let ignore_urllike = can_be_url || (is_shortcut_style && !ori_link.link.contains('`'));
1022 if ignore_urllike && should_ignore_link(path_str) {
1023 return None;
1024 }
1025 if is_shortcut_style
1031 && let Some(suffix) = ori_link.link.strip_prefix('!')
1032 && !suffix.is_empty()
1033 && suffix.chars().all(|c| c.is_ascii_alphabetic())
1034 {
1035 return None;
1036 }
1037
1038 let path_str = match strip_generics_from_path(path_str) {
1040 Ok(path) => path,
1041 Err(err) => {
1042 debug!("link has malformed generics: {path_str}");
1043 return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
1044 }
1045 };
1046
1047 assert!(!path_str.contains(['<', '>'].as_slice()));
1049
1050 if path_str.contains(' ') {
1052 return None;
1053 }
1054
1055 Some(Ok(PreprocessingInfo {
1056 path_str,
1057 disambiguator,
1058 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1059 link_text: Box::<str>::from(link_text),
1060 }))
1061}
1062
1063fn preprocessed_markdown_links(s: &str) -> Vec<PreprocessedMarkdownLink> {
1064 markdown_links(s, |link| {
1065 preprocess_link(&link, s).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1066 })
1067}
1068
1069impl LinkCollector<'_, '_> {
1070 #[instrument(level = "debug", skip_all)]
1071 fn resolve_links(&mut self, item: &Item) {
1072 if !self.cx.render_options.document_private
1073 && let Some(def_id) = item.item_id.as_def_id()
1074 && let Some(def_id) = def_id.as_local()
1075 && !self.cx.tcx.effective_visibilities(()).is_exported(def_id)
1076 && !has_primitive_or_keyword_or_attribute_docs(&item.attrs.other_attrs)
1077 {
1078 return;
1080 }
1081
1082 for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
1087 if !may_have_doc_links(&doc) {
1088 continue;
1089 }
1090 debug!("combined_docs={doc}");
1091 let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
1094 let module_id = match self.cx.tcx.def_kind(item_id) {
1095 DefKind::Mod if item.inner_docs(self.cx.tcx) => item_id,
1096 _ => find_nearest_parent_module(self.cx.tcx, item_id).unwrap(),
1097 };
1098 for md_link in preprocessed_markdown_links(&doc) {
1099 let link = self.resolve_link(&doc, item, item_id, module_id, &md_link);
1100 if let Some(link) = link {
1101 self.cx
1102 .cache
1103 .intra_doc_links
1104 .entry(item.item_or_reexport_id())
1105 .or_default()
1106 .insert(link);
1107 }
1108 }
1109 }
1110 }
1111
1112 pub(crate) fn save_link(&mut self, item_id: ItemId, link: ItemLink) {
1113 self.cx.cache.intra_doc_links.entry(item_id).or_default().insert(link);
1114 }
1115
1116 fn resolve_link(
1120 &mut self,
1121 dox: &String,
1122 item: &Item,
1123 item_id: DefId,
1124 module_id: DefId,
1125 PreprocessedMarkdownLink(pp_link, ori_link): &PreprocessedMarkdownLink,
1126 ) -> Option<ItemLink> {
1127 trace!("considering link '{}'", ori_link.link);
1128
1129 let diag_info = DiagnosticInfo {
1130 item,
1131 dox,
1132 ori_link: &ori_link.link,
1133 link_range: ori_link.range.clone(),
1134 };
1135 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1136 pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1137 let disambiguator = *disambiguator;
1138
1139 let mut resolved = self.resolve_with_disambiguator_cached(
1140 ResolutionInfo {
1141 item_id,
1142 module_id,
1143 dis: disambiguator,
1144 path_str: path_str.clone(),
1145 extra_fragment: extra_fragment.clone(),
1146 },
1147 diag_info.clone(), matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1152 )?;
1153
1154 if resolved.len() > 1 {
1155 let links = AmbiguousLinks {
1156 link_text: link_text.clone(),
1157 diag_info: diag_info.into(),
1158 resolved,
1159 };
1160
1161 self.ambiguous_links
1162 .entry((item.item_id, path_str.to_string()))
1163 .or_default()
1164 .push(links);
1165 None
1166 } else if let Some((res, fragment)) = resolved.pop() {
1167 self.compute_link(res, fragment, path_str, disambiguator, diag_info, link_text)
1168 } else {
1169 None
1170 }
1171 }
1172
1173 fn validate_link(&self, original_did: DefId) -> bool {
1182 let tcx = self.cx.tcx;
1183 let def_kind = tcx.def_kind(original_did);
1184 let did = match def_kind {
1185 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
1186 tcx.parent(original_did)
1188 }
1189 DefKind::Ctor(..) => return self.validate_link(tcx.parent(original_did)),
1192 DefKind::ExternCrate => {
1193 if let Some(local_did) = original_did.as_local() {
1195 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
1196 } else {
1197 original_did
1198 }
1199 }
1200 _ => original_did,
1201 };
1202
1203 let cache = &self.cx.cache;
1204 if !original_did.is_local()
1205 && !cache.effective_visibilities.is_directly_public(tcx, did)
1206 && !cache.document_private
1207 && !cache.primitive_locations.values().any(|&id| id == did)
1208 {
1209 return false;
1210 }
1211
1212 cache.paths.get(&did).is_some()
1213 || cache.external_paths.contains_key(&did)
1214 || !did.is_local()
1215 }
1216
1217 #[allow(rustc::potential_query_instability)]
1218 pub(crate) fn resolve_ambiguities(&mut self) {
1219 let mut ambiguous_links = mem::take(&mut self.ambiguous_links);
1220 for ((item_id, path_str), info_items) in ambiguous_links.iter_mut() {
1221 for info in info_items {
1222 info.resolved.retain(|(res, _)| match res {
1223 Res::Def(_, def_id) => self.validate_link(*def_id),
1224 Res::Primitive(_) => true,
1226 });
1227 let diag_info = info.diag_info.as_info();
1228 match info.resolved.len() {
1229 1 => {
1230 let (res, fragment) = info.resolved.pop().unwrap();
1231 if let Some(link) = self.compute_link(
1232 res,
1233 fragment,
1234 path_str,
1235 None,
1236 diag_info,
1237 &info.link_text,
1238 ) {
1239 self.save_link(*item_id, link);
1240 }
1241 }
1242 0 => {
1243 report_diagnostic(
1244 self.cx.tcx,
1245 BROKEN_INTRA_DOC_LINKS,
1246 format!("all items matching `{path_str}` are private or doc(hidden)"),
1247 &diag_info,
1248 |diag, sp, _| {
1249 if let Some(sp) = sp {
1250 diag.span_label(sp, "unresolved link");
1251 } else {
1252 diag.note("unresolved link");
1253 }
1254 },
1255 );
1256 }
1257 _ => {
1258 let candidates = info
1259 .resolved
1260 .iter()
1261 .map(|(res, fragment)| {
1262 let def_id = if let Some(UrlFragment::Item(def_id)) = fragment {
1263 Some(*def_id)
1264 } else {
1265 None
1266 };
1267 (*res, def_id)
1268 })
1269 .collect::<Vec<_>>();
1270 ambiguity_error(self.cx, &diag_info, path_str, &candidates, true);
1271 }
1272 }
1273 }
1274 }
1275 }
1276
1277 fn compute_link(
1278 &mut self,
1279 mut res: Res,
1280 fragment: Option<UrlFragment>,
1281 path_str: &str,
1282 disambiguator: Option<Disambiguator>,
1283 diag_info: DiagnosticInfo<'_>,
1284 link_text: &Box<str>,
1285 ) -> Option<ItemLink> {
1286 if matches!(
1290 disambiguator,
1291 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1292 ) && !matches!(res, Res::Primitive(_))
1293 && let Some(prim) = resolve_primitive(path_str, TypeNS)
1294 {
1295 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1297 res = prim;
1298 } else {
1299 let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)];
1301 ambiguity_error(self.cx, &diag_info, path_str, candidates, true);
1302 return None;
1303 }
1304 }
1305
1306 match res {
1307 Res::Primitive(_) => {
1308 if let Some(UrlFragment::Item(id)) = fragment {
1309 let kind = self.cx.tcx.def_kind(id);
1318 self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1319 } else {
1320 match disambiguator {
1321 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1322 Some(other) => {
1323 self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1324 return None;
1325 }
1326 }
1327 }
1328
1329 res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1330 link: Box::<str>::from(diag_info.ori_link),
1331 link_text: link_text.clone(),
1332 page_id,
1333 fragment,
1334 })
1335 }
1336 Res::Def(kind, id) => {
1337 let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1338 (self.cx.tcx.def_kind(id), id)
1339 } else {
1340 (kind, id)
1341 };
1342 self.verify_disambiguator(
1343 path_str,
1344 kind_for_dis,
1345 id_for_dis,
1346 disambiguator,
1347 &diag_info,
1348 )?;
1349
1350 let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1351 Some(ItemLink {
1352 link: Box::<str>::from(diag_info.ori_link),
1353 link_text: link_text.clone(),
1354 page_id,
1355 fragment,
1356 })
1357 }
1358 }
1359 }
1360
1361 fn verify_disambiguator(
1362 &self,
1363 path_str: &str,
1364 kind: DefKind,
1365 id: DefId,
1366 disambiguator: Option<Disambiguator>,
1367 diag_info: &DiagnosticInfo<'_>,
1368 ) -> Option<()> {
1369 debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1370
1371 debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1373 match (kind, disambiguator) {
1374 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1375 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1378 | (_, Some(Disambiguator::Namespace(_)))
1380 | (_, None)
1382 => {}
1384 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1385 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1386 self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1387 return None;
1388 }
1389 }
1390
1391 if let Some(dst_id) = id.as_local()
1393 && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1394 && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1395 && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1396 {
1397 privacy_error(self.cx, diag_info, path_str);
1398 }
1399
1400 Some(())
1401 }
1402
1403 fn report_disambiguator_mismatch(
1404 &self,
1405 path_str: &str,
1406 specified: Disambiguator,
1407 resolved: Res,
1408 diag_info: &DiagnosticInfo<'_>,
1409 ) {
1410 let msg = format!("incompatible link kind for `{path_str}`");
1412 let callback = |diag: &mut Diag<'_, ()>, sp: Option<rustc_span::Span>, link_range| {
1413 let note = format!(
1414 "this link resolved to {} {}, which is not {} {}",
1415 resolved.article(),
1416 resolved.descr(),
1417 specified.article(),
1418 specified.descr(),
1419 );
1420 if let Some(sp) = sp {
1421 diag.span_label(sp, note);
1422 } else {
1423 diag.note(note);
1424 }
1425 suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1426 };
1427 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1428 }
1429
1430 fn report_rawptr_assoc_feature_gate(
1431 &self,
1432 dox: &str,
1433 ori_link: &MarkdownLinkRange,
1434 item: &Item,
1435 ) {
1436 let span = match source_span_for_markdown_range(
1437 self.cx.tcx,
1438 dox,
1439 ori_link.inner_range(),
1440 &item.attrs.doc_strings,
1441 ) {
1442 Some((sp, _)) => sp,
1443 None => item.attr_span(self.cx.tcx),
1444 };
1445 rustc_session::parse::feature_err(
1446 self.cx.tcx.sess,
1447 sym::intra_doc_pointers,
1448 span,
1449 "linking to associated items of raw pointers is experimental",
1450 )
1451 .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1452 .emit();
1453 }
1454
1455 fn resolve_with_disambiguator_cached(
1456 &mut self,
1457 key: ResolutionInfo,
1458 diag: DiagnosticInfo<'_>,
1459 cache_errors: bool,
1462 ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1463 if let Some(res) = self.visited_links.get(&key)
1464 && (res.is_some() || cache_errors)
1465 {
1466 return res.clone().map(|r| vec![r]);
1467 }
1468
1469 let mut candidates = self.resolve_with_disambiguator(&key, diag.clone());
1470
1471 if let Some(candidate) = candidates.first()
1474 && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1475 && key.path_str.contains("::")
1476 {
1478 if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1479 self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1480 return None;
1481 } else {
1482 candidates = vec![*candidate];
1483 }
1484 }
1485
1486 if let [candidate, _candidate2, ..] = *candidates
1491 && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1492 {
1493 candidates = vec![candidate];
1494 }
1495
1496 let mut out = Vec::with_capacity(candidates.len());
1497 for (res, def_id) in candidates {
1498 let fragment = match (&key.extra_fragment, def_id) {
1499 (Some(_), Some(def_id)) => {
1500 report_anchor_conflict(self.cx, diag, def_id);
1501 return None;
1502 }
1503 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1504 (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1505 (None, None) => None,
1506 };
1507 out.push((res, fragment));
1508 }
1509 if let [r] = out.as_slice() {
1510 self.visited_links.insert(key, Some(r.clone()));
1511 } else if cache_errors {
1512 self.visited_links.insert(key, None);
1513 }
1514 Some(out)
1515 }
1516
1517 fn resolve_with_disambiguator(
1519 &mut self,
1520 key: &ResolutionInfo,
1521 diag: DiagnosticInfo<'_>,
1522 ) -> Vec<(Res, Option<DefId>)> {
1523 let disambiguator = key.dis;
1524 let path_str = &key.path_str;
1525 let item_id = key.item_id;
1526 let module_id = key.module_id;
1527
1528 match disambiguator.map(Disambiguator::ns) {
1529 Some(expected_ns) => {
1530 match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1531 Ok(candidates) => candidates,
1532 Err(err) => {
1533 let mut err = ResolutionFailure::NotResolved(err);
1537 for other_ns in [TypeNS, ValueNS, MacroNS] {
1538 if other_ns != expected_ns
1539 && let Ok(&[res, ..]) = self
1540 .resolve(path_str, other_ns, None, item_id, module_id)
1541 .as_deref()
1542 {
1543 err = ResolutionFailure::WrongNamespace {
1544 res: full_res(self.cx.tcx, res),
1545 expected_ns,
1546 };
1547 break;
1548 }
1549 }
1550 resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1551 vec![]
1552 }
1553 }
1554 }
1555 None => {
1556 let mut candidate = |ns| {
1558 self.resolve(path_str, ns, None, item_id, module_id)
1559 .map_err(ResolutionFailure::NotResolved)
1560 };
1561
1562 let candidates = PerNS {
1563 macro_ns: candidate(MacroNS),
1564 type_ns: candidate(TypeNS),
1565 value_ns: candidate(ValueNS).and_then(|v_res| {
1566 for (res, _) in v_res.iter() {
1567 if let Res::Def(DefKind::Ctor(..), _) = res {
1569 return Err(ResolutionFailure::WrongNamespace {
1570 res: *res,
1571 expected_ns: TypeNS,
1572 });
1573 }
1574 }
1575 Ok(v_res)
1576 }),
1577 };
1578
1579 let len = candidates
1580 .iter()
1581 .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1582
1583 if len == 0 {
1584 resolution_failure(
1585 self,
1586 diag,
1587 path_str,
1588 disambiguator,
1589 candidates.into_iter().filter_map(|res| res.err()).collect(),
1590 );
1591 vec![]
1592 } else if len == 1 {
1593 candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1594 } else {
1595 let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1596 if len == 2 && has_derive_trait_collision {
1597 candidates.type_ns.unwrap()
1598 } else {
1599 let mut candidates = candidates.map(|candidate| candidate.ok());
1601 if has_derive_trait_collision {
1603 candidates.macro_ns = None;
1604 }
1605 candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1606 }
1607 }
1608 }
1609 }
1610 }
1611}
1612
1613fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1625 let range = match ori_link_range {
1626 mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1627 MarkdownLinkRange::Destination(inner) => inner.clone(),
1628 };
1629 let ori_link_text = &dox[range.clone()];
1630 let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1631 let before_second_backtick_group = ori_link_text
1632 .bytes()
1633 .skip(after_first_backtick_group)
1634 .position(|b| b == b'`')
1635 .unwrap_or(ori_link_text.len());
1636 MarkdownLinkRange::Destination(
1637 (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1638 )
1639}
1640
1641fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1648 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1649}
1650
1651fn should_ignore_link(path_str: &str) -> bool {
1654 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1655}
1656
1657#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1658enum Disambiguator {
1660 Primitive,
1664 Kind(DefKind),
1666 Namespace(Namespace),
1668}
1669
1670impl Disambiguator {
1671 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1677 use Disambiguator::{Kind, Namespace as NS, Primitive};
1678
1679 let suffixes = [
1680 ("!()", DefKind::Macro(MacroKinds::BANG)),
1682 ("!{}", DefKind::Macro(MacroKinds::BANG)),
1683 ("![]", DefKind::Macro(MacroKinds::BANG)),
1684 ("()", DefKind::Fn),
1685 ("!", DefKind::Macro(MacroKinds::BANG)),
1686 ];
1687
1688 if let Some(idx) = link.find('@') {
1689 let (prefix, rest) = link.split_at(idx);
1690 let d = match prefix {
1691 "struct" => Kind(DefKind::Struct),
1693 "enum" => Kind(DefKind::Enum),
1694 "trait" => Kind(DefKind::Trait),
1695 "union" => Kind(DefKind::Union),
1696 "module" | "mod" => Kind(DefKind::Mod),
1697 "const" | "constant" => Kind(DefKind::Const),
1698 "static" => Kind(DefKind::Static {
1699 mutability: Mutability::Not,
1700 nested: false,
1701 safety: Safety::Safe,
1702 }),
1703 "function" | "fn" | "method" => Kind(DefKind::Fn),
1704 "derive" => Kind(DefKind::Macro(MacroKinds::DERIVE)),
1705 "field" => Kind(DefKind::Field),
1706 "variant" => Kind(DefKind::Variant),
1707 "type" => NS(Namespace::TypeNS),
1708 "value" => NS(Namespace::ValueNS),
1709 "macro" => NS(Namespace::MacroNS),
1710 "prim" | "primitive" => Primitive,
1711 _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1712 };
1713
1714 for (suffix, kind) in suffixes {
1715 if let Some(path_str) = rest.strip_suffix(suffix) {
1716 if d.ns() != Kind(kind).ns() {
1717 return Err((
1718 format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1719 0..idx,
1720 ));
1721 } else if path_str.len() > 1 {
1722 return Ok(Some((d, &path_str[1..], &rest[1..])));
1724 }
1725 }
1726 }
1727
1728 Ok(Some((d, &rest[1..], &rest[1..])))
1729 } else {
1730 for (suffix, kind) in suffixes {
1731 if let Some(path_str) = link.strip_suffix(suffix)
1733 && !path_str.is_empty()
1734 {
1735 return Ok(Some((Kind(kind), path_str, link)));
1736 }
1737 }
1738 Ok(None)
1739 }
1740 }
1741
1742 fn ns(self) -> Namespace {
1743 match self {
1744 Self::Namespace(n) => n,
1745 Self::Kind(DefKind::Field) => ValueNS,
1747 Self::Kind(k) => {
1748 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1749 }
1750 Self::Primitive => TypeNS,
1751 }
1752 }
1753
1754 fn article(self) -> &'static str {
1755 match self {
1756 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1757 Self::Kind(k) => k.article(),
1758 Self::Primitive => "a",
1759 }
1760 }
1761
1762 fn descr(self) -> &'static str {
1763 match self {
1764 Self::Namespace(n) => n.descr(),
1765 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1768 Self::Primitive => "builtin type",
1769 }
1770 }
1771}
1772
1773enum Suggestion {
1775 Prefix(&'static str),
1777 Function,
1779 Macro,
1781}
1782
1783impl Suggestion {
1784 fn descr(&self) -> Cow<'static, str> {
1785 match self {
1786 Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1787 Self::Function => "add parentheses".into(),
1788 Self::Macro => "add an exclamation mark".into(),
1789 }
1790 }
1791
1792 fn as_help(&self, path_str: &str) -> String {
1793 match self {
1795 Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1796 Self::Function => format!("{path_str}()"),
1797 Self::Macro => format!("{path_str}!"),
1798 }
1799 }
1800
1801 fn as_help_span(
1802 &self,
1803 ori_link: &str,
1804 sp: rustc_span::Span,
1805 ) -> Vec<(rustc_span::Span, String)> {
1806 let inner_sp = match ori_link.find('(') {
1807 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1808 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1809 }
1810 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1811 None => sp,
1812 };
1813 let inner_sp = match ori_link.find('!') {
1814 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1815 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1816 }
1817 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1818 None => inner_sp,
1819 };
1820 let inner_sp = match ori_link.find('@') {
1821 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1822 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1823 }
1824 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1825 None => inner_sp,
1826 };
1827 match self {
1828 Self::Prefix(prefix) => {
1829 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
1831 if sp.hi() != inner_sp.hi() {
1832 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1833 }
1834 sugg
1835 }
1836 Self::Function => {
1837 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1838 if sp.lo() != inner_sp.lo() {
1839 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1840 }
1841 sugg
1842 }
1843 Self::Macro => {
1844 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1845 if sp.lo() != inner_sp.lo() {
1846 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1847 }
1848 sugg
1849 }
1850 }
1851 }
1852}
1853
1854fn report_diagnostic(
1865 tcx: TyCtxt<'_>,
1866 lint: &'static Lint,
1867 msg: impl Into<DiagMessage> + Display,
1868 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1869 decorate: impl FnOnce(&mut Diag<'_, ()>, Option<rustc_span::Span>, MarkdownLinkRange),
1870) {
1871 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
1872 info!("ignoring warning from parent crate: {msg}");
1874 return;
1875 };
1876
1877 let sp = item.attr_span(tcx);
1878
1879 tcx.node_span_lint(lint, hir_id, sp, |lint| {
1880 lint.primary_message(msg);
1881
1882 let (span, link_range) = match link_range {
1883 MarkdownLinkRange::Destination(md_range) => {
1884 let mut md_range = md_range.clone();
1885 let sp =
1886 source_span_for_markdown_range(tcx, dox, &md_range, &item.attrs.doc_strings)
1887 .map(|(mut sp, _)| {
1888 while dox.as_bytes().get(md_range.start) == Some(&b' ')
1889 || dox.as_bytes().get(md_range.start) == Some(&b'`')
1890 {
1891 md_range.start += 1;
1892 sp = sp.with_lo(sp.lo() + BytePos(1));
1893 }
1894 while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
1895 || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
1896 {
1897 md_range.end -= 1;
1898 sp = sp.with_hi(sp.hi() - BytePos(1));
1899 }
1900 sp
1901 });
1902 (sp, MarkdownLinkRange::Destination(md_range))
1903 }
1904 MarkdownLinkRange::WholeLink(md_range) => (
1905 source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
1906 .map(|(sp, _)| sp),
1907 link_range.clone(),
1908 ),
1909 };
1910
1911 if let Some(sp) = span {
1912 lint.span(sp);
1913 } else {
1914 let md_range = link_range.inner_range().clone();
1919 let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
1920 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1921
1922 lint.note(format!(
1924 "the link appears in this line:\n\n{line}\n\
1925 {indicator: <before$}{indicator:^<found$}",
1926 indicator = "",
1927 before = md_range.start - last_new_line_offset,
1928 found = md_range.len(),
1929 ));
1930 }
1931
1932 decorate(lint, span, link_range);
1933 });
1934}
1935
1936fn resolution_failure(
1942 collector: &mut LinkCollector<'_, '_>,
1943 diag_info: DiagnosticInfo<'_>,
1944 path_str: &str,
1945 disambiguator: Option<Disambiguator>,
1946 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1947) {
1948 let tcx = collector.cx.tcx;
1949 report_diagnostic(
1950 tcx,
1951 BROKEN_INTRA_DOC_LINKS,
1952 format!("unresolved link to `{path_str}`"),
1953 &diag_info,
1954 |diag, sp, link_range| {
1955 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
1956 let assoc_item_not_allowed = |res: Res| {
1957 let name = res.name(tcx);
1958 format!(
1959 "`{name}` is {} {}, not a module or type, and cannot have associated items",
1960 res.article(),
1961 res.descr()
1962 )
1963 };
1964 let mut variants_seen = SmallVec::<[_; 3]>::new();
1966 for mut failure in kinds {
1967 let variant = mem::discriminant(&failure);
1968 if variants_seen.contains(&variant) {
1969 continue;
1970 }
1971 variants_seen.push(variant);
1972
1973 if let ResolutionFailure::NotResolved(UnresolvedPath {
1974 item_id,
1975 module_id,
1976 partial_res,
1977 unresolved,
1978 }) = &mut failure
1979 {
1980 use DefKind::*;
1981
1982 let item_id = *item_id;
1983 let module_id = *module_id;
1984
1985 let mut name = path_str;
1988 'outer: loop {
1989 let Some((start, end)) = name.rsplit_once("::") else {
1991 if partial_res.is_none() {
1993 *unresolved = name.into();
1994 }
1995 break;
1996 };
1997 name = start;
1998 for ns in [TypeNS, ValueNS, MacroNS] {
1999 if let Ok(v_res) =
2000 collector.resolve(start, ns, None, item_id, module_id)
2001 {
2002 debug!("found partial_res={v_res:?}");
2003 if let Some(&res) = v_res.first() {
2004 *partial_res = Some(full_res(tcx, res));
2005 *unresolved = end.into();
2006 break 'outer;
2007 }
2008 }
2009 }
2010 *unresolved = end.into();
2011 }
2012
2013 let last_found_module = match *partial_res {
2014 Some(Res::Def(DefKind::Mod, id)) => Some(id),
2015 None => Some(module_id),
2016 _ => None,
2017 };
2018 if let Some(module) = last_found_module {
2020 let note = if partial_res.is_some() {
2021 let module_name = tcx.item_name(module);
2023 format!("no item named `{unresolved}` in module `{module_name}`")
2024 } else {
2025 format!("no item named `{unresolved}` in scope")
2027 };
2028 if let Some(span) = sp {
2029 diag.span_label(span, note);
2030 } else {
2031 diag.note(note);
2032 }
2033
2034 if !path_str.contains("::") {
2035 if disambiguator.is_none_or(|d| d.ns() == MacroNS)
2036 && collector
2037 .cx
2038 .tcx
2039 .resolutions(())
2040 .all_macro_rules
2041 .contains(&Symbol::intern(path_str))
2042 {
2043 diag.note(format!(
2044 "`macro_rules` named `{path_str}` exists in this crate, \
2045 but it is not in scope at this link's location"
2046 ));
2047 } else {
2048 diag.help(
2051 "to escape `[` and `]` characters, \
2052 add '\\' before them like `\\[` or `\\]`",
2053 );
2054 }
2055 }
2056
2057 continue;
2058 }
2059
2060 let res = partial_res.expect("None case was handled by `last_found_module`");
2062 let kind_did = match res {
2063 Res::Def(kind, did) => Some((kind, did)),
2064 Res::Primitive(_) => None,
2065 };
2066 let is_struct_variant = |did| {
2067 if let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind()
2068 && def.is_enum()
2069 && let Some(variant) =
2070 def.variants().iter().find(|v| v.name == res.name(tcx))
2071 {
2072 variant.ctor.is_none()
2074 } else {
2075 false
2076 }
2077 };
2078 let path_description = if let Some((kind, did)) = kind_did {
2079 match kind {
2080 Mod | ForeignMod => "inner item",
2081 Struct => "field or associated item",
2082 Enum | Union => "variant or associated item",
2083 Variant if is_struct_variant(did) => {
2084 let variant = res.name(tcx);
2085 let note = format!("variant `{variant}` has no such field");
2086 if let Some(span) = sp {
2087 diag.span_label(span, note);
2088 } else {
2089 diag.note(note);
2090 }
2091 return;
2092 }
2093 Variant
2094 | Field
2095 | Closure
2096 | AssocTy
2097 | AssocConst
2098 | AssocFn
2099 | Fn
2100 | Macro(_)
2101 | Const
2102 | ConstParam
2103 | ExternCrate
2104 | Use
2105 | LifetimeParam
2106 | Ctor(_, _)
2107 | AnonConst
2108 | InlineConst => {
2109 let note = assoc_item_not_allowed(res);
2110 if let Some(span) = sp {
2111 diag.span_label(span, note);
2112 } else {
2113 diag.note(note);
2114 }
2115 return;
2116 }
2117 Trait
2118 | TyAlias
2119 | ForeignTy
2120 | OpaqueTy
2121 | TraitAlias
2122 | TyParam
2123 | Static { .. } => "associated item",
2124 Impl { .. } | GlobalAsm | SyntheticCoroutineBody => {
2125 unreachable!("not a path")
2126 }
2127 }
2128 } else {
2129 "associated item"
2130 };
2131 let name = res.name(tcx);
2132 let note = format!(
2133 "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2134 res = res.descr(),
2135 disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2136 );
2137 if let Some(span) = sp {
2138 diag.span_label(span, note);
2139 } else {
2140 diag.note(note);
2141 }
2142
2143 continue;
2144 }
2145 let note = match failure {
2146 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2147 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2148 suggest_disambiguator(
2149 res,
2150 diag,
2151 path_str,
2152 link_range.clone(),
2153 sp,
2154 &diag_info,
2155 );
2156
2157 if let Some(disambiguator) = disambiguator
2158 && !matches!(disambiguator, Disambiguator::Namespace(..))
2159 {
2160 format!(
2161 "this link resolves to {}, which is not {} {}",
2162 item(res),
2163 disambiguator.article(),
2164 disambiguator.descr()
2165 )
2166 } else {
2167 format!(
2168 "this link resolves to {}, which is not in the {} namespace",
2169 item(res),
2170 expected_ns.descr()
2171 )
2172 }
2173 }
2174 };
2175 if let Some(span) = sp {
2176 diag.span_label(span, note);
2177 } else {
2178 diag.note(note);
2179 }
2180 }
2181 },
2182 );
2183}
2184
2185fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2186 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2187 anchor_failure(cx, diag_info, msg, 1)
2188}
2189
2190fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2191 let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2192 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2193 anchor_failure(cx, diag_info, msg, 0)
2194}
2195
2196fn anchor_failure(
2198 cx: &DocContext<'_>,
2199 diag_info: DiagnosticInfo<'_>,
2200 msg: String,
2201 anchor_idx: usize,
2202) {
2203 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2204 if let Some(mut sp) = sp {
2205 if let Some((fragment_offset, _)) =
2206 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2207 {
2208 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2209 }
2210 diag.span_label(sp, "invalid anchor");
2211 }
2212 });
2213}
2214
2215fn disambiguator_error(
2217 cx: &DocContext<'_>,
2218 mut diag_info: DiagnosticInfo<'_>,
2219 disambiguator_range: MarkdownLinkRange,
2220 msg: impl Into<DiagMessage> + Display,
2221) {
2222 diag_info.link_range = disambiguator_range;
2223 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2224 let msg = format!(
2225 "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2226 crate::DOC_RUST_LANG_ORG_VERSION
2227 );
2228 diag.note(msg);
2229 });
2230}
2231
2232fn report_malformed_generics(
2233 cx: &DocContext<'_>,
2234 diag_info: DiagnosticInfo<'_>,
2235 err: MalformedGenerics,
2236 path_str: &str,
2237) {
2238 report_diagnostic(
2239 cx.tcx,
2240 BROKEN_INTRA_DOC_LINKS,
2241 format!("unresolved link to `{path_str}`"),
2242 &diag_info,
2243 |diag, sp, _link_range| {
2244 let note = match err {
2245 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2246 MalformedGenerics::MissingType => "missing type for generic parameters",
2247 MalformedGenerics::HasFullyQualifiedSyntax => {
2248 diag.note(
2249 "see https://github.com/rust-lang/rust/issues/74563 for more information",
2250 );
2251 "fully-qualified syntax is unsupported"
2252 }
2253 MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
2254 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2255 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2256 };
2257 if let Some(span) = sp {
2258 diag.span_label(span, note);
2259 } else {
2260 diag.note(note);
2261 }
2262 },
2263 );
2264}
2265
2266fn ambiguity_error(
2272 cx: &DocContext<'_>,
2273 diag_info: &DiagnosticInfo<'_>,
2274 path_str: &str,
2275 candidates: &[(Res, Option<DefId>)],
2276 emit_error: bool,
2277) -> bool {
2278 let mut descrs = FxHashSet::default();
2279 let mut possible_proc_macro_id = None;
2282 let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro];
2283 let mut kinds = candidates
2284 .iter()
2285 .map(|(res, def_id)| {
2286 let r =
2287 if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2288 if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2289 possible_proc_macro_id = Some(id);
2290 }
2291 r
2292 })
2293 .collect::<Vec<_>>();
2294 if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2303 kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2304 }
2305
2306 kinds.retain(|res| descrs.insert(res.descr()));
2307
2308 if descrs.len() == 1 {
2309 return false;
2312 } else if !emit_error {
2313 return true;
2314 }
2315
2316 let mut msg = format!("`{path_str}` is ");
2317 match kinds.as_slice() {
2318 [res1, res2] => {
2319 msg += &format!(
2320 "both {} {} and {} {}",
2321 res1.article(),
2322 res1.descr(),
2323 res2.article(),
2324 res2.descr()
2325 );
2326 }
2327 _ => {
2328 let mut kinds = kinds.iter().peekable();
2329 while let Some(res) = kinds.next() {
2330 if kinds.peek().is_some() {
2331 msg += &format!("{} {}, ", res.article(), res.descr());
2332 } else {
2333 msg += &format!("and {} {}", res.article(), res.descr());
2334 }
2335 }
2336 }
2337 }
2338
2339 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2340 if let Some(sp) = sp {
2341 diag.span_label(sp, "ambiguous link");
2342 } else {
2343 diag.note("ambiguous link");
2344 }
2345
2346 for res in kinds {
2347 suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2348 }
2349 });
2350 true
2351}
2352
2353fn suggest_disambiguator(
2356 res: Res,
2357 diag: &mut Diag<'_, ()>,
2358 path_str: &str,
2359 link_range: MarkdownLinkRange,
2360 sp: Option<rustc_span::Span>,
2361 diag_info: &DiagnosticInfo<'_>,
2362) {
2363 let suggestion = res.disambiguator_suggestion();
2364 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2365
2366 let ori_link = match link_range {
2367 MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2368 MarkdownLinkRange::WholeLink(_) => None,
2369 };
2370
2371 if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2372 let mut spans = suggestion.as_help_span(ori_link, sp);
2373 if spans.len() > 1 {
2374 diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2375 } else {
2376 let (sp, suggestion_text) = spans.pop().unwrap();
2377 diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2378 }
2379 } else {
2380 diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2381 }
2382}
2383
2384fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2386 let sym;
2387 let item_name = match diag_info.item.name {
2388 Some(name) => {
2389 sym = name;
2390 sym.as_str()
2391 }
2392 None => "<unknown>",
2393 };
2394 let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2395
2396 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2397 if let Some(sp) = sp {
2398 diag.span_label(sp, "this item is private");
2399 }
2400
2401 let note_msg = if cx.render_options.document_private {
2402 "this link resolves only because you passed `--document-private-items`, but will break without"
2403 } else {
2404 "this link will resolve properly if you pass `--document-private-items`"
2405 };
2406 diag.note(note_msg);
2407 });
2408}
2409
2410fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2412 if ns != TypeNS {
2413 return None;
2414 }
2415 use PrimitiveType::*;
2416 let prim = match path_str {
2417 "isize" => Isize,
2418 "i8" => I8,
2419 "i16" => I16,
2420 "i32" => I32,
2421 "i64" => I64,
2422 "i128" => I128,
2423 "usize" => Usize,
2424 "u8" => U8,
2425 "u16" => U16,
2426 "u32" => U32,
2427 "u64" => U64,
2428 "u128" => U128,
2429 "f16" => F16,
2430 "f32" => F32,
2431 "f64" => F64,
2432 "f128" => F128,
2433 "char" => Char,
2434 "bool" | "true" | "false" => Bool,
2435 "str" | "&str" => Str,
2436 "slice" => Slice,
2438 "array" => Array,
2439 "tuple" => Tuple,
2440 "unit" => Unit,
2441 "pointer" | "*const" | "*mut" => RawPointer,
2442 "reference" | "&" | "&mut" => Reference,
2443 "fn" => Fn,
2444 "never" | "!" => Never,
2445 _ => return None,
2446 };
2447 debug!("resolved primitives {prim:?}");
2448 Some(Res::Primitive(prim))
2449}