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, 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_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::hygiene::MacroKind;
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(MacroKind::Bang) => return Suggestion::Macro,
119
120 DefKind::Macro(MacroKind::Derive) => "derive",
121 DefKind::Struct => "struct",
122 DefKind::Enum => "enum",
123 DefKind::Trait => "trait",
124 DefKind::Union => "union",
125 DefKind::Mod => "mod",
126 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
127 "const"
128 }
129 DefKind::Static { .. } => "static",
130 DefKind::Field => "field",
131 DefKind::Variant | DefKind::Ctor(..) => "variant",
132 _ => match kind
134 .ns()
135 .expect("tried to calculate a disambiguator for a def without a namespace?")
136 {
137 Namespace::TypeNS => "type",
138 Namespace::ValueNS => "value",
139 Namespace::MacroNS => "macro",
140 },
141 };
142
143 Suggestion::Prefix(prefix)
144 }
145}
146
147impl TryFrom<ResolveRes> for Res {
148 type Error = ();
149
150 fn try_from(res: ResolveRes) -> Result<Self, ()> {
151 use rustc_hir::def::Res::*;
152 match res {
153 Def(kind, id) => Ok(Res::Def(kind, id)),
154 PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
155 ToolMod | NonMacroAttr(..) | Err => Result::Err(()),
157 other => bug!("unrecognized res {other:?}"),
158 }
159 }
160}
161
162#[derive(Debug)]
165struct UnresolvedPath<'a> {
166 item_id: DefId,
168 module_id: DefId,
170 partial_res: Option<Res>,
174 unresolved: Cow<'a, str>,
178}
179
180#[derive(Debug)]
181enum ResolutionFailure<'a> {
182 WrongNamespace {
184 res: Res,
186 expected_ns: Namespace,
191 },
192 NotResolved(UnresolvedPath<'a>),
193}
194
195#[derive(Clone, Debug, Hash, PartialEq, Eq)]
196pub(crate) enum UrlFragment {
197 Item(DefId),
198 UserWritten(String),
202}
203
204impl UrlFragment {
205 pub(crate) fn render(&self, s: &mut String, tcx: TyCtxt<'_>) {
207 s.push('#');
208 match self {
209 &UrlFragment::Item(def_id) => {
210 let kind = match tcx.def_kind(def_id) {
211 DefKind::AssocFn => {
212 if tcx.defaultness(def_id).has_value() {
213 "method."
214 } else {
215 "tymethod."
216 }
217 }
218 DefKind::AssocConst => "associatedconstant.",
219 DefKind::AssocTy => "associatedtype.",
220 DefKind::Variant => "variant.",
221 DefKind::Field => {
222 let parent_id = tcx.parent(def_id);
223 if tcx.def_kind(parent_id) == DefKind::Variant {
224 s.push_str("variant.");
225 s.push_str(tcx.item_name(parent_id).as_str());
226 ".field."
227 } else {
228 "structfield."
229 }
230 }
231 kind => bug!("unexpected associated item kind: {kind:?}"),
232 };
233 s.push_str(kind);
234 s.push_str(tcx.item_name(def_id).as_str());
235 }
236 UrlFragment::UserWritten(raw) => s.push_str(raw),
237 }
238 }
239}
240
241#[derive(Clone, Debug, Hash, PartialEq, Eq)]
242pub(crate) struct ResolutionInfo {
243 item_id: DefId,
244 module_id: DefId,
245 dis: Option<Disambiguator>,
246 path_str: Box<str>,
247 extra_fragment: Option<String>,
248}
249
250#[derive(Clone)]
251pub(crate) struct DiagnosticInfo<'a> {
252 item: &'a Item,
253 dox: &'a str,
254 ori_link: &'a str,
255 link_range: MarkdownLinkRange,
256}
257
258pub(crate) struct OwnedDiagnosticInfo {
259 item: Item,
260 dox: String,
261 ori_link: String,
262 link_range: MarkdownLinkRange,
263}
264
265impl From<DiagnosticInfo<'_>> for OwnedDiagnosticInfo {
266 fn from(f: DiagnosticInfo<'_>) -> Self {
267 Self {
268 item: f.item.clone(),
269 dox: f.dox.to_string(),
270 ori_link: f.ori_link.to_string(),
271 link_range: f.link_range.clone(),
272 }
273 }
274}
275
276impl OwnedDiagnosticInfo {
277 pub(crate) fn as_info(&self) -> DiagnosticInfo<'_> {
278 DiagnosticInfo {
279 item: &self.item,
280 ori_link: &self.ori_link,
281 dox: &self.dox,
282 link_range: self.link_range.clone(),
283 }
284 }
285}
286
287pub(crate) struct LinkCollector<'a, 'tcx> {
288 pub(crate) cx: &'a mut DocContext<'tcx>,
289 pub(crate) visited_links: FxHashMap<ResolutionInfo, Option<(Res, Option<UrlFragment>)>>,
292 pub(crate) ambiguous_links: FxIndexMap<(ItemId, String), Vec<AmbiguousLinks>>,
303}
304
305pub(crate) struct AmbiguousLinks {
306 link_text: Box<str>,
307 diag_info: OwnedDiagnosticInfo,
308 resolved: Vec<(Res, Option<UrlFragment>)>,
309}
310
311impl<'tcx> LinkCollector<'_, 'tcx> {
312 fn variant_field<'path>(
319 &self,
320 path_str: &'path str,
321 item_id: DefId,
322 module_id: DefId,
323 ) -> Result<(Res, DefId), UnresolvedPath<'path>> {
324 let tcx = self.cx.tcx;
325 let no_res = || UnresolvedPath {
326 item_id,
327 module_id,
328 partial_res: None,
329 unresolved: path_str.into(),
330 };
331
332 debug!("looking for enum variant {path_str}");
333 let mut split = path_str.rsplitn(3, "::");
334 let variant_field_name = Symbol::intern(split.next().unwrap());
335 let variant_name = Symbol::intern(split.next().ok_or_else(no_res)?);
339
340 let path = split.next().ok_or_else(no_res)?;
343 let ty_res = self.resolve_path(path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
344
345 match ty_res {
346 Res::Def(DefKind::Enum, did) => match tcx.type_of(did).instantiate_identity().kind() {
347 ty::Adt(def, _) if def.is_enum() => {
348 if let Some(variant) = def.variants().iter().find(|v| v.name == variant_name)
349 && let Some(field) =
350 variant.fields.iter().find(|f| f.name == variant_field_name)
351 {
352 Ok((ty_res, field.did))
353 } else {
354 Err(UnresolvedPath {
355 item_id,
356 module_id,
357 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
358 unresolved: variant_field_name.to_string().into(),
359 })
360 }
361 }
362 _ => unreachable!(),
363 },
364 _ => Err(UnresolvedPath {
365 item_id,
366 module_id,
367 partial_res: Some(ty_res),
368 unresolved: variant_name.to_string().into(),
369 }),
370 }
371 }
372
373 fn resolve_primitive_associated_item(
375 &self,
376 prim_ty: PrimitiveType,
377 ns: Namespace,
378 item_name: Symbol,
379 ) -> Vec<(Res, DefId)> {
380 let tcx = self.cx.tcx;
381
382 prim_ty
383 .impls(tcx)
384 .flat_map(|impl_| {
385 filter_assoc_items_by_name_and_namespace(
386 tcx,
387 impl_,
388 Ident::with_dummy_span(item_name),
389 ns,
390 )
391 .map(|item| (Res::Primitive(prim_ty), item.def_id))
392 })
393 .collect::<Vec<_>>()
394 }
395
396 fn resolve_self_ty(&self, path_str: &str, ns: Namespace, item_id: DefId) -> Option<Res> {
397 if ns != TypeNS || path_str != "Self" {
398 return None;
399 }
400
401 let tcx = self.cx.tcx;
402 let self_id = match tcx.def_kind(item_id) {
403 def_kind @ (DefKind::AssocFn
404 | DefKind::AssocConst
405 | DefKind::AssocTy
406 | DefKind::Variant
407 | DefKind::Field) => {
408 let parent_def_id = tcx.parent(item_id);
409 if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant {
410 tcx.parent(parent_def_id)
411 } else {
412 parent_def_id
413 }
414 }
415 _ => item_id,
416 };
417
418 match tcx.def_kind(self_id) {
419 DefKind::Impl { .. } => self.def_id_to_res(self_id),
420 DefKind::Use => None,
421 def_kind => Some(Res::Def(def_kind, self_id)),
422 }
423 }
424
425 fn resolve_path(
431 &self,
432 path_str: &str,
433 ns: Namespace,
434 item_id: DefId,
435 module_id: DefId,
436 ) -> Option<Res> {
437 if let res @ Some(..) = self.resolve_self_ty(path_str, ns, item_id) {
438 return res;
439 }
440
441 let result = self
443 .cx
444 .tcx
445 .doc_link_resolutions(module_id)
446 .get(&(Symbol::intern(path_str), ns))
447 .copied()
448 .unwrap_or_else(|| {
453 span_bug!(
454 self.cx.tcx.def_span(item_id),
455 "no resolution for {path_str:?} {ns:?} {module_id:?}",
456 )
457 })
458 .and_then(|res| res.try_into().ok())
459 .or_else(|| resolve_primitive(path_str, ns));
460 debug!("{path_str} resolved to {result:?} in namespace {ns:?}");
461 result
462 }
463
464 fn resolve<'path>(
467 &mut self,
468 path_str: &'path str,
469 ns: Namespace,
470 disambiguator: Option<Disambiguator>,
471 item_id: DefId,
472 module_id: DefId,
473 ) -> Result<Vec<(Res, Option<DefId>)>, UnresolvedPath<'path>> {
474 if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
475 return Ok(match res {
476 Res::Def(
477 DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Variant,
478 def_id,
479 ) => {
480 vec![(Res::from_def_id(self.cx.tcx, self.cx.tcx.parent(def_id)), Some(def_id))]
481 }
482 _ => vec![(res, None)],
483 });
484 } else if ns == MacroNS {
485 return Err(UnresolvedPath {
486 item_id,
487 module_id,
488 partial_res: None,
489 unresolved: path_str.into(),
490 });
491 }
492
493 let (path_root, item_str) = match path_str.rsplit_once("::") {
496 Some(res @ (_path_root, item_str)) if !item_str.is_empty() => res,
497 _ => {
498 debug!("`::` missing or at end, assuming {path_str} was not in scope");
502 return Err(UnresolvedPath {
503 item_id,
504 module_id,
505 partial_res: None,
506 unresolved: path_str.into(),
507 });
508 }
509 };
510 let item_name = Symbol::intern(item_str);
511
512 match resolve_primitive(path_root, TypeNS)
517 .or_else(|| self.resolve_path(path_root, TypeNS, item_id, module_id))
518 .map(|ty_res| {
519 self.resolve_associated_item(ty_res, item_name, ns, disambiguator, module_id)
520 .into_iter()
521 .map(|(res, def_id)| (res, Some(def_id)))
522 .collect::<Vec<_>>()
523 }) {
524 Some(r) if !r.is_empty() => Ok(r),
525 _ => {
526 if ns == Namespace::ValueNS {
527 self.variant_field(path_str, item_id, module_id)
528 .map(|(res, def_id)| vec![(res, Some(def_id))])
529 } else {
530 Err(UnresolvedPath {
531 item_id,
532 module_id,
533 partial_res: None,
534 unresolved: path_root.into(),
535 })
536 }
537 }
538 }
539 }
540
541 fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
545 use PrimitiveType::*;
546 Some(match *self.cx.tcx.type_of(ty_id).instantiate_identity().kind() {
547 ty::Bool => Res::Primitive(Bool),
548 ty::Char => Res::Primitive(Char),
549 ty::Int(ity) => Res::Primitive(ity.into()),
550 ty::Uint(uty) => Res::Primitive(uty.into()),
551 ty::Float(fty) => Res::Primitive(fty.into()),
552 ty::Str => Res::Primitive(Str),
553 ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
554 ty::Tuple(_) => Res::Primitive(Tuple),
555 ty::Pat(..) => Res::Primitive(Pat),
556 ty::Array(..) => Res::Primitive(Array),
557 ty::Slice(_) => Res::Primitive(Slice),
558 ty::RawPtr(_, _) => Res::Primitive(RawPointer),
559 ty::Ref(..) => Res::Primitive(Reference),
560 ty::FnDef(..) => panic!("type alias to a function definition"),
561 ty::FnPtr(..) => Res::Primitive(Fn),
562 ty::Never => Res::Primitive(Never),
563 ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
564 Res::from_def_id(self.cx.tcx, did)
565 }
566 ty::Alias(..)
567 | ty::Closure(..)
568 | ty::CoroutineClosure(..)
569 | ty::Coroutine(..)
570 | ty::CoroutineWitness(..)
571 | ty::Dynamic(..)
572 | ty::UnsafeBinder(_)
573 | ty::Param(_)
574 | ty::Bound(..)
575 | ty::Placeholder(_)
576 | ty::Infer(_)
577 | ty::Error(_) => return None,
578 })
579 }
580
581 fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
585 use PrimitiveType::*;
586 let tcx = self.cx.tcx;
587
588 Some(match prim {
592 Bool => tcx.types.bool,
593 Str => tcx.types.str_,
594 Char => tcx.types.char,
595 Never => tcx.types.never,
596 I8 => tcx.types.i8,
597 I16 => tcx.types.i16,
598 I32 => tcx.types.i32,
599 I64 => tcx.types.i64,
600 I128 => tcx.types.i128,
601 Isize => tcx.types.isize,
602 F16 => tcx.types.f16,
603 F32 => tcx.types.f32,
604 F64 => tcx.types.f64,
605 F128 => tcx.types.f128,
606 U8 => tcx.types.u8,
607 U16 => tcx.types.u16,
608 U32 => tcx.types.u32,
609 U64 => tcx.types.u64,
610 U128 => tcx.types.u128,
611 Usize => tcx.types.usize,
612 _ => return None,
613 })
614 }
615
616 fn resolve_associated_item(
619 &mut self,
620 root_res: Res,
621 item_name: Symbol,
622 ns: Namespace,
623 disambiguator: Option<Disambiguator>,
624 module_id: DefId,
625 ) -> Vec<(Res, DefId)> {
626 let tcx = self.cx.tcx;
627
628 match root_res {
629 Res::Primitive(prim) => {
630 let items = self.resolve_primitive_associated_item(prim, ns, item_name);
631 if !items.is_empty() {
632 items
633 } else {
635 self.primitive_type_to_ty(prim)
636 .map(|ty| {
637 resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
638 .iter()
639 .map(|item| (root_res, item.def_id))
640 .collect::<Vec<_>>()
641 })
642 .unwrap_or_default()
643 }
644 }
645 Res::Def(DefKind::TyAlias, did) => {
646 let Some(res) = self.def_id_to_res(did) else { return Vec::new() };
650 self.resolve_associated_item(res, item_name, ns, disambiguator, module_id)
651 }
652 Res::Def(
653 def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
654 did,
655 ) => {
656 debug!("looking for associated item named {item_name} for item {did:?}");
657 if ns == TypeNS && def_kind == DefKind::Enum {
659 match tcx.type_of(did).instantiate_identity().kind() {
660 ty::Adt(adt_def, _) => {
661 for variant in adt_def.variants() {
662 if variant.name == item_name {
663 return vec![(root_res, variant.def_id)];
664 }
665 }
666 }
667 _ => unreachable!(),
668 }
669 }
670
671 let search_for_field = || {
672 let (DefKind::Struct | DefKind::Union) = def_kind else { return vec![] };
673 debug!("looking for fields named {item_name} for {did:?}");
674 let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind() else {
690 unreachable!()
691 };
692 def.non_enum_variant()
693 .fields
694 .iter()
695 .filter(|field| field.name == item_name)
696 .map(|field| (root_res, field.did))
697 .collect::<Vec<_>>()
698 };
699
700 if let Some(Disambiguator::Kind(DefKind::Field)) = disambiguator {
701 return search_for_field();
702 }
703
704 let mut assoc_items: Vec<_> = tcx
706 .inherent_impls(did)
707 .iter()
708 .flat_map(|&imp| {
709 filter_assoc_items_by_name_and_namespace(
710 tcx,
711 imp,
712 Ident::with_dummy_span(item_name),
713 ns,
714 )
715 })
716 .map(|item| (root_res, item.def_id))
717 .collect();
718
719 if assoc_items.is_empty() {
720 assoc_items = resolve_associated_trait_item(
726 tcx.type_of(did).instantiate_identity(),
727 module_id,
728 item_name,
729 ns,
730 self.cx,
731 )
732 .into_iter()
733 .map(|item| (root_res, item.def_id))
734 .collect::<Vec<_>>();
735 }
736
737 debug!("got associated item {assoc_items:?}");
738
739 if !assoc_items.is_empty() {
740 return assoc_items;
741 }
742
743 if ns != Namespace::ValueNS {
744 return Vec::new();
745 }
746
747 search_for_field()
748 }
749 Res::Def(DefKind::Trait, did) => filter_assoc_items_by_name_and_namespace(
750 tcx,
751 did,
752 Ident::with_dummy_span(item_name),
753 ns,
754 )
755 .map(|item| {
756 let res = Res::Def(item.as_def_kind(), item.def_id);
757 (res, item.def_id)
758 })
759 .collect::<Vec<_>>(),
760 _ => Vec::new(),
761 }
762 }
763}
764
765fn full_res(tcx: TyCtxt<'_>, (base, assoc_item): (Res, Option<DefId>)) -> Res {
766 assoc_item.map_or(base, |def_id| Res::from_def_id(tcx, def_id))
767}
768
769fn resolve_associated_trait_item<'a>(
775 ty: Ty<'a>,
776 module: DefId,
777 item_name: Symbol,
778 ns: Namespace,
779 cx: &mut DocContext<'a>,
780) -> Vec<ty::AssocItem> {
781 let traits = trait_impls_for(cx, ty, module);
788 let tcx = cx.tcx;
789 debug!("considering traits {traits:?}");
790 let candidates = traits
791 .iter()
792 .flat_map(|&(impl_, trait_)| {
793 filter_assoc_items_by_name_and_namespace(
794 tcx,
795 trait_,
796 Ident::with_dummy_span(item_name),
797 ns,
798 )
799 .map(move |trait_assoc| {
800 trait_assoc_to_impl_assoc_item(tcx, impl_, trait_assoc.def_id)
801 .unwrap_or(*trait_assoc)
802 })
803 })
804 .collect::<Vec<_>>();
805 debug!("the candidates were {candidates:?}");
807 candidates
808}
809
810#[instrument(level = "debug", skip(tcx), ret)]
820fn trait_assoc_to_impl_assoc_item<'tcx>(
821 tcx: TyCtxt<'tcx>,
822 impl_id: DefId,
823 trait_assoc_id: DefId,
824) -> Option<ty::AssocItem> {
825 let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
826 debug!(?trait_to_impl_assoc_map);
827 let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
828 debug!(?impl_assoc_id);
829 Some(tcx.associated_item(impl_assoc_id))
830}
831
832#[instrument(level = "debug", skip(cx))]
838fn trait_impls_for<'a>(
839 cx: &mut DocContext<'a>,
840 ty: Ty<'a>,
841 module: DefId,
842) -> FxIndexSet<(DefId, DefId)> {
843 let tcx = cx.tcx;
844 let mut impls = FxIndexSet::default();
845
846 for &trait_ in tcx.doc_link_traits_in_scope(module) {
847 tcx.for_each_relevant_impl(trait_, ty, |impl_| {
848 let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
849 let impl_type = trait_ref.skip_binder().self_ty();
851 trace!(
852 "comparing type {impl_type} with kind {kind:?} against type {ty:?}",
853 kind = impl_type.kind(),
854 );
855 let saw_impl = impl_type == ty
861 || match (impl_type.kind(), ty.kind()) {
862 (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
863 debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
864 impl_def.did() == ty_def.did()
865 }
866 _ => false,
867 };
868
869 if saw_impl {
870 impls.insert((impl_, trait_));
871 }
872 });
873 }
874
875 impls
876}
877
878fn is_derive_trait_collision<T>(ns: &PerNS<Result<Vec<(Res, T)>, ResolutionFailure<'_>>>) -> bool {
882 if let (Ok(type_ns), Ok(macro_ns)) = (&ns.type_ns, &ns.macro_ns) {
883 type_ns.iter().any(|(res, _)| matches!(res, Res::Def(DefKind::Trait, _)))
884 && macro_ns
885 .iter()
886 .any(|(res, _)| matches!(res, Res::Def(DefKind::Macro(MacroKind::Derive), _)))
887 } else {
888 false
889 }
890}
891
892impl DocVisitor<'_> for LinkCollector<'_, '_> {
893 fn visit_item(&mut self, item: &Item) {
894 self.resolve_links(item);
895 self.visit_item_recur(item)
896 }
897}
898
899enum PreprocessingError {
900 MultipleAnchors,
902 Disambiguator(MarkdownLinkRange, String),
903 MalformedGenerics(MalformedGenerics, String),
904}
905
906impl PreprocessingError {
907 fn report(&self, cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
908 match self {
909 PreprocessingError::MultipleAnchors => report_multiple_anchors(cx, diag_info),
910 PreprocessingError::Disambiguator(range, msg) => {
911 disambiguator_error(cx, diag_info, range.clone(), msg.clone())
912 }
913 PreprocessingError::MalformedGenerics(err, path_str) => {
914 report_malformed_generics(cx, diag_info, *err, path_str)
915 }
916 }
917 }
918}
919
920#[derive(Clone)]
921struct PreprocessingInfo {
922 path_str: Box<str>,
923 disambiguator: Option<Disambiguator>,
924 extra_fragment: Option<String>,
925 link_text: Box<str>,
926}
927
928pub(crate) struct PreprocessedMarkdownLink(
930 Result<PreprocessingInfo, PreprocessingError>,
931 MarkdownLink,
932);
933
934fn preprocess_link(
941 ori_link: &MarkdownLink,
942 dox: &str,
943) -> Option<Result<PreprocessingInfo, PreprocessingError>> {
944 if ori_link.link.is_empty() {
946 return None;
947 }
948
949 if ori_link.link.contains('/') {
951 return None;
952 }
953
954 let stripped = ori_link.link.replace('`', "");
955 let mut parts = stripped.split('#');
956
957 let link = parts.next().unwrap();
958 let link = link.trim();
959 if link.is_empty() {
960 return None;
962 }
963 let extra_fragment = parts.next();
964 if parts.next().is_some() {
965 return Some(Err(PreprocessingError::MultipleAnchors));
967 }
968
969 let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
971 Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
972 Ok(None) => (None, link, link),
973 Err((err_msg, relative_range)) => {
974 if !should_ignore_link_with_disambiguators(link) {
976 let disambiguator_range = match range_between_backticks(&ori_link.range, dox) {
977 MarkdownLinkRange::Destination(no_backticks_range) => {
978 MarkdownLinkRange::Destination(
979 (no_backticks_range.start + relative_range.start)
980 ..(no_backticks_range.start + relative_range.end),
981 )
982 }
983 mdlr @ MarkdownLinkRange::WholeLink(_) => mdlr,
984 };
985 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
986 } else {
987 return None;
988 }
989 }
990 };
991
992 if should_ignore_link(path_str) {
993 return None;
994 }
995
996 let path_str = match strip_generics_from_path(path_str) {
998 Ok(path) => path,
999 Err(err) => {
1000 debug!("link has malformed generics: {path_str}");
1001 return Some(Err(PreprocessingError::MalformedGenerics(err, path_str.to_owned())));
1002 }
1003 };
1004
1005 assert!(!path_str.contains(['<', '>'].as_slice()));
1007
1008 if path_str.contains(' ') {
1010 return None;
1011 }
1012
1013 Some(Ok(PreprocessingInfo {
1014 path_str,
1015 disambiguator,
1016 extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1017 link_text: Box::<str>::from(link_text),
1018 }))
1019}
1020
1021fn preprocessed_markdown_links(s: &str) -> Vec<PreprocessedMarkdownLink> {
1022 markdown_links(s, |link| {
1023 preprocess_link(&link, s).map(|pp_link| PreprocessedMarkdownLink(pp_link, link))
1024 })
1025}
1026
1027impl LinkCollector<'_, '_> {
1028 #[instrument(level = "debug", skip_all)]
1029 fn resolve_links(&mut self, item: &Item) {
1030 if !self.cx.render_options.document_private
1031 && let Some(def_id) = item.item_id.as_def_id()
1032 && let Some(def_id) = def_id.as_local()
1033 && !self.cx.tcx.effective_visibilities(()).is_exported(def_id)
1034 && !has_primitive_or_keyword_docs(&item.attrs.other_attrs)
1035 {
1036 return;
1038 }
1039
1040 for (item_id, doc) in prepare_to_doc_link_resolution(&item.attrs.doc_strings) {
1045 if !may_have_doc_links(&doc) {
1046 continue;
1047 }
1048 debug!("combined_docs={doc}");
1049 let item_id = item_id.unwrap_or_else(|| item.item_id.expect_def_id());
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.cache.intra_doc_links.entry(item.item_id).or_default().insert(link);
1060 }
1061 }
1062 }
1063 }
1064
1065 pub(crate) fn save_link(&mut self, item_id: ItemId, link: ItemLink) {
1066 self.cx.cache.intra_doc_links.entry(item_id).or_default().insert(link);
1067 }
1068
1069 fn resolve_link(
1073 &mut self,
1074 dox: &String,
1075 item: &Item,
1076 item_id: DefId,
1077 module_id: DefId,
1078 PreprocessedMarkdownLink(pp_link, ori_link): &PreprocessedMarkdownLink,
1079 ) -> Option<ItemLink> {
1080 trace!("considering link '{}'", ori_link.link);
1081
1082 let diag_info = DiagnosticInfo {
1083 item,
1084 dox,
1085 ori_link: &ori_link.link,
1086 link_range: ori_link.range.clone(),
1087 };
1088 let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1089 pp_link.as_ref().map_err(|err| err.report(self.cx, diag_info.clone())).ok()?;
1090 let disambiguator = *disambiguator;
1091
1092 let mut resolved = self.resolve_with_disambiguator_cached(
1093 ResolutionInfo {
1094 item_id,
1095 module_id,
1096 dis: disambiguator,
1097 path_str: path_str.clone(),
1098 extra_fragment: extra_fragment.clone(),
1099 },
1100 diag_info.clone(), matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1105 )?;
1106
1107 if resolved.len() > 1 {
1108 let links = AmbiguousLinks {
1109 link_text: link_text.clone(),
1110 diag_info: diag_info.into(),
1111 resolved,
1112 };
1113
1114 self.ambiguous_links
1115 .entry((item.item_id, path_str.to_string()))
1116 .or_default()
1117 .push(links);
1118 None
1119 } else if let Some((res, fragment)) = resolved.pop() {
1120 self.compute_link(res, fragment, path_str, disambiguator, diag_info, link_text)
1121 } else {
1122 None
1123 }
1124 }
1125
1126 fn validate_link(&self, original_did: DefId) -> bool {
1135 let tcx = self.cx.tcx;
1136 let def_kind = tcx.def_kind(original_did);
1137 let did = match def_kind {
1138 DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst | DefKind::Variant => {
1139 tcx.parent(original_did)
1141 }
1142 DefKind::Ctor(..) => return self.validate_link(tcx.parent(original_did)),
1145 DefKind::ExternCrate => {
1146 if let Some(local_did) = original_did.as_local() {
1148 tcx.extern_mod_stmt_cnum(local_did).unwrap_or(LOCAL_CRATE).as_def_id()
1149 } else {
1150 original_did
1151 }
1152 }
1153 _ => original_did,
1154 };
1155
1156 let cache = &self.cx.cache;
1157 if !original_did.is_local()
1158 && !cache.effective_visibilities.is_directly_public(tcx, did)
1159 && !cache.document_private
1160 && !cache.primitive_locations.values().any(|&id| id == did)
1161 {
1162 return false;
1163 }
1164
1165 cache.paths.get(&did).is_some()
1166 || cache.external_paths.contains_key(&did)
1167 || !did.is_local()
1168 }
1169
1170 #[allow(rustc::potential_query_instability)]
1171 pub(crate) fn resolve_ambiguities(&mut self) {
1172 let mut ambiguous_links = mem::take(&mut self.ambiguous_links);
1173 for ((item_id, path_str), info_items) in ambiguous_links.iter_mut() {
1174 for info in info_items {
1175 info.resolved.retain(|(res, _)| match res {
1176 Res::Def(_, def_id) => self.validate_link(*def_id),
1177 Res::Primitive(_) => true,
1179 });
1180 let diag_info = info.diag_info.as_info();
1181 match info.resolved.len() {
1182 1 => {
1183 let (res, fragment) = info.resolved.pop().unwrap();
1184 if let Some(link) = self.compute_link(
1185 res,
1186 fragment,
1187 path_str,
1188 None,
1189 diag_info,
1190 &info.link_text,
1191 ) {
1192 self.save_link(*item_id, link);
1193 }
1194 }
1195 0 => {
1196 report_diagnostic(
1197 self.cx.tcx,
1198 BROKEN_INTRA_DOC_LINKS,
1199 format!("all items matching `{path_str}` are private or doc(hidden)"),
1200 &diag_info,
1201 |diag, sp, _| {
1202 if let Some(sp) = sp {
1203 diag.span_label(sp, "unresolved link");
1204 } else {
1205 diag.note("unresolved link");
1206 }
1207 },
1208 );
1209 }
1210 _ => {
1211 let candidates = info
1212 .resolved
1213 .iter()
1214 .map(|(res, fragment)| {
1215 let def_id = if let Some(UrlFragment::Item(def_id)) = fragment {
1216 Some(*def_id)
1217 } else {
1218 None
1219 };
1220 (*res, def_id)
1221 })
1222 .collect::<Vec<_>>();
1223 ambiguity_error(self.cx, &diag_info, path_str, &candidates, true);
1224 }
1225 }
1226 }
1227 }
1228 }
1229
1230 fn compute_link(
1231 &mut self,
1232 mut res: Res,
1233 fragment: Option<UrlFragment>,
1234 path_str: &str,
1235 disambiguator: Option<Disambiguator>,
1236 diag_info: DiagnosticInfo<'_>,
1237 link_text: &Box<str>,
1238 ) -> Option<ItemLink> {
1239 if matches!(
1243 disambiguator,
1244 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1245 ) && !matches!(res, Res::Primitive(_))
1246 && let Some(prim) = resolve_primitive(path_str, TypeNS)
1247 {
1248 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1250 res = prim;
1251 } else {
1252 let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)];
1254 ambiguity_error(self.cx, &diag_info, path_str, candidates, true);
1255 return None;
1256 }
1257 }
1258
1259 match res {
1260 Res::Primitive(_) => {
1261 if let Some(UrlFragment::Item(id)) = fragment {
1262 let kind = self.cx.tcx.def_kind(id);
1271 self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1272 } else {
1273 match disambiguator {
1274 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1275 Some(other) => {
1276 self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1277 return None;
1278 }
1279 }
1280 }
1281
1282 res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1283 link: Box::<str>::from(diag_info.ori_link),
1284 link_text: link_text.clone(),
1285 page_id,
1286 fragment,
1287 })
1288 }
1289 Res::Def(kind, id) => {
1290 let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1291 (self.cx.tcx.def_kind(id), id)
1292 } else {
1293 (kind, id)
1294 };
1295 self.verify_disambiguator(
1296 path_str,
1297 kind_for_dis,
1298 id_for_dis,
1299 disambiguator,
1300 &diag_info,
1301 )?;
1302
1303 let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1304 Some(ItemLink {
1305 link: Box::<str>::from(diag_info.ori_link),
1306 link_text: link_text.clone(),
1307 page_id,
1308 fragment,
1309 })
1310 }
1311 }
1312 }
1313
1314 fn verify_disambiguator(
1315 &self,
1316 path_str: &str,
1317 kind: DefKind,
1318 id: DefId,
1319 disambiguator: Option<Disambiguator>,
1320 diag_info: &DiagnosticInfo<'_>,
1321 ) -> Option<()> {
1322 debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1323
1324 debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1326 match (kind, disambiguator) {
1327 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1328 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1331 | (_, Some(Disambiguator::Namespace(_)))
1333 | (_, None)
1335 => {}
1337 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1338 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1339 self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1340 return None;
1341 }
1342 }
1343
1344 if let Some(dst_id) = id.as_local()
1346 && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1347 && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1348 && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1349 {
1350 privacy_error(self.cx, diag_info, path_str);
1351 }
1352
1353 Some(())
1354 }
1355
1356 fn report_disambiguator_mismatch(
1357 &self,
1358 path_str: &str,
1359 specified: Disambiguator,
1360 resolved: Res,
1361 diag_info: &DiagnosticInfo<'_>,
1362 ) {
1363 let msg = format!("incompatible link kind for `{path_str}`");
1365 let callback = |diag: &mut Diag<'_, ()>, sp: Option<rustc_span::Span>, link_range| {
1366 let note = format!(
1367 "this link resolved to {} {}, which is not {} {}",
1368 resolved.article(),
1369 resolved.descr(),
1370 specified.article(),
1371 specified.descr(),
1372 );
1373 if let Some(sp) = sp {
1374 diag.span_label(sp, note);
1375 } else {
1376 diag.note(note);
1377 }
1378 suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1379 };
1380 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1381 }
1382
1383 fn report_rawptr_assoc_feature_gate(
1384 &self,
1385 dox: &str,
1386 ori_link: &MarkdownLinkRange,
1387 item: &Item,
1388 ) {
1389 let span = match source_span_for_markdown_range(
1390 self.cx.tcx,
1391 dox,
1392 ori_link.inner_range(),
1393 &item.attrs.doc_strings,
1394 ) {
1395 Some((sp, _)) => sp,
1396 None => item.attr_span(self.cx.tcx),
1397 };
1398 rustc_session::parse::feature_err(
1399 self.cx.tcx.sess,
1400 sym::intra_doc_pointers,
1401 span,
1402 "linking to associated items of raw pointers is experimental",
1403 )
1404 .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1405 .emit();
1406 }
1407
1408 fn resolve_with_disambiguator_cached(
1409 &mut self,
1410 key: ResolutionInfo,
1411 diag: DiagnosticInfo<'_>,
1412 cache_errors: bool,
1415 ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1416 if let Some(res) = self.visited_links.get(&key)
1417 && (res.is_some() || cache_errors)
1418 {
1419 return res.clone().map(|r| vec![r]);
1420 }
1421
1422 let mut candidates = self.resolve_with_disambiguator(&key, diag.clone());
1423
1424 if let Some(candidate) = candidates.first()
1427 && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1428 && key.path_str.contains("::")
1429 {
1431 if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1432 self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1433 return None;
1434 } else {
1435 candidates = vec![*candidate];
1436 }
1437 }
1438
1439 if let [candidate, _candidate2, ..] = *candidates
1444 && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1445 {
1446 candidates = vec![candidate];
1447 }
1448
1449 let mut out = Vec::with_capacity(candidates.len());
1450 for (res, def_id) in candidates {
1451 let fragment = match (&key.extra_fragment, def_id) {
1452 (Some(_), Some(def_id)) => {
1453 report_anchor_conflict(self.cx, diag, def_id);
1454 return None;
1455 }
1456 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1457 (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1458 (None, None) => None,
1459 };
1460 out.push((res, fragment));
1461 }
1462 if let [r] = out.as_slice() {
1463 self.visited_links.insert(key, Some(r.clone()));
1464 } else if cache_errors {
1465 self.visited_links.insert(key, None);
1466 }
1467 Some(out)
1468 }
1469
1470 fn resolve_with_disambiguator(
1472 &mut self,
1473 key: &ResolutionInfo,
1474 diag: DiagnosticInfo<'_>,
1475 ) -> Vec<(Res, Option<DefId>)> {
1476 let disambiguator = key.dis;
1477 let path_str = &key.path_str;
1478 let item_id = key.item_id;
1479 let module_id = key.module_id;
1480
1481 match disambiguator.map(Disambiguator::ns) {
1482 Some(expected_ns) => {
1483 match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1484 Ok(candidates) => candidates,
1485 Err(err) => {
1486 let mut err = ResolutionFailure::NotResolved(err);
1490 for other_ns in [TypeNS, ValueNS, MacroNS] {
1491 if other_ns != expected_ns
1492 && let Ok(&[res, ..]) = self
1493 .resolve(path_str, other_ns, None, item_id, module_id)
1494 .as_deref()
1495 {
1496 err = ResolutionFailure::WrongNamespace {
1497 res: full_res(self.cx.tcx, res),
1498 expected_ns,
1499 };
1500 break;
1501 }
1502 }
1503 resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1504 vec![]
1505 }
1506 }
1507 }
1508 None => {
1509 let mut candidate = |ns| {
1511 self.resolve(path_str, ns, None, item_id, module_id)
1512 .map_err(ResolutionFailure::NotResolved)
1513 };
1514
1515 let candidates = PerNS {
1516 macro_ns: candidate(MacroNS),
1517 type_ns: candidate(TypeNS),
1518 value_ns: candidate(ValueNS).and_then(|v_res| {
1519 for (res, _) in v_res.iter() {
1520 if let Res::Def(DefKind::Ctor(..), _) = res {
1522 return Err(ResolutionFailure::WrongNamespace {
1523 res: *res,
1524 expected_ns: TypeNS,
1525 });
1526 }
1527 }
1528 Ok(v_res)
1529 }),
1530 };
1531
1532 let len = candidates
1533 .iter()
1534 .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1535
1536 if len == 0 {
1537 resolution_failure(
1538 self,
1539 diag,
1540 path_str,
1541 disambiguator,
1542 candidates.into_iter().filter_map(|res| res.err()).collect(),
1543 );
1544 vec![]
1545 } else if len == 1 {
1546 candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1547 } else {
1548 let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1549 if len == 2 && has_derive_trait_collision {
1550 candidates.type_ns.unwrap()
1551 } else {
1552 let mut candidates = candidates.map(|candidate| candidate.ok());
1554 if has_derive_trait_collision {
1556 candidates.macro_ns = None;
1557 }
1558 candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1559 }
1560 }
1561 }
1562 }
1563 }
1564}
1565
1566fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1578 let range = match ori_link_range {
1579 mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1580 MarkdownLinkRange::Destination(inner) => inner.clone(),
1581 };
1582 let ori_link_text = &dox[range.clone()];
1583 let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1584 let before_second_backtick_group = ori_link_text
1585 .bytes()
1586 .skip(after_first_backtick_group)
1587 .position(|b| b == b'`')
1588 .unwrap_or(ori_link_text.len());
1589 MarkdownLinkRange::Destination(
1590 (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1591 )
1592}
1593
1594fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1601 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1602}
1603
1604fn should_ignore_link(path_str: &str) -> bool {
1607 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1608}
1609
1610#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1611enum Disambiguator {
1613 Primitive,
1617 Kind(DefKind),
1619 Namespace(Namespace),
1621}
1622
1623impl Disambiguator {
1624 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1630 use Disambiguator::{Kind, Namespace as NS, Primitive};
1631
1632 let suffixes = [
1633 ("!()", DefKind::Macro(MacroKind::Bang)),
1635 ("!{}", DefKind::Macro(MacroKind::Bang)),
1636 ("![]", DefKind::Macro(MacroKind::Bang)),
1637 ("()", DefKind::Fn),
1638 ("!", DefKind::Macro(MacroKind::Bang)),
1639 ];
1640
1641 if let Some(idx) = link.find('@') {
1642 let (prefix, rest) = link.split_at(idx);
1643 let d = match prefix {
1644 "struct" => Kind(DefKind::Struct),
1646 "enum" => Kind(DefKind::Enum),
1647 "trait" => Kind(DefKind::Trait),
1648 "union" => Kind(DefKind::Union),
1649 "module" | "mod" => Kind(DefKind::Mod),
1650 "const" | "constant" => Kind(DefKind::Const),
1651 "static" => Kind(DefKind::Static {
1652 mutability: Mutability::Not,
1653 nested: false,
1654 safety: Safety::Safe,
1655 }),
1656 "function" | "fn" | "method" => Kind(DefKind::Fn),
1657 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1658 "field" => Kind(DefKind::Field),
1659 "variant" => Kind(DefKind::Variant),
1660 "type" => NS(Namespace::TypeNS),
1661 "value" => NS(Namespace::ValueNS),
1662 "macro" => NS(Namespace::MacroNS),
1663 "prim" | "primitive" => Primitive,
1664 _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1665 };
1666
1667 for (suffix, kind) in suffixes {
1668 if let Some(path_str) = rest.strip_suffix(suffix) {
1669 if d.ns() != Kind(kind).ns() {
1670 return Err((
1671 format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1672 0..idx,
1673 ));
1674 } else if path_str.len() > 1 {
1675 return Ok(Some((d, &path_str[1..], &rest[1..])));
1677 }
1678 }
1679 }
1680
1681 Ok(Some((d, &rest[1..], &rest[1..])))
1682 } else {
1683 for (suffix, kind) in suffixes {
1684 if let Some(path_str) = link.strip_suffix(suffix)
1686 && !path_str.is_empty()
1687 {
1688 return Ok(Some((Kind(kind), path_str, link)));
1689 }
1690 }
1691 Ok(None)
1692 }
1693 }
1694
1695 fn ns(self) -> Namespace {
1696 match self {
1697 Self::Namespace(n) => n,
1698 Self::Kind(DefKind::Field) => ValueNS,
1700 Self::Kind(k) => {
1701 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1702 }
1703 Self::Primitive => TypeNS,
1704 }
1705 }
1706
1707 fn article(self) -> &'static str {
1708 match self {
1709 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1710 Self::Kind(k) => k.article(),
1711 Self::Primitive => "a",
1712 }
1713 }
1714
1715 fn descr(self) -> &'static str {
1716 match self {
1717 Self::Namespace(n) => n.descr(),
1718 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1721 Self::Primitive => "builtin type",
1722 }
1723 }
1724}
1725
1726enum Suggestion {
1728 Prefix(&'static str),
1730 Function,
1732 Macro,
1734}
1735
1736impl Suggestion {
1737 fn descr(&self) -> Cow<'static, str> {
1738 match self {
1739 Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1740 Self::Function => "add parentheses".into(),
1741 Self::Macro => "add an exclamation mark".into(),
1742 }
1743 }
1744
1745 fn as_help(&self, path_str: &str) -> String {
1746 match self {
1748 Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1749 Self::Function => format!("{path_str}()"),
1750 Self::Macro => format!("{path_str}!"),
1751 }
1752 }
1753
1754 fn as_help_span(
1755 &self,
1756 ori_link: &str,
1757 sp: rustc_span::Span,
1758 ) -> Vec<(rustc_span::Span, String)> {
1759 let inner_sp = match ori_link.find('(') {
1760 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1761 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1762 }
1763 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1764 None => sp,
1765 };
1766 let inner_sp = match ori_link.find('!') {
1767 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1768 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1769 }
1770 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1771 None => inner_sp,
1772 };
1773 let inner_sp = match ori_link.find('@') {
1774 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1775 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1776 }
1777 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1778 None => inner_sp,
1779 };
1780 match self {
1781 Self::Prefix(prefix) => {
1782 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
1784 if sp.hi() != inner_sp.hi() {
1785 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1786 }
1787 sugg
1788 }
1789 Self::Function => {
1790 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1791 if sp.lo() != inner_sp.lo() {
1792 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1793 }
1794 sugg
1795 }
1796 Self::Macro => {
1797 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1798 if sp.lo() != inner_sp.lo() {
1799 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1800 }
1801 sugg
1802 }
1803 }
1804 }
1805}
1806
1807fn report_diagnostic(
1818 tcx: TyCtxt<'_>,
1819 lint: &'static Lint,
1820 msg: impl Into<DiagMessage> + Display,
1821 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1822 decorate: impl FnOnce(&mut Diag<'_, ()>, Option<rustc_span::Span>, MarkdownLinkRange),
1823) {
1824 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
1825 info!("ignoring warning from parent crate: {msg}");
1827 return;
1828 };
1829
1830 let sp = item.attr_span(tcx);
1831
1832 tcx.node_span_lint(lint, hir_id, sp, |lint| {
1833 lint.primary_message(msg);
1834
1835 let (span, link_range) = match link_range {
1836 MarkdownLinkRange::Destination(md_range) => {
1837 let mut md_range = md_range.clone();
1838 let sp =
1839 source_span_for_markdown_range(tcx, dox, &md_range, &item.attrs.doc_strings)
1840 .map(|(mut sp, _)| {
1841 while dox.as_bytes().get(md_range.start) == Some(&b' ')
1842 || dox.as_bytes().get(md_range.start) == Some(&b'`')
1843 {
1844 md_range.start += 1;
1845 sp = sp.with_lo(sp.lo() + BytePos(1));
1846 }
1847 while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
1848 || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
1849 {
1850 md_range.end -= 1;
1851 sp = sp.with_hi(sp.hi() - BytePos(1));
1852 }
1853 sp
1854 });
1855 (sp, MarkdownLinkRange::Destination(md_range))
1856 }
1857 MarkdownLinkRange::WholeLink(md_range) => (
1858 source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
1859 .map(|(sp, _)| sp),
1860 link_range.clone(),
1861 ),
1862 };
1863
1864 if let Some(sp) = span {
1865 lint.span(sp);
1866 } else {
1867 let md_range = link_range.inner_range().clone();
1872 let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
1873 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1874
1875 lint.note(format!(
1877 "the link appears in this line:\n\n{line}\n\
1878 {indicator: <before$}{indicator:^<found$}",
1879 indicator = "",
1880 before = md_range.start - last_new_line_offset,
1881 found = md_range.len(),
1882 ));
1883 }
1884
1885 decorate(lint, span, link_range);
1886 });
1887}
1888
1889fn resolution_failure(
1895 collector: &mut LinkCollector<'_, '_>,
1896 diag_info: DiagnosticInfo<'_>,
1897 path_str: &str,
1898 disambiguator: Option<Disambiguator>,
1899 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1900) {
1901 let tcx = collector.cx.tcx;
1902 report_diagnostic(
1903 tcx,
1904 BROKEN_INTRA_DOC_LINKS,
1905 format!("unresolved link to `{path_str}`"),
1906 &diag_info,
1907 |diag, sp, link_range| {
1908 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
1909 let assoc_item_not_allowed = |res: Res| {
1910 let name = res.name(tcx);
1911 format!(
1912 "`{name}` is {} {}, not a module or type, and cannot have associated items",
1913 res.article(),
1914 res.descr()
1915 )
1916 };
1917 let mut variants_seen = SmallVec::<[_; 3]>::new();
1919 for mut failure in kinds {
1920 let variant = mem::discriminant(&failure);
1921 if variants_seen.contains(&variant) {
1922 continue;
1923 }
1924 variants_seen.push(variant);
1925
1926 if let ResolutionFailure::NotResolved(UnresolvedPath {
1927 item_id,
1928 module_id,
1929 partial_res,
1930 unresolved,
1931 }) = &mut failure
1932 {
1933 use DefKind::*;
1934
1935 let item_id = *item_id;
1936 let module_id = *module_id;
1937
1938 let mut name = path_str;
1941 'outer: loop {
1942 let Some((start, end)) = name.rsplit_once("::") else {
1944 if partial_res.is_none() {
1946 *unresolved = name.into();
1947 }
1948 break;
1949 };
1950 name = start;
1951 for ns in [TypeNS, ValueNS, MacroNS] {
1952 if let Ok(v_res) =
1953 collector.resolve(start, ns, None, item_id, module_id)
1954 {
1955 debug!("found partial_res={v_res:?}");
1956 if let Some(&res) = v_res.first() {
1957 *partial_res = Some(full_res(tcx, res));
1958 *unresolved = end.into();
1959 break 'outer;
1960 }
1961 }
1962 }
1963 *unresolved = end.into();
1964 }
1965
1966 let last_found_module = match *partial_res {
1967 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1968 None => Some(module_id),
1969 _ => None,
1970 };
1971 if let Some(module) = last_found_module {
1973 let note = if partial_res.is_some() {
1974 let module_name = tcx.item_name(module);
1976 format!("no item named `{unresolved}` in module `{module_name}`")
1977 } else {
1978 format!("no item named `{unresolved}` in scope")
1980 };
1981 if let Some(span) = sp {
1982 diag.span_label(span, note);
1983 } else {
1984 diag.note(note);
1985 }
1986
1987 if !path_str.contains("::") {
1988 if disambiguator.is_none_or(|d| d.ns() == MacroNS)
1989 && collector
1990 .cx
1991 .tcx
1992 .resolutions(())
1993 .all_macro_rules
1994 .contains(&Symbol::intern(path_str))
1995 {
1996 diag.note(format!(
1997 "`macro_rules` named `{path_str}` exists in this crate, \
1998 but it is not in scope at this link's location"
1999 ));
2000 } else {
2001 diag.help(
2004 "to escape `[` and `]` characters, \
2005 add '\\' before them like `\\[` or `\\]`",
2006 );
2007 }
2008 }
2009
2010 continue;
2011 }
2012
2013 let res = partial_res.expect("None case was handled by `last_found_module`");
2015 let kind_did = match res {
2016 Res::Def(kind, did) => Some((kind, did)),
2017 Res::Primitive(_) => None,
2018 };
2019 let is_struct_variant = |did| {
2020 if let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind()
2021 && def.is_enum()
2022 && let Some(variant) =
2023 def.variants().iter().find(|v| v.name == res.name(tcx))
2024 {
2025 variant.ctor.is_none()
2027 } else {
2028 false
2029 }
2030 };
2031 let path_description = if let Some((kind, did)) = kind_did {
2032 match kind {
2033 Mod | ForeignMod => "inner item",
2034 Struct => "field or associated item",
2035 Enum | Union => "variant or associated item",
2036 Variant if is_struct_variant(did) => {
2037 let variant = res.name(tcx);
2038 let note = format!("variant `{variant}` has no such field");
2039 if let Some(span) = sp {
2040 diag.span_label(span, note);
2041 } else {
2042 diag.note(note);
2043 }
2044 return;
2045 }
2046 Variant
2047 | Field
2048 | Closure
2049 | AssocTy
2050 | AssocConst
2051 | AssocFn
2052 | Fn
2053 | Macro(_)
2054 | Const
2055 | ConstParam
2056 | ExternCrate
2057 | Use
2058 | LifetimeParam
2059 | Ctor(_, _)
2060 | AnonConst
2061 | InlineConst => {
2062 let note = assoc_item_not_allowed(res);
2063 if let Some(span) = sp {
2064 diag.span_label(span, note);
2065 } else {
2066 diag.note(note);
2067 }
2068 return;
2069 }
2070 Trait
2071 | TyAlias
2072 | ForeignTy
2073 | OpaqueTy
2074 | TraitAlias
2075 | TyParam
2076 | Static { .. } => "associated item",
2077 Impl { .. } | GlobalAsm | SyntheticCoroutineBody => {
2078 unreachable!("not a path")
2079 }
2080 }
2081 } else {
2082 "associated item"
2083 };
2084 let name = res.name(tcx);
2085 let note = format!(
2086 "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2087 res = res.descr(),
2088 disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2089 );
2090 if let Some(span) = sp {
2091 diag.span_label(span, note);
2092 } else {
2093 diag.note(note);
2094 }
2095
2096 continue;
2097 }
2098 let note = match failure {
2099 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2100 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2101 suggest_disambiguator(
2102 res,
2103 diag,
2104 path_str,
2105 link_range.clone(),
2106 sp,
2107 &diag_info,
2108 );
2109
2110 if let Some(disambiguator) = disambiguator
2111 && !matches!(disambiguator, Disambiguator::Namespace(..))
2112 {
2113 format!(
2114 "this link resolves to {}, which is not {} {}",
2115 item(res),
2116 disambiguator.article(),
2117 disambiguator.descr()
2118 )
2119 } else {
2120 format!(
2121 "this link resolves to {}, which is not in the {} namespace",
2122 item(res),
2123 expected_ns.descr()
2124 )
2125 }
2126 }
2127 };
2128 if let Some(span) = sp {
2129 diag.span_label(span, note);
2130 } else {
2131 diag.note(note);
2132 }
2133 }
2134 },
2135 );
2136}
2137
2138fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2139 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2140 anchor_failure(cx, diag_info, msg, 1)
2141}
2142
2143fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2144 let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2145 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2146 anchor_failure(cx, diag_info, msg, 0)
2147}
2148
2149fn anchor_failure(
2151 cx: &DocContext<'_>,
2152 diag_info: DiagnosticInfo<'_>,
2153 msg: String,
2154 anchor_idx: usize,
2155) {
2156 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2157 if let Some(mut sp) = sp {
2158 if let Some((fragment_offset, _)) =
2159 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2160 {
2161 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2162 }
2163 diag.span_label(sp, "invalid anchor");
2164 }
2165 });
2166}
2167
2168fn disambiguator_error(
2170 cx: &DocContext<'_>,
2171 mut diag_info: DiagnosticInfo<'_>,
2172 disambiguator_range: MarkdownLinkRange,
2173 msg: impl Into<DiagMessage> + Display,
2174) {
2175 diag_info.link_range = disambiguator_range;
2176 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2177 let msg = format!(
2178 "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2179 crate::DOC_RUST_LANG_ORG_VERSION
2180 );
2181 diag.note(msg);
2182 });
2183}
2184
2185fn report_malformed_generics(
2186 cx: &DocContext<'_>,
2187 diag_info: DiagnosticInfo<'_>,
2188 err: MalformedGenerics,
2189 path_str: &str,
2190) {
2191 report_diagnostic(
2192 cx.tcx,
2193 BROKEN_INTRA_DOC_LINKS,
2194 format!("unresolved link to `{path_str}`"),
2195 &diag_info,
2196 |diag, sp, _link_range| {
2197 let note = match err {
2198 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2199 MalformedGenerics::MissingType => "missing type for generic parameters",
2200 MalformedGenerics::HasFullyQualifiedSyntax => {
2201 diag.note(
2202 "see https://github.com/rust-lang/rust/issues/74563 for more information",
2203 );
2204 "fully-qualified syntax is unsupported"
2205 }
2206 MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
2207 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2208 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2209 };
2210 if let Some(span) = sp {
2211 diag.span_label(span, note);
2212 } else {
2213 diag.note(note);
2214 }
2215 },
2216 );
2217}
2218
2219fn ambiguity_error(
2225 cx: &DocContext<'_>,
2226 diag_info: &DiagnosticInfo<'_>,
2227 path_str: &str,
2228 candidates: &[(Res, Option<DefId>)],
2229 emit_error: bool,
2230) -> bool {
2231 let mut descrs = FxHashSet::default();
2232 let mut possible_proc_macro_id = None;
2235 let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro];
2236 let mut kinds = candidates
2237 .iter()
2238 .map(|(res, def_id)| {
2239 let r =
2240 if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2241 if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2242 possible_proc_macro_id = Some(id);
2243 }
2244 r
2245 })
2246 .collect::<Vec<_>>();
2247 if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2256 kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2257 }
2258
2259 kinds.retain(|res| descrs.insert(res.descr()));
2260
2261 if descrs.len() == 1 {
2262 return false;
2265 } else if !emit_error {
2266 return true;
2267 }
2268
2269 let mut msg = format!("`{path_str}` is ");
2270 match kinds.as_slice() {
2271 [res1, res2] => {
2272 msg += &format!(
2273 "both {} {} and {} {}",
2274 res1.article(),
2275 res1.descr(),
2276 res2.article(),
2277 res2.descr()
2278 );
2279 }
2280 _ => {
2281 let mut kinds = kinds.iter().peekable();
2282 while let Some(res) = kinds.next() {
2283 if kinds.peek().is_some() {
2284 msg += &format!("{} {}, ", res.article(), res.descr());
2285 } else {
2286 msg += &format!("and {} {}", res.article(), res.descr());
2287 }
2288 }
2289 }
2290 }
2291
2292 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2293 if let Some(sp) = sp {
2294 diag.span_label(sp, "ambiguous link");
2295 } else {
2296 diag.note("ambiguous link");
2297 }
2298
2299 for res in kinds {
2300 suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2301 }
2302 });
2303 true
2304}
2305
2306fn suggest_disambiguator(
2309 res: Res,
2310 diag: &mut Diag<'_, ()>,
2311 path_str: &str,
2312 link_range: MarkdownLinkRange,
2313 sp: Option<rustc_span::Span>,
2314 diag_info: &DiagnosticInfo<'_>,
2315) {
2316 let suggestion = res.disambiguator_suggestion();
2317 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2318
2319 let ori_link = match link_range {
2320 MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2321 MarkdownLinkRange::WholeLink(_) => None,
2322 };
2323
2324 if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2325 let mut spans = suggestion.as_help_span(ori_link, sp);
2326 if spans.len() > 1 {
2327 diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2328 } else {
2329 let (sp, suggestion_text) = spans.pop().unwrap();
2330 diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2331 }
2332 } else {
2333 diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2334 }
2335}
2336
2337fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2339 let sym;
2340 let item_name = match diag_info.item.name {
2341 Some(name) => {
2342 sym = name;
2343 sym.as_str()
2344 }
2345 None => "<unknown>",
2346 };
2347 let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2348
2349 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2350 if let Some(sp) = sp {
2351 diag.span_label(sp, "this item is private");
2352 }
2353
2354 let note_msg = if cx.render_options.document_private {
2355 "this link resolves only because you passed `--document-private-items`, but will break without"
2356 } else {
2357 "this link will resolve properly if you pass `--document-private-items`"
2358 };
2359 diag.note(note_msg);
2360 });
2361}
2362
2363fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2365 if ns != TypeNS {
2366 return None;
2367 }
2368 use PrimitiveType::*;
2369 let prim = match path_str {
2370 "isize" => Isize,
2371 "i8" => I8,
2372 "i16" => I16,
2373 "i32" => I32,
2374 "i64" => I64,
2375 "i128" => I128,
2376 "usize" => Usize,
2377 "u8" => U8,
2378 "u16" => U16,
2379 "u32" => U32,
2380 "u64" => U64,
2381 "u128" => U128,
2382 "f16" => F16,
2383 "f32" => F32,
2384 "f64" => F64,
2385 "f128" => F128,
2386 "char" => Char,
2387 "bool" | "true" | "false" => Bool,
2388 "str" | "&str" => Str,
2389 "slice" => Slice,
2391 "array" => Array,
2392 "tuple" => Tuple,
2393 "unit" => Unit,
2394 "pointer" | "*const" | "*mut" => RawPointer,
2395 "reference" | "&" | "&mut" => Reference,
2396 "fn" => Fn,
2397 "never" | "!" => Never,
2398 _ => return None,
2399 };
2400 debug!("resolved primitives {prim:?}");
2401 Some(Res::Primitive(prim))
2402}