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 into_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.into_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 {
1247 if let Some(prim) = resolve_primitive(path_str, TypeNS) {
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
1260 match res {
1261 Res::Primitive(_) => {
1262 if let Some(UrlFragment::Item(id)) = fragment {
1263 let kind = self.cx.tcx.def_kind(id);
1272 self.verify_disambiguator(path_str, kind, id, disambiguator, &diag_info)?;
1273 } else {
1274 match disambiguator {
1275 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1276 Some(other) => {
1277 self.report_disambiguator_mismatch(path_str, other, res, &diag_info);
1278 return None;
1279 }
1280 }
1281 }
1282
1283 res.def_id(self.cx.tcx).map(|page_id| ItemLink {
1284 link: Box::<str>::from(diag_info.ori_link),
1285 link_text: link_text.clone(),
1286 page_id,
1287 fragment,
1288 })
1289 }
1290 Res::Def(kind, id) => {
1291 let (kind_for_dis, id_for_dis) = if let Some(UrlFragment::Item(id)) = fragment {
1292 (self.cx.tcx.def_kind(id), id)
1293 } else {
1294 (kind, id)
1295 };
1296 self.verify_disambiguator(
1297 path_str,
1298 kind_for_dis,
1299 id_for_dis,
1300 disambiguator,
1301 &diag_info,
1302 )?;
1303
1304 let page_id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1305 Some(ItemLink {
1306 link: Box::<str>::from(diag_info.ori_link),
1307 link_text: link_text.clone(),
1308 page_id,
1309 fragment,
1310 })
1311 }
1312 }
1313 }
1314
1315 fn verify_disambiguator(
1316 &self,
1317 path_str: &str,
1318 kind: DefKind,
1319 id: DefId,
1320 disambiguator: Option<Disambiguator>,
1321 diag_info: &DiagnosticInfo<'_>,
1322 ) -> Option<()> {
1323 debug!("intra-doc link to {path_str} resolved to {:?}", (kind, id));
1324
1325 debug!("saw kind {kind:?} with disambiguator {disambiguator:?}");
1327 match (kind, disambiguator) {
1328 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1329 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1332 | (_, Some(Disambiguator::Namespace(_)))
1334 | (_, None)
1336 => {}
1338 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1339 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1340 self.report_disambiguator_mismatch(path_str, specified, Res::Def(kind, id), diag_info);
1341 return None;
1342 }
1343 }
1344
1345 if let Some(dst_id) = id.as_local()
1347 && let Some(src_id) = diag_info.item.item_id.expect_def_id().as_local()
1348 && self.cx.tcx.effective_visibilities(()).is_exported(src_id)
1349 && !self.cx.tcx.effective_visibilities(()).is_exported(dst_id)
1350 {
1351 privacy_error(self.cx, diag_info, path_str);
1352 }
1353
1354 Some(())
1355 }
1356
1357 fn report_disambiguator_mismatch(
1358 &self,
1359 path_str: &str,
1360 specified: Disambiguator,
1361 resolved: Res,
1362 diag_info: &DiagnosticInfo<'_>,
1363 ) {
1364 let msg = format!("incompatible link kind for `{path_str}`");
1366 let callback = |diag: &mut Diag<'_, ()>, sp: Option<rustc_span::Span>, link_range| {
1367 let note = format!(
1368 "this link resolved to {} {}, which is not {} {}",
1369 resolved.article(),
1370 resolved.descr(),
1371 specified.article(),
1372 specified.descr(),
1373 );
1374 if let Some(sp) = sp {
1375 diag.span_label(sp, note);
1376 } else {
1377 diag.note(note);
1378 }
1379 suggest_disambiguator(resolved, diag, path_str, link_range, sp, diag_info);
1380 };
1381 report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, callback);
1382 }
1383
1384 fn report_rawptr_assoc_feature_gate(
1385 &self,
1386 dox: &str,
1387 ori_link: &MarkdownLinkRange,
1388 item: &Item,
1389 ) {
1390 let span = match source_span_for_markdown_range(
1391 self.cx.tcx,
1392 dox,
1393 ori_link.inner_range(),
1394 &item.attrs.doc_strings,
1395 ) {
1396 Some((sp, _)) => sp,
1397 None => item.attr_span(self.cx.tcx),
1398 };
1399 rustc_session::parse::feature_err(
1400 self.cx.tcx.sess,
1401 sym::intra_doc_pointers,
1402 span,
1403 "linking to associated items of raw pointers is experimental",
1404 )
1405 .with_note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1406 .emit();
1407 }
1408
1409 fn resolve_with_disambiguator_cached(
1410 &mut self,
1411 key: ResolutionInfo,
1412 diag: DiagnosticInfo<'_>,
1413 cache_errors: bool,
1416 ) -> Option<Vec<(Res, Option<UrlFragment>)>> {
1417 if let Some(res) = self.visited_links.get(&key)
1418 && (res.is_some() || cache_errors)
1419 {
1420 return res.clone().map(|r| vec![r]);
1421 }
1422
1423 let mut candidates = self.resolve_with_disambiguator(&key, diag.clone());
1424
1425 if let Some(candidate) = candidates.first()
1428 && candidate.0 == Res::Primitive(PrimitiveType::RawPointer)
1429 && key.path_str.contains("::")
1430 {
1432 if key.item_id.is_local() && !self.cx.tcx.features().intra_doc_pointers() {
1433 self.report_rawptr_assoc_feature_gate(diag.dox, &diag.link_range, diag.item);
1434 return None;
1435 } else {
1436 candidates = vec![*candidate];
1437 }
1438 }
1439
1440 if let [candidate, _candidate2, ..] = *candidates
1445 && !ambiguity_error(self.cx, &diag, &key.path_str, &candidates, false)
1446 {
1447 candidates = vec![candidate];
1448 }
1449
1450 let mut out = Vec::with_capacity(candidates.len());
1451 for (res, def_id) in candidates {
1452 let fragment = match (&key.extra_fragment, def_id) {
1453 (Some(_), Some(def_id)) => {
1454 report_anchor_conflict(self.cx, diag, def_id);
1455 return None;
1456 }
1457 (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
1458 (None, Some(def_id)) => Some(UrlFragment::Item(def_id)),
1459 (None, None) => None,
1460 };
1461 out.push((res, fragment));
1462 }
1463 if let [r] = out.as_slice() {
1464 self.visited_links.insert(key, Some(r.clone()));
1465 } else if cache_errors {
1466 self.visited_links.insert(key, None);
1467 }
1468 Some(out)
1469 }
1470
1471 fn resolve_with_disambiguator(
1473 &mut self,
1474 key: &ResolutionInfo,
1475 diag: DiagnosticInfo<'_>,
1476 ) -> Vec<(Res, Option<DefId>)> {
1477 let disambiguator = key.dis;
1478 let path_str = &key.path_str;
1479 let item_id = key.item_id;
1480 let module_id = key.module_id;
1481
1482 match disambiguator.map(Disambiguator::ns) {
1483 Some(expected_ns) => {
1484 match self.resolve(path_str, expected_ns, disambiguator, item_id, module_id) {
1485 Ok(candidates) => candidates,
1486 Err(err) => {
1487 let mut err = ResolutionFailure::NotResolved(err);
1491 for other_ns in [TypeNS, ValueNS, MacroNS] {
1492 if other_ns != expected_ns
1493 && let Ok(&[res, ..]) = self
1494 .resolve(path_str, other_ns, None, item_id, module_id)
1495 .as_deref()
1496 {
1497 err = ResolutionFailure::WrongNamespace {
1498 res: full_res(self.cx.tcx, res),
1499 expected_ns,
1500 };
1501 break;
1502 }
1503 }
1504 resolution_failure(self, diag, path_str, disambiguator, smallvec![err]);
1505 vec![]
1506 }
1507 }
1508 }
1509 None => {
1510 let mut candidate = |ns| {
1512 self.resolve(path_str, ns, None, item_id, module_id)
1513 .map_err(ResolutionFailure::NotResolved)
1514 };
1515
1516 let candidates = PerNS {
1517 macro_ns: candidate(MacroNS),
1518 type_ns: candidate(TypeNS),
1519 value_ns: candidate(ValueNS).and_then(|v_res| {
1520 for (res, _) in v_res.iter() {
1521 if let Res::Def(DefKind::Ctor(..), _) = res {
1523 return Err(ResolutionFailure::WrongNamespace {
1524 res: *res,
1525 expected_ns: TypeNS,
1526 });
1527 }
1528 }
1529 Ok(v_res)
1530 }),
1531 };
1532
1533 let len = candidates
1534 .iter()
1535 .fold(0, |acc, res| if let Ok(res) = res { acc + res.len() } else { acc });
1536
1537 if len == 0 {
1538 resolution_failure(
1539 self,
1540 diag,
1541 path_str,
1542 disambiguator,
1543 candidates.into_iter().filter_map(|res| res.err()).collect(),
1544 );
1545 vec![]
1546 } else if len == 1 {
1547 candidates.into_iter().filter_map(|res| res.ok()).flatten().collect::<Vec<_>>()
1548 } else {
1549 let has_derive_trait_collision = is_derive_trait_collision(&candidates);
1550 if len == 2 && has_derive_trait_collision {
1551 candidates.type_ns.unwrap()
1552 } else {
1553 let mut candidates = candidates.map(|candidate| candidate.ok());
1555 if has_derive_trait_collision {
1557 candidates.macro_ns = None;
1558 }
1559 candidates.into_iter().flatten().flatten().collect::<Vec<_>>()
1560 }
1561 }
1562 }
1563 }
1564 }
1565}
1566
1567fn range_between_backticks(ori_link_range: &MarkdownLinkRange, dox: &str) -> MarkdownLinkRange {
1579 let range = match ori_link_range {
1580 mdlr @ MarkdownLinkRange::WholeLink(_) => return mdlr.clone(),
1581 MarkdownLinkRange::Destination(inner) => inner.clone(),
1582 };
1583 let ori_link_text = &dox[range.clone()];
1584 let after_first_backtick_group = ori_link_text.bytes().position(|b| b != b'`').unwrap_or(0);
1585 let before_second_backtick_group = ori_link_text
1586 .bytes()
1587 .skip(after_first_backtick_group)
1588 .position(|b| b == b'`')
1589 .unwrap_or(ori_link_text.len());
1590 MarkdownLinkRange::Destination(
1591 (range.start + after_first_backtick_group)..(range.start + before_second_backtick_group),
1592 )
1593}
1594
1595fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1602 link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1603}
1604
1605fn should_ignore_link(path_str: &str) -> bool {
1608 path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1609}
1610
1611#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1612enum Disambiguator {
1614 Primitive,
1618 Kind(DefKind),
1620 Namespace(Namespace),
1622}
1623
1624impl Disambiguator {
1625 fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1631 use Disambiguator::{Kind, Namespace as NS, Primitive};
1632
1633 let suffixes = [
1634 ("!()", DefKind::Macro(MacroKind::Bang)),
1636 ("!{}", DefKind::Macro(MacroKind::Bang)),
1637 ("![]", DefKind::Macro(MacroKind::Bang)),
1638 ("()", DefKind::Fn),
1639 ("!", DefKind::Macro(MacroKind::Bang)),
1640 ];
1641
1642 if let Some(idx) = link.find('@') {
1643 let (prefix, rest) = link.split_at(idx);
1644 let d = match prefix {
1645 "struct" => Kind(DefKind::Struct),
1647 "enum" => Kind(DefKind::Enum),
1648 "trait" => Kind(DefKind::Trait),
1649 "union" => Kind(DefKind::Union),
1650 "module" | "mod" => Kind(DefKind::Mod),
1651 "const" | "constant" => Kind(DefKind::Const),
1652 "static" => Kind(DefKind::Static {
1653 mutability: Mutability::Not,
1654 nested: false,
1655 safety: Safety::Safe,
1656 }),
1657 "function" | "fn" | "method" => Kind(DefKind::Fn),
1658 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1659 "field" => Kind(DefKind::Field),
1660 "variant" => Kind(DefKind::Variant),
1661 "type" => NS(Namespace::TypeNS),
1662 "value" => NS(Namespace::ValueNS),
1663 "macro" => NS(Namespace::MacroNS),
1664 "prim" | "primitive" => Primitive,
1665 _ => return Err((format!("unknown disambiguator `{prefix}`"), 0..idx)),
1666 };
1667
1668 for (suffix, kind) in suffixes {
1669 if let Some(path_str) = rest.strip_suffix(suffix) {
1670 if d.ns() != Kind(kind).ns() {
1671 return Err((
1672 format!("unmatched disambiguator `{prefix}` and suffix `{suffix}`"),
1673 0..idx,
1674 ));
1675 } else if path_str.len() > 1 {
1676 return Ok(Some((d, &path_str[1..], &rest[1..])));
1678 }
1679 }
1680 }
1681
1682 Ok(Some((d, &rest[1..], &rest[1..])))
1683 } else {
1684 for (suffix, kind) in suffixes {
1685 if let Some(path_str) = link.strip_suffix(suffix)
1687 && !path_str.is_empty()
1688 {
1689 return Ok(Some((Kind(kind), path_str, link)));
1690 }
1691 }
1692 Ok(None)
1693 }
1694 }
1695
1696 fn ns(self) -> Namespace {
1697 match self {
1698 Self::Namespace(n) => n,
1699 Self::Kind(DefKind::Field) => ValueNS,
1701 Self::Kind(k) => {
1702 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1703 }
1704 Self::Primitive => TypeNS,
1705 }
1706 }
1707
1708 fn article(self) -> &'static str {
1709 match self {
1710 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1711 Self::Kind(k) => k.article(),
1712 Self::Primitive => "a",
1713 }
1714 }
1715
1716 fn descr(self) -> &'static str {
1717 match self {
1718 Self::Namespace(n) => n.descr(),
1719 Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1722 Self::Primitive => "builtin type",
1723 }
1724 }
1725}
1726
1727enum Suggestion {
1729 Prefix(&'static str),
1731 Function,
1733 Macro,
1735}
1736
1737impl Suggestion {
1738 fn descr(&self) -> Cow<'static, str> {
1739 match self {
1740 Self::Prefix(x) => format!("prefix with `{x}@`").into(),
1741 Self::Function => "add parentheses".into(),
1742 Self::Macro => "add an exclamation mark".into(),
1743 }
1744 }
1745
1746 fn as_help(&self, path_str: &str) -> String {
1747 match self {
1749 Self::Prefix(prefix) => format!("{prefix}@{path_str}"),
1750 Self::Function => format!("{path_str}()"),
1751 Self::Macro => format!("{path_str}!"),
1752 }
1753 }
1754
1755 fn as_help_span(
1756 &self,
1757 ori_link: &str,
1758 sp: rustc_span::Span,
1759 ) -> Vec<(rustc_span::Span, String)> {
1760 let inner_sp = match ori_link.find('(') {
1761 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1762 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1763 }
1764 Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1765 None => sp,
1766 };
1767 let inner_sp = match ori_link.find('!') {
1768 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1769 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1770 }
1771 Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1772 None => inner_sp,
1773 };
1774 let inner_sp = match ori_link.find('@') {
1775 Some(index) if index != 0 && ori_link.as_bytes()[index - 1] == b'\\' => {
1776 sp.with_hi(sp.lo() + BytePos((index - 1) as _))
1777 }
1778 Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1779 None => inner_sp,
1780 };
1781 match self {
1782 Self::Prefix(prefix) => {
1783 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{prefix}@"))];
1785 if sp.hi() != inner_sp.hi() {
1786 sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1787 }
1788 sugg
1789 }
1790 Self::Function => {
1791 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1792 if sp.lo() != inner_sp.lo() {
1793 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1794 }
1795 sugg
1796 }
1797 Self::Macro => {
1798 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1799 if sp.lo() != inner_sp.lo() {
1800 sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1801 }
1802 sugg
1803 }
1804 }
1805 }
1806}
1807
1808fn report_diagnostic(
1819 tcx: TyCtxt<'_>,
1820 lint: &'static Lint,
1821 msg: impl Into<DiagMessage> + Display,
1822 DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1823 decorate: impl FnOnce(&mut Diag<'_, ()>, Option<rustc_span::Span>, MarkdownLinkRange),
1824) {
1825 let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else {
1826 info!("ignoring warning from parent crate: {msg}");
1828 return;
1829 };
1830
1831 let sp = item.attr_span(tcx);
1832
1833 tcx.node_span_lint(lint, hir_id, sp, |lint| {
1834 lint.primary_message(msg);
1835
1836 let (span, link_range) = match link_range {
1837 MarkdownLinkRange::Destination(md_range) => {
1838 let mut md_range = md_range.clone();
1839 let sp =
1840 source_span_for_markdown_range(tcx, dox, &md_range, &item.attrs.doc_strings)
1841 .map(|(mut sp, _)| {
1842 while dox.as_bytes().get(md_range.start) == Some(&b' ')
1843 || dox.as_bytes().get(md_range.start) == Some(&b'`')
1844 {
1845 md_range.start += 1;
1846 sp = sp.with_lo(sp.lo() + BytePos(1));
1847 }
1848 while dox.as_bytes().get(md_range.end - 1) == Some(&b' ')
1849 || dox.as_bytes().get(md_range.end - 1) == Some(&b'`')
1850 {
1851 md_range.end -= 1;
1852 sp = sp.with_hi(sp.hi() - BytePos(1));
1853 }
1854 sp
1855 });
1856 (sp, MarkdownLinkRange::Destination(md_range))
1857 }
1858 MarkdownLinkRange::WholeLink(md_range) => (
1859 source_span_for_markdown_range(tcx, dox, md_range, &item.attrs.doc_strings)
1860 .map(|(sp, _)| sp),
1861 link_range.clone(),
1862 ),
1863 };
1864
1865 if let Some(sp) = span {
1866 lint.span(sp);
1867 } else {
1868 let md_range = link_range.inner_range().clone();
1873 let last_new_line_offset = dox[..md_range.start].rfind('\n').map_or(0, |n| n + 1);
1874 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1875
1876 lint.note(format!(
1878 "the link appears in this line:\n\n{line}\n\
1879 {indicator: <before$}{indicator:^<found$}",
1880 indicator = "",
1881 before = md_range.start - last_new_line_offset,
1882 found = md_range.len(),
1883 ));
1884 }
1885
1886 decorate(lint, span, link_range);
1887 });
1888}
1889
1890fn resolution_failure(
1896 collector: &mut LinkCollector<'_, '_>,
1897 diag_info: DiagnosticInfo<'_>,
1898 path_str: &str,
1899 disambiguator: Option<Disambiguator>,
1900 kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1901) {
1902 let tcx = collector.cx.tcx;
1903 report_diagnostic(
1904 tcx,
1905 BROKEN_INTRA_DOC_LINKS,
1906 format!("unresolved link to `{path_str}`"),
1907 &diag_info,
1908 |diag, sp, link_range| {
1909 let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx));
1910 let assoc_item_not_allowed = |res: Res| {
1911 let name = res.name(tcx);
1912 format!(
1913 "`{name}` is {} {}, not a module or type, and cannot have associated items",
1914 res.article(),
1915 res.descr()
1916 )
1917 };
1918 let mut variants_seen = SmallVec::<[_; 3]>::new();
1920 for mut failure in kinds {
1921 let variant = mem::discriminant(&failure);
1922 if variants_seen.contains(&variant) {
1923 continue;
1924 }
1925 variants_seen.push(variant);
1926
1927 if let ResolutionFailure::NotResolved(UnresolvedPath {
1928 item_id,
1929 module_id,
1930 partial_res,
1931 unresolved,
1932 }) = &mut failure
1933 {
1934 use DefKind::*;
1935
1936 let item_id = *item_id;
1937 let module_id = *module_id;
1938
1939 let mut name = path_str;
1942 'outer: loop {
1943 let Some((start, end)) = name.rsplit_once("::") else {
1945 if partial_res.is_none() {
1947 *unresolved = name.into();
1948 }
1949 break;
1950 };
1951 name = start;
1952 for ns in [TypeNS, ValueNS, MacroNS] {
1953 if let Ok(v_res) =
1954 collector.resolve(start, ns, None, item_id, module_id)
1955 {
1956 debug!("found partial_res={v_res:?}");
1957 if let Some(&res) = v_res.first() {
1958 *partial_res = Some(full_res(tcx, res));
1959 *unresolved = end.into();
1960 break 'outer;
1961 }
1962 }
1963 }
1964 *unresolved = end.into();
1965 }
1966
1967 let last_found_module = match *partial_res {
1968 Some(Res::Def(DefKind::Mod, id)) => Some(id),
1969 None => Some(module_id),
1970 _ => None,
1971 };
1972 if let Some(module) = last_found_module {
1974 let note = if partial_res.is_some() {
1975 let module_name = tcx.item_name(module);
1977 format!("no item named `{unresolved}` in module `{module_name}`")
1978 } else {
1979 format!("no item named `{unresolved}` in scope")
1981 };
1982 if let Some(span) = sp {
1983 diag.span_label(span, note);
1984 } else {
1985 diag.note(note);
1986 }
1987
1988 if !path_str.contains("::") {
1989 if disambiguator.is_none_or(|d| d.ns() == MacroNS)
1990 && collector
1991 .cx
1992 .tcx
1993 .resolutions(())
1994 .all_macro_rules
1995 .contains(&Symbol::intern(path_str))
1996 {
1997 diag.note(format!(
1998 "`macro_rules` named `{path_str}` exists in this crate, \
1999 but it is not in scope at this link's location"
2000 ));
2001 } else {
2002 diag.help(
2005 "to escape `[` and `]` characters, \
2006 add '\\' before them like `\\[` or `\\]`",
2007 );
2008 }
2009 }
2010
2011 continue;
2012 }
2013
2014 let res = partial_res.expect("None case was handled by `last_found_module`");
2016 let kind_did = match res {
2017 Res::Def(kind, did) => Some((kind, did)),
2018 Res::Primitive(_) => None,
2019 };
2020 let is_struct_variant = |did| {
2021 if let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind()
2022 && def.is_enum()
2023 && let Some(variant) =
2024 def.variants().iter().find(|v| v.name == res.name(tcx))
2025 {
2026 variant.ctor.is_none()
2028 } else {
2029 false
2030 }
2031 };
2032 let path_description = if let Some((kind, did)) = kind_did {
2033 match kind {
2034 Mod | ForeignMod => "inner item",
2035 Struct => "field or associated item",
2036 Enum | Union => "variant or associated item",
2037 Variant if is_struct_variant(did) => {
2038 let variant = res.name(tcx);
2039 let note = format!("variant `{variant}` has no such field");
2040 if let Some(span) = sp {
2041 diag.span_label(span, note);
2042 } else {
2043 diag.note(note);
2044 }
2045 return;
2046 }
2047 Variant
2048 | Field
2049 | Closure
2050 | AssocTy
2051 | AssocConst
2052 | AssocFn
2053 | Fn
2054 | Macro(_)
2055 | Const
2056 | ConstParam
2057 | ExternCrate
2058 | Use
2059 | LifetimeParam
2060 | Ctor(_, _)
2061 | AnonConst
2062 | InlineConst => {
2063 let note = assoc_item_not_allowed(res);
2064 if let Some(span) = sp {
2065 diag.span_label(span, note);
2066 } else {
2067 diag.note(note);
2068 }
2069 return;
2070 }
2071 Trait
2072 | TyAlias
2073 | ForeignTy
2074 | OpaqueTy
2075 | TraitAlias
2076 | TyParam
2077 | Static { .. } => "associated item",
2078 Impl { .. } | GlobalAsm | SyntheticCoroutineBody => {
2079 unreachable!("not a path")
2080 }
2081 }
2082 } else {
2083 "associated item"
2084 };
2085 let name = res.name(tcx);
2086 let note = format!(
2087 "the {res} `{name}` has no {disamb_res} named `{unresolved}`",
2088 res = res.descr(),
2089 disamb_res = disambiguator.map_or(path_description, |d| d.descr()),
2090 );
2091 if let Some(span) = sp {
2092 diag.span_label(span, note);
2093 } else {
2094 diag.note(note);
2095 }
2096
2097 continue;
2098 }
2099 let note = match failure {
2100 ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2101 ResolutionFailure::WrongNamespace { res, expected_ns } => {
2102 suggest_disambiguator(
2103 res,
2104 diag,
2105 path_str,
2106 link_range.clone(),
2107 sp,
2108 &diag_info,
2109 );
2110
2111 if let Some(disambiguator) = disambiguator
2112 && !matches!(disambiguator, Disambiguator::Namespace(..))
2113 {
2114 format!(
2115 "this link resolves to {}, which is not {} {}",
2116 item(res),
2117 disambiguator.article(),
2118 disambiguator.descr()
2119 )
2120 } else {
2121 format!(
2122 "this link resolves to {}, which is not in the {} namespace",
2123 item(res),
2124 expected_ns.descr()
2125 )
2126 }
2127 }
2128 };
2129 if let Some(span) = sp {
2130 diag.span_label(span, note);
2131 } else {
2132 diag.note(note);
2133 }
2134 }
2135 },
2136 );
2137}
2138
2139fn report_multiple_anchors(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>) {
2140 let msg = format!("`{}` contains multiple anchors", diag_info.ori_link);
2141 anchor_failure(cx, diag_info, msg, 1)
2142}
2143
2144fn report_anchor_conflict(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, def_id: DefId) {
2145 let (link, kind) = (diag_info.ori_link, Res::from_def_id(cx.tcx, def_id).descr());
2146 let msg = format!("`{link}` contains an anchor, but links to {kind}s are already anchored");
2147 anchor_failure(cx, diag_info, msg, 0)
2148}
2149
2150fn anchor_failure(
2152 cx: &DocContext<'_>,
2153 diag_info: DiagnosticInfo<'_>,
2154 msg: String,
2155 anchor_idx: usize,
2156) {
2157 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, sp, _link_range| {
2158 if let Some(mut sp) = sp {
2159 if let Some((fragment_offset, _)) =
2160 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2161 {
2162 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2163 }
2164 diag.span_label(sp, "invalid anchor");
2165 }
2166 });
2167}
2168
2169fn disambiguator_error(
2171 cx: &DocContext<'_>,
2172 mut diag_info: DiagnosticInfo<'_>,
2173 disambiguator_range: MarkdownLinkRange,
2174 msg: impl Into<DiagMessage> + Display,
2175) {
2176 diag_info.link_range = disambiguator_range;
2177 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| {
2178 let msg = format!(
2179 "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2180 crate::DOC_RUST_LANG_ORG_VERSION
2181 );
2182 diag.note(msg);
2183 });
2184}
2185
2186fn report_malformed_generics(
2187 cx: &DocContext<'_>,
2188 diag_info: DiagnosticInfo<'_>,
2189 err: MalformedGenerics,
2190 path_str: &str,
2191) {
2192 report_diagnostic(
2193 cx.tcx,
2194 BROKEN_INTRA_DOC_LINKS,
2195 format!("unresolved link to `{path_str}`"),
2196 &diag_info,
2197 |diag, sp, _link_range| {
2198 let note = match err {
2199 MalformedGenerics::UnbalancedAngleBrackets => "unbalanced angle brackets",
2200 MalformedGenerics::MissingType => "missing type for generic parameters",
2201 MalformedGenerics::HasFullyQualifiedSyntax => {
2202 diag.note(
2203 "see https://github.com/rust-lang/rust/issues/74563 for more information",
2204 );
2205 "fully-qualified syntax is unsupported"
2206 }
2207 MalformedGenerics::InvalidPathSeparator => "has invalid path separator",
2208 MalformedGenerics::TooManyAngleBrackets => "too many angle brackets",
2209 MalformedGenerics::EmptyAngleBrackets => "empty angle brackets",
2210 };
2211 if let Some(span) = sp {
2212 diag.span_label(span, note);
2213 } else {
2214 diag.note(note);
2215 }
2216 },
2217 );
2218}
2219
2220fn ambiguity_error(
2226 cx: &DocContext<'_>,
2227 diag_info: &DiagnosticInfo<'_>,
2228 path_str: &str,
2229 candidates: &[(Res, Option<DefId>)],
2230 emit_error: bool,
2231) -> bool {
2232 let mut descrs = FxHashSet::default();
2233 let mut possible_proc_macro_id = None;
2236 let is_proc_macro_crate = cx.tcx.crate_types() == &[CrateType::ProcMacro];
2237 let mut kinds = candidates
2238 .iter()
2239 .map(|(res, def_id)| {
2240 let r =
2241 if let Some(def_id) = def_id { Res::from_def_id(cx.tcx, *def_id) } else { *res };
2242 if is_proc_macro_crate && let Res::Def(DefKind::Macro(_), id) = r {
2243 possible_proc_macro_id = Some(id);
2244 }
2245 r
2246 })
2247 .collect::<Vec<_>>();
2248 if is_proc_macro_crate && let Some(macro_id) = possible_proc_macro_id {
2257 kinds.retain(|res| !matches!(res, Res::Def(DefKind::Fn, fn_id) if macro_id == *fn_id));
2258 }
2259
2260 kinds.retain(|res| descrs.insert(res.descr()));
2261
2262 if descrs.len() == 1 {
2263 return false;
2266 } else if !emit_error {
2267 return true;
2268 }
2269
2270 let mut msg = format!("`{path_str}` is ");
2271 match kinds.as_slice() {
2272 [res1, res2] => {
2273 msg += &format!(
2274 "both {} {} and {} {}",
2275 res1.article(),
2276 res1.descr(),
2277 res2.article(),
2278 res2.descr()
2279 );
2280 }
2281 _ => {
2282 let mut kinds = kinds.iter().peekable();
2283 while let Some(res) = kinds.next() {
2284 if kinds.peek().is_some() {
2285 msg += &format!("{} {}, ", res.article(), res.descr());
2286 } else {
2287 msg += &format!("and {} {}", res.article(), res.descr());
2288 }
2289 }
2290 }
2291 }
2292
2293 report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, link_range| {
2294 if let Some(sp) = sp {
2295 diag.span_label(sp, "ambiguous link");
2296 } else {
2297 diag.note("ambiguous link");
2298 }
2299
2300 for res in kinds {
2301 suggest_disambiguator(res, diag, path_str, link_range.clone(), sp, diag_info);
2302 }
2303 });
2304 true
2305}
2306
2307fn suggest_disambiguator(
2310 res: Res,
2311 diag: &mut Diag<'_, ()>,
2312 path_str: &str,
2313 link_range: MarkdownLinkRange,
2314 sp: Option<rustc_span::Span>,
2315 diag_info: &DiagnosticInfo<'_>,
2316) {
2317 let suggestion = res.disambiguator_suggestion();
2318 let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2319
2320 let ori_link = match link_range {
2321 MarkdownLinkRange::Destination(range) => Some(&diag_info.dox[range]),
2322 MarkdownLinkRange::WholeLink(_) => None,
2323 };
2324
2325 if let (Some(sp), Some(ori_link)) = (sp, ori_link) {
2326 let mut spans = suggestion.as_help_span(ori_link, sp);
2327 if spans.len() > 1 {
2328 diag.multipart_suggestion(help, spans, Applicability::MaybeIncorrect);
2329 } else {
2330 let (sp, suggestion_text) = spans.pop().unwrap();
2331 diag.span_suggestion_verbose(sp, help, suggestion_text, Applicability::MaybeIncorrect);
2332 }
2333 } else {
2334 diag.help(format!("{help}: {}", suggestion.as_help(path_str)));
2335 }
2336}
2337
2338fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2340 let sym;
2341 let item_name = match diag_info.item.name {
2342 Some(name) => {
2343 sym = name;
2344 sym.as_str()
2345 }
2346 None => "<unknown>",
2347 };
2348 let msg = format!("public documentation for `{item_name}` links to private item `{path_str}`");
2349
2350 report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, msg, diag_info, |diag, sp, _link_range| {
2351 if let Some(sp) = sp {
2352 diag.span_label(sp, "this item is private");
2353 }
2354
2355 let note_msg = if cx.render_options.document_private {
2356 "this link resolves only because you passed `--document-private-items`, but will break without"
2357 } else {
2358 "this link will resolve properly if you pass `--document-private-items`"
2359 };
2360 diag.note(note_msg);
2361 });
2362}
2363
2364fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2366 if ns != TypeNS {
2367 return None;
2368 }
2369 use PrimitiveType::*;
2370 let prim = match path_str {
2371 "isize" => Isize,
2372 "i8" => I8,
2373 "i16" => I16,
2374 "i32" => I32,
2375 "i64" => I64,
2376 "i128" => I128,
2377 "usize" => Usize,
2378 "u8" => U8,
2379 "u16" => U16,
2380 "u32" => U32,
2381 "u64" => U64,
2382 "u128" => U128,
2383 "f16" => F16,
2384 "f32" => F32,
2385 "f64" => F64,
2386 "f128" => F128,
2387 "char" => Char,
2388 "bool" | "true" | "false" => Bool,
2389 "str" | "&str" => Str,
2390 "slice" => Slice,
2392 "array" => Array,
2393 "tuple" => Tuple,
2394 "unit" => Unit,
2395 "pointer" | "*const" | "*mut" => RawPointer,
2396 "reference" | "&" | "&mut" => Reference,
2397 "fn" => Fn,
2398 "never" | "!" => Never,
2399 _ => return None,
2400 };
2401 debug!("resolved primitives {prim:?}");
2402 Some(Res::Primitive(prim))
2403}