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