]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_intra_doc_links.rs
Rollup merge of #94985 - dtolnay:constattr, r=pnkfelix
[rust.git] / src / librustdoc / passes / collect_intra_doc_links.rs
1 //! This module implements [RFC 1946]: Intra-rustdoc-links
2 //!
3 //! [RFC 1946]: https://github.com/rust-lang/rfcs/blob/master/text/1946-intra-rustdoc-links.md
4
5 use pulldown_cmark::LinkType;
6 use rustc_data_structures::{fx::FxHashMap, intern::Interned, stable_set::FxHashSet};
7 use rustc_errors::{Applicability, Diagnostic};
8 use rustc_hir::def::Namespace::*;
9 use rustc_hir::def::{DefKind, Namespace, PerNS};
10 use rustc_hir::def_id::{DefId, CRATE_DEF_ID};
11 use rustc_hir::Mutability;
12 use rustc_middle::ty::{DefIdTree, Ty, TyCtxt};
13 use rustc_middle::{bug, span_bug, ty};
14 use rustc_session::lint::Lint;
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::symbol::{sym, Ident, Symbol};
17 use rustc_span::{BytePos, DUMMY_SP};
18 use smallvec::{smallvec, SmallVec};
19
20 use std::borrow::Cow;
21 use std::fmt::Write;
22 use std::mem;
23 use std::ops::Range;
24
25 use crate::clean::{self, utils::find_nearest_parent_module};
26 use crate::clean::{Crate, Item, ItemId, ItemLink, PrimitiveType};
27 use crate::core::DocContext;
28 use crate::html::markdown::{markdown_links, MarkdownLink};
29 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
30 use crate::passes::Pass;
31 use crate::visit::DocVisitor;
32
33 mod early;
34 crate use early::early_resolve_intra_doc_links;
35
36 crate const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
37     name: "collect-intra-doc-links",
38     run: collect_intra_doc_links,
39     description: "resolves intra-doc links",
40 };
41
42 fn collect_intra_doc_links(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
43     let mut collector =
44         LinkCollector { cx, mod_ids: Vec::new(), visited_links: FxHashMap::default() };
45     collector.visit_crate(&krate);
46     krate
47 }
48
49 /// Top-level errors emitted by this pass.
50 enum ErrorKind<'a> {
51     Resolve(Box<ResolutionFailure<'a>>),
52     AnchorFailure(AnchorFailure),
53 }
54
55 impl<'a> From<ResolutionFailure<'a>> for ErrorKind<'a> {
56     fn from(err: ResolutionFailure<'a>) -> Self {
57         ErrorKind::Resolve(box err)
58     }
59 }
60
61 #[derive(Copy, Clone, Debug, Hash)]
62 enum Res {
63     Def(DefKind, DefId),
64     Primitive(PrimitiveType),
65 }
66
67 type ResolveRes = rustc_hir::def::Res<rustc_ast::NodeId>;
68
69 impl Res {
70     fn descr(self) -> &'static str {
71         match self {
72             Res::Def(kind, id) => ResolveRes::Def(kind, id).descr(),
73             Res::Primitive(_) => "builtin type",
74         }
75     }
76
77     fn article(self) -> &'static str {
78         match self {
79             Res::Def(kind, id) => ResolveRes::Def(kind, id).article(),
80             Res::Primitive(_) => "a",
81         }
82     }
83
84     fn name(self, tcx: TyCtxt<'_>) -> Symbol {
85         match self {
86             Res::Def(_, id) => tcx.item_name(id),
87             Res::Primitive(prim) => prim.as_sym(),
88         }
89     }
90
91     fn def_id(self, tcx: TyCtxt<'_>) -> DefId {
92         match self {
93             Res::Def(_, id) => id,
94             Res::Primitive(prim) => *PrimitiveType::primitive_locations(tcx).get(&prim).unwrap(),
95         }
96     }
97
98     fn as_hir_res(self) -> Option<rustc_hir::def::Res> {
99         match self {
100             Res::Def(kind, id) => Some(rustc_hir::def::Res::Def(kind, id)),
101             // FIXME: maybe this should handle the subset of PrimitiveType that fits into hir::PrimTy?
102             Res::Primitive(_) => None,
103         }
104     }
105
106     /// Used for error reporting.
107     fn disambiguator_suggestion(self) -> Suggestion {
108         let kind = match self {
109             Res::Primitive(_) => return Suggestion::Prefix("prim"),
110             Res::Def(kind, _) => kind,
111         };
112         if kind == DefKind::Macro(MacroKind::Bang) {
113             return Suggestion::Macro;
114         } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
115             return Suggestion::Function;
116         } else if kind == DefKind::Field {
117             return Suggestion::RemoveDisambiguator;
118         }
119
120         let prefix = match kind {
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::Macro(MacroKind::Derive) => "derive",
131             // Now handle things that don't have a specific disambiguator
132             _ => match kind
133                 .ns()
134                 .expect("tried to calculate a disambiguator for a def without a namespace?")
135             {
136                 Namespace::TypeNS => "type",
137                 Namespace::ValueNS => "value",
138                 Namespace::MacroNS => "macro",
139             },
140         };
141
142         Suggestion::Prefix(prefix)
143     }
144 }
145
146 impl TryFrom<ResolveRes> for Res {
147     type Error = ();
148
149     fn try_from(res: ResolveRes) -> Result<Self, ()> {
150         use rustc_hir::def::Res::*;
151         match res {
152             Def(kind, id) => Ok(Res::Def(kind, id)),
153             PrimTy(prim) => Ok(Res::Primitive(PrimitiveType::from_hir(prim))),
154             // e.g. `#[derive]`
155             NonMacroAttr(..) | Err => Result::Err(()),
156             other => bug!("unrecognized res {:?}", other),
157         }
158     }
159 }
160
161 /// A link failed to resolve.
162 #[derive(Debug)]
163 enum ResolutionFailure<'a> {
164     /// This resolved, but with the wrong namespace.
165     WrongNamespace {
166         /// What the link resolved to.
167         res: Res,
168         /// The expected namespace for the resolution, determined from the link's disambiguator.
169         ///
170         /// E.g., for `[fn@Result]` this is [`Namespace::ValueNS`],
171         /// even though `Result`'s actual namespace is [`Namespace::TypeNS`].
172         expected_ns: Namespace,
173     },
174     /// The link failed to resolve. [`resolution_failure`] should look to see if there's
175     /// a more helpful error that can be given.
176     NotResolved {
177         /// Item on which the link is resolved, used for resolving `Self`.
178         item_id: ItemId,
179         /// The scope the link was resolved in.
180         module_id: DefId,
181         /// If part of the link resolved, this has the `Res`.
182         ///
183         /// In `[std::io::Error::x]`, `std::io::Error` would be a partial resolution.
184         partial_res: Option<Res>,
185         /// The remaining unresolved path segments.
186         ///
187         /// In `[std::io::Error::x]`, `x` would be unresolved.
188         unresolved: Cow<'a, str>,
189     },
190     /// This happens when rustdoc can't determine the parent scope for an item.
191     /// It is always a bug in rustdoc.
192     NoParentItem,
193     /// This link has malformed generic parameters; e.g., the angle brackets are unbalanced.
194     MalformedGenerics(MalformedGenerics),
195     /// Used to communicate that this should be ignored, but shouldn't be reported to the user.
196     ///
197     /// This happens when there is no disambiguator and one of the namespaces
198     /// failed to resolve.
199     Dummy,
200 }
201
202 #[derive(Debug)]
203 enum MalformedGenerics {
204     /// This link has unbalanced angle brackets.
205     ///
206     /// For example, `Vec<T` should trigger this, as should `Vec<T>>`.
207     UnbalancedAngleBrackets,
208     /// The generics are not attached to a type.
209     ///
210     /// For example, `<T>` should trigger this.
211     ///
212     /// This is detected by checking if the path is empty after the generics are stripped.
213     MissingType,
214     /// The link uses fully-qualified syntax, which is currently unsupported.
215     ///
216     /// For example, `<Vec as IntoIterator>::into_iter` should trigger this.
217     ///
218     /// This is detected by checking if ` as ` (the keyword `as` with spaces around it) is inside
219     /// angle brackets.
220     HasFullyQualifiedSyntax,
221     /// The link has an invalid path separator.
222     ///
223     /// For example, `Vec:<T>:new()` should trigger this. Note that `Vec:new()` will **not**
224     /// trigger this because it has no generics and thus [`strip_generics_from_path`] will not be
225     /// called.
226     ///
227     /// Note that this will also **not** be triggered if the invalid path separator is inside angle
228     /// brackets because rustdoc mostly ignores what's inside angle brackets (except for
229     /// [`HasFullyQualifiedSyntax`](MalformedGenerics::HasFullyQualifiedSyntax)).
230     ///
231     /// This is detected by checking if there is a colon followed by a non-colon in the link.
232     InvalidPathSeparator,
233     /// The link has too many angle brackets.
234     ///
235     /// For example, `Vec<<T>>` should trigger this.
236     TooManyAngleBrackets,
237     /// The link has empty angle brackets.
238     ///
239     /// For example, `Vec<>` should trigger this.
240     EmptyAngleBrackets,
241 }
242
243 impl ResolutionFailure<'_> {
244     /// This resolved fully (not just partially) but is erroneous for some other reason
245     ///
246     /// Returns the full resolution of the link, if present.
247     fn full_res(&self) -> Option<Res> {
248         match self {
249             Self::WrongNamespace { res, expected_ns: _ } => Some(*res),
250             _ => None,
251         }
252     }
253 }
254
255 enum AnchorFailure {
256     /// User error: `[std#x#y]` is not valid
257     MultipleAnchors,
258     /// The anchor provided by the user conflicts with Rustdoc's generated anchor.
259     ///
260     /// This is an unfortunate state of affairs. Not every item that can be
261     /// linked to has its own page; sometimes it is a subheading within a page,
262     /// like for associated items. In those cases, rustdoc uses an anchor to
263     /// link to the subheading. Since you can't have two anchors for the same
264     /// link, Rustdoc disallows having a user-specified anchor.
265     ///
266     /// Most of the time this is fine, because you can just link to the page of
267     /// the item if you want to provide your own anchor.
268     RustdocAnchorConflict(Res),
269 }
270
271 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
272 crate enum UrlFragment {
273     Item(ItemFragment),
274     UserWritten(String),
275 }
276
277 impl UrlFragment {
278     /// Render the fragment, including the leading `#`.
279     crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
280         match self {
281             UrlFragment::Item(frag) => frag.render(s, tcx),
282             UrlFragment::UserWritten(raw) => write!(s, "#{}", raw),
283         }
284     }
285 }
286
287 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
288 crate struct ItemFragment(FragmentKind, DefId);
289
290 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
291 crate enum FragmentKind {
292     Method,
293     TyMethod,
294     AssociatedConstant,
295     AssociatedType,
296
297     StructField,
298     Variant,
299     VariantField,
300 }
301
302 impl ItemFragment {
303     /// Create a fragment for an associated item.
304     #[instrument(level = "debug")]
305     fn from_assoc_item(item: &ty::AssocItem) -> Self {
306         let def_id = item.def_id;
307         match item.kind {
308             ty::AssocKind::Fn => {
309                 if item.defaultness.has_value() {
310                     ItemFragment(FragmentKind::Method, def_id)
311                 } else {
312                     ItemFragment(FragmentKind::TyMethod, def_id)
313                 }
314             }
315             ty::AssocKind::Const => ItemFragment(FragmentKind::AssociatedConstant, def_id),
316             ty::AssocKind::Type => ItemFragment(FragmentKind::AssociatedType, def_id),
317         }
318     }
319
320     /// Render the fragment, including the leading `#`.
321     crate fn render(&self, s: &mut String, tcx: TyCtxt<'_>) -> std::fmt::Result {
322         write!(s, "#")?;
323         match *self {
324             ItemFragment(kind, def_id) => {
325                 let name = tcx.item_name(def_id);
326                 match kind {
327                     FragmentKind::Method => write!(s, "method.{}", name),
328                     FragmentKind::TyMethod => write!(s, "tymethod.{}", name),
329                     FragmentKind::AssociatedConstant => write!(s, "associatedconstant.{}", name),
330                     FragmentKind::AssociatedType => write!(s, "associatedtype.{}", name),
331                     FragmentKind::StructField => write!(s, "structfield.{}", name),
332                     FragmentKind::Variant => write!(s, "variant.{}", name),
333                     FragmentKind::VariantField => {
334                         let variant = tcx.item_name(tcx.parent(def_id).unwrap());
335                         write!(s, "variant.{}.field.{}", variant, name)
336                     }
337                 }
338             }
339         }
340     }
341 }
342
343 #[derive(Clone, Debug, Hash, PartialEq, Eq)]
344 struct ResolutionInfo {
345     item_id: ItemId,
346     module_id: DefId,
347     dis: Option<Disambiguator>,
348     path_str: String,
349     extra_fragment: Option<String>,
350 }
351
352 #[derive(Clone)]
353 struct DiagnosticInfo<'a> {
354     item: &'a Item,
355     dox: &'a str,
356     ori_link: &'a str,
357     link_range: Range<usize>,
358 }
359
360 #[derive(Clone, Debug, Hash)]
361 struct CachedLink {
362     res: (Res, Option<UrlFragment>),
363 }
364
365 struct LinkCollector<'a, 'tcx> {
366     cx: &'a mut DocContext<'tcx>,
367     /// A stack of modules used to decide what scope to resolve in.
368     ///
369     /// The last module will be used if the parent scope of the current item is
370     /// unknown.
371     mod_ids: Vec<DefId>,
372     /// Cache the resolved links so we can avoid resolving (and emitting errors for) the same link.
373     /// The link will be `None` if it could not be resolved (i.e. the error was cached).
374     visited_links: FxHashMap<ResolutionInfo, Option<CachedLink>>,
375 }
376
377 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
378     /// Given a full link, parse it as an [enum struct variant].
379     ///
380     /// In particular, this will return an error whenever there aren't three
381     /// full path segments left in the link.
382     ///
383     /// [enum struct variant]: rustc_hir::VariantData::Struct
384     fn variant_field<'path>(
385         &self,
386         path_str: &'path str,
387         item_id: ItemId,
388         module_id: DefId,
389     ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
390         let tcx = self.cx.tcx;
391         let no_res = || ResolutionFailure::NotResolved {
392             item_id,
393             module_id,
394             partial_res: None,
395             unresolved: path_str.into(),
396         };
397
398         debug!("looking for enum variant {}", path_str);
399         let mut split = path_str.rsplitn(3, "::");
400         let variant_field_name = split
401             .next()
402             .map(|f| Symbol::intern(f))
403             .expect("fold_item should ensure link is non-empty");
404         let variant_name =
405             // we're not sure this is a variant at all, so use the full string
406             // If there's no second component, the link looks like `[path]`.
407             // So there's no partial res and we should say the whole link failed to resolve.
408             split.next().map(|f|  Symbol::intern(f)).ok_or_else(no_res)?;
409         let path = split
410             .next()
411             .map(|f| f.to_owned())
412             // If there's no third component, we saw `[a::b]` before and it failed to resolve.
413             // So there's no partial res.
414             .ok_or_else(no_res)?;
415         let ty_res = self.resolve_path(&path, TypeNS, item_id, module_id).ok_or_else(no_res)?;
416
417         match ty_res {
418             Res::Def(DefKind::Enum, did) => {
419                 if tcx
420                     .inherent_impls(did)
421                     .iter()
422                     .flat_map(|imp| tcx.associated_items(*imp).in_definition_order())
423                     .any(|item| item.name == variant_name)
424                 {
425                     // This is just to let `fold_item` know that this shouldn't be considered;
426                     // it's a bug for the error to make it to the user
427                     return Err(ResolutionFailure::Dummy.into());
428                 }
429                 match tcx.type_of(did).kind() {
430                     ty::Adt(def, _) if def.is_enum() => {
431                         if let Some(field) = def.all_fields().find(|f| f.name == variant_field_name)
432                         {
433                             Ok((ty_res, Some(ItemFragment(FragmentKind::VariantField, field.did))))
434                         } else {
435                             Err(ResolutionFailure::NotResolved {
436                                 item_id,
437                                 module_id,
438                                 partial_res: Some(Res::Def(DefKind::Enum, def.did())),
439                                 unresolved: variant_field_name.to_string().into(),
440                             }
441                             .into())
442                         }
443                     }
444                     _ => unreachable!(),
445                 }
446             }
447             _ => Err(ResolutionFailure::NotResolved {
448                 item_id,
449                 module_id,
450                 partial_res: Some(ty_res),
451                 unresolved: variant_name.to_string().into(),
452             }
453             .into()),
454         }
455     }
456
457     /// Given a primitive type, try to resolve an associated item.
458     fn resolve_primitive_associated_item(
459         &self,
460         prim_ty: PrimitiveType,
461         ns: Namespace,
462         item_name: Symbol,
463     ) -> Option<(Res, ItemFragment)> {
464         let tcx = self.cx.tcx;
465
466         prim_ty.impls(tcx).find_map(|impl_| {
467             tcx.associated_items(impl_)
468                 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, impl_)
469                 .map(|item| {
470                     let fragment = ItemFragment::from_assoc_item(item);
471                     (Res::Primitive(prim_ty), fragment)
472                 })
473         })
474     }
475
476     /// Resolves a string as a macro.
477     ///
478     /// FIXME(jynelson): Can this be unified with `resolve()`?
479     fn resolve_macro(
480         &self,
481         path_str: &'a str,
482         item_id: ItemId,
483         module_id: DefId,
484     ) -> Result<Res, ResolutionFailure<'a>> {
485         self.resolve_path(path_str, MacroNS, item_id, module_id).ok_or_else(|| {
486             ResolutionFailure::NotResolved {
487                 item_id,
488                 module_id,
489                 partial_res: None,
490                 unresolved: path_str.into(),
491             }
492         })
493     }
494
495     fn resolve_self_ty(&self, path_str: &str, ns: Namespace, item_id: ItemId) -> Option<Res> {
496         if ns != TypeNS || path_str != "Self" {
497             return None;
498         }
499
500         let tcx = self.cx.tcx;
501         item_id
502             .as_def_id()
503             .map(|def_id| match tcx.def_kind(def_id) {
504                 def_kind @ (DefKind::AssocFn
505                 | DefKind::AssocConst
506                 | DefKind::AssocTy
507                 | DefKind::Variant
508                 | DefKind::Field) => {
509                     let parent_def_id = tcx.parent(def_id).expect("nested item has no parent");
510                     if def_kind == DefKind::Field && tcx.def_kind(parent_def_id) == DefKind::Variant
511                     {
512                         tcx.parent(parent_def_id).expect("variant has no parent")
513                     } else {
514                         parent_def_id
515                     }
516                 }
517                 _ => def_id,
518             })
519             .and_then(|self_id| match tcx.def_kind(self_id) {
520                 DefKind::Impl => self.def_id_to_res(self_id),
521                 def_kind => Some(Res::Def(def_kind, self_id)),
522             })
523     }
524
525     /// HACK: Try to search the macro name in the list of all `macro_rules` items in the crate.
526     /// Used when nothing else works, may often give an incorrect result.
527     fn resolve_macro_rules(&self, path_str: &str, ns: Namespace) -> Option<Res> {
528         if ns != MacroNS {
529             return None;
530         }
531
532         self.cx
533             .resolver_caches
534             .all_macro_rules
535             .get(&Symbol::intern(path_str))
536             .copied()
537             .and_then(|res| res.try_into().ok())
538     }
539
540     /// Convenience wrapper around `resolve_rustdoc_path`.
541     ///
542     /// This also handles resolving `true` and `false` as booleans.
543     /// NOTE: `resolve_rustdoc_path` knows only about paths, not about types.
544     /// Associated items will never be resolved by this function.
545     fn resolve_path(
546         &self,
547         path_str: &str,
548         ns: Namespace,
549         item_id: ItemId,
550         module_id: DefId,
551     ) -> Option<Res> {
552         if let res @ Some(..) = self.resolve_self_ty(path_str, ns, item_id) {
553             return res;
554         }
555
556         // Resolver doesn't know about true, false, and types that aren't paths (e.g. `()`).
557         let result = self
558             .cx
559             .enter_resolver(|resolver| resolver.resolve_rustdoc_path(path_str, ns, module_id))
560             .and_then(|res| res.try_into().ok())
561             .or_else(|| resolve_primitive(path_str, ns))
562             .or_else(|| self.resolve_macro_rules(path_str, ns));
563         debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
564         result
565     }
566
567     /// Resolves a string as a path within a particular namespace. Returns an
568     /// optional URL fragment in the case of variants and methods.
569     fn resolve<'path>(
570         &mut self,
571         path_str: &'path str,
572         ns: Namespace,
573         item_id: ItemId,
574         module_id: DefId,
575         user_fragment: &Option<String>,
576     ) -> Result<(Res, Option<UrlFragment>), ErrorKind<'path>> {
577         let (res, rustdoc_fragment) = self.resolve_inner(path_str, ns, item_id, module_id)?;
578         let chosen_fragment = match (user_fragment, rustdoc_fragment) {
579             (Some(_), Some(r_frag)) => {
580                 let diag_res = match r_frag {
581                     ItemFragment(_, did) => Res::Def(self.cx.tcx.def_kind(did), did),
582                 };
583                 let failure = AnchorFailure::RustdocAnchorConflict(diag_res);
584                 return Err(ErrorKind::AnchorFailure(failure));
585             }
586             (Some(u_frag), None) => Some(UrlFragment::UserWritten(u_frag.clone())),
587             (None, Some(r_frag)) => Some(UrlFragment::Item(r_frag)),
588             (None, None) => None,
589         };
590         Ok((res, chosen_fragment))
591     }
592
593     fn resolve_inner<'path>(
594         &mut self,
595         path_str: &'path str,
596         ns: Namespace,
597         item_id: ItemId,
598         module_id: DefId,
599     ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'path>> {
600         if let Some(res) = self.resolve_path(path_str, ns, item_id, module_id) {
601             match res {
602                 // FIXME(#76467): make this fallthrough to lookup the associated
603                 // item a separate function.
604                 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => assert_eq!(ns, ValueNS),
605                 Res::Def(DefKind::AssocTy, _) => assert_eq!(ns, TypeNS),
606                 Res::Def(DefKind::Variant, _) => {
607                     return handle_variant(self.cx, res);
608                 }
609                 // Not a trait item; just return what we found.
610                 _ => return Ok((res, None)),
611             }
612         }
613
614         // Try looking for methods and associated items.
615         let mut split = path_str.rsplitn(2, "::");
616         // NB: `split`'s first element is always defined, even if the delimiter was not present.
617         // NB: `item_str` could be empty when resolving in the root namespace (e.g. `::std`).
618         let item_str = split.next().unwrap();
619         let item_name = Symbol::intern(item_str);
620         let path_root = split
621             .next()
622             .map(|f| f.to_owned())
623             // If there's no `::`, it's not an associated item.
624             // So we can be sure that `rustc_resolve` was accurate when it said it wasn't resolved.
625             .ok_or_else(|| {
626                 debug!("found no `::`, assumming {} was correctly not in scope", item_name);
627                 ResolutionFailure::NotResolved {
628                     item_id,
629                     module_id,
630                     partial_res: None,
631                     unresolved: item_str.into(),
632                 }
633             })?;
634
635         // FIXME(#83862): this arbitrarily gives precedence to primitives over modules to support
636         // links to primitives when `#[doc(primitive)]` is present. It should give an ambiguity
637         // error instead and special case *only* modules with `#[doc(primitive)]`, not all
638         // primitives.
639         resolve_primitive(&path_root, TypeNS)
640             .or_else(|| self.resolve_path(&path_root, TypeNS, item_id, module_id))
641             .and_then(|ty_res| {
642                 let (res, fragment) =
643                     self.resolve_associated_item(ty_res, item_name, ns, module_id)?;
644
645                 Some(Ok((res, Some(fragment))))
646             })
647             .unwrap_or_else(|| {
648                 if ns == Namespace::ValueNS {
649                     self.variant_field(path_str, item_id, module_id)
650                 } else {
651                     Err(ResolutionFailure::NotResolved {
652                         item_id,
653                         module_id,
654                         partial_res: None,
655                         unresolved: path_root.into(),
656                     }
657                     .into())
658                 }
659             })
660     }
661
662     /// Convert a DefId to a Res, where possible.
663     ///
664     /// This is used for resolving type aliases.
665     fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> {
666         use PrimitiveType::*;
667         Some(match *self.cx.tcx.type_of(ty_id).kind() {
668             ty::Bool => Res::Primitive(Bool),
669             ty::Char => Res::Primitive(Char),
670             ty::Int(ity) => Res::Primitive(ity.into()),
671             ty::Uint(uty) => Res::Primitive(uty.into()),
672             ty::Float(fty) => Res::Primitive(fty.into()),
673             ty::Str => Res::Primitive(Str),
674             ty::Tuple(tys) if tys.is_empty() => Res::Primitive(Unit),
675             ty::Tuple(_) => Res::Primitive(Tuple),
676             ty::Array(..) => Res::Primitive(Array),
677             ty::Slice(_) => Res::Primitive(Slice),
678             ty::RawPtr(_) => Res::Primitive(RawPointer),
679             ty::Ref(..) => Res::Primitive(Reference),
680             ty::FnDef(..) => panic!("type alias to a function definition"),
681             ty::FnPtr(_) => Res::Primitive(Fn),
682             ty::Never => Res::Primitive(Never),
683             ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => {
684                 Res::Def(self.cx.tcx.def_kind(did), did)
685             }
686             ty::Projection(_)
687             | ty::Closure(..)
688             | ty::Generator(..)
689             | ty::GeneratorWitness(_)
690             | ty::Opaque(..)
691             | ty::Dynamic(..)
692             | ty::Param(_)
693             | ty::Bound(..)
694             | ty::Placeholder(_)
695             | ty::Infer(_)
696             | ty::Error(_) => return None,
697         })
698     }
699
700     /// Convert a PrimitiveType to a Ty, where possible.
701     ///
702     /// This is used for resolving trait impls for primitives
703     fn primitive_type_to_ty(&mut self, prim: PrimitiveType) -> Option<Ty<'tcx>> {
704         use PrimitiveType::*;
705         let tcx = self.cx.tcx;
706
707         // FIXME: Only simple types are supported here, see if we can support
708         // other types such as Tuple, Array, Slice, etc.
709         // See https://github.com/rust-lang/rust/issues/90703#issuecomment-1004263455
710         Some(tcx.mk_ty(match prim {
711             Bool => ty::Bool,
712             Str => ty::Str,
713             Char => ty::Char,
714             Never => ty::Never,
715             I8 => ty::Int(ty::IntTy::I8),
716             I16 => ty::Int(ty::IntTy::I16),
717             I32 => ty::Int(ty::IntTy::I32),
718             I64 => ty::Int(ty::IntTy::I64),
719             I128 => ty::Int(ty::IntTy::I128),
720             Isize => ty::Int(ty::IntTy::Isize),
721             F32 => ty::Float(ty::FloatTy::F32),
722             F64 => ty::Float(ty::FloatTy::F64),
723             U8 => ty::Uint(ty::UintTy::U8),
724             U16 => ty::Uint(ty::UintTy::U16),
725             U32 => ty::Uint(ty::UintTy::U32),
726             U64 => ty::Uint(ty::UintTy::U64),
727             U128 => ty::Uint(ty::UintTy::U128),
728             Usize => ty::Uint(ty::UintTy::Usize),
729             _ => return None,
730         }))
731     }
732
733     /// Resolve an associated item, returning its containing page's `Res`
734     /// and the fragment targeting the associated item on its page.
735     fn resolve_associated_item(
736         &mut self,
737         root_res: Res,
738         item_name: Symbol,
739         ns: Namespace,
740         module_id: DefId,
741     ) -> Option<(Res, ItemFragment)> {
742         let tcx = self.cx.tcx;
743
744         match root_res {
745             Res::Primitive(prim) => {
746                 self.resolve_primitive_associated_item(prim, ns, item_name).or_else(|| {
747                     let assoc_item = self
748                         .primitive_type_to_ty(prim)
749                         .map(|ty| {
750                             resolve_associated_trait_item(ty, module_id, item_name, ns, self.cx)
751                         })
752                         .flatten();
753
754                     assoc_item.map(|item| {
755                         let fragment = ItemFragment::from_assoc_item(&item);
756                         (root_res, fragment)
757                     })
758                 })
759             }
760             Res::Def(DefKind::TyAlias, did) => {
761                 // Resolve the link on the type the alias points to.
762                 // FIXME: if the associated item is defined directly on the type alias,
763                 // it will show up on its documentation page, we should link there instead.
764                 let res = self.def_id_to_res(did)?;
765                 self.resolve_associated_item(res, item_name, ns, module_id)
766             }
767             Res::Def(
768                 def_kind @ (DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::ForeignTy),
769                 did,
770             ) => {
771                 debug!("looking for associated item named {} for item {:?}", item_name, did);
772                 // Checks if item_name is a variant of the `SomeItem` enum
773                 if ns == TypeNS && def_kind == DefKind::Enum {
774                     match tcx.type_of(did).kind() {
775                         ty::Adt(adt_def, _) => {
776                             for variant in adt_def.variants() {
777                                 if variant.name == item_name {
778                                     return Some((
779                                         root_res,
780                                         ItemFragment(FragmentKind::Variant, variant.def_id),
781                                     ));
782                                 }
783                             }
784                         }
785                         _ => unreachable!(),
786                     }
787                 }
788
789                 // Checks if item_name belongs to `impl SomeItem`
790                 let assoc_item = tcx
791                     .inherent_impls(did)
792                     .iter()
793                     .flat_map(|&imp| {
794                         tcx.associated_items(imp).find_by_name_and_namespace(
795                             tcx,
796                             Ident::with_dummy_span(item_name),
797                             ns,
798                             imp,
799                         )
800                     })
801                     .copied()
802                     // There should only ever be one associated item that matches from any inherent impl
803                     .next()
804                     // Check if item_name belongs to `impl SomeTrait for SomeItem`
805                     // FIXME(#74563): This gives precedence to `impl SomeItem`:
806                     // Although having both would be ambiguous, use impl version for compatibility's sake.
807                     // To handle that properly resolve() would have to support
808                     // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
809                     .or_else(|| {
810                         resolve_associated_trait_item(
811                             tcx.type_of(did),
812                             module_id,
813                             item_name,
814                             ns,
815                             self.cx,
816                         )
817                     });
818
819                 debug!("got associated item {:?}", assoc_item);
820
821                 if let Some(item) = assoc_item {
822                     let fragment = ItemFragment::from_assoc_item(&item);
823                     return Some((root_res, fragment));
824                 }
825
826                 if ns != Namespace::ValueNS {
827                     return None;
828                 }
829                 debug!("looking for fields named {} for {:?}", item_name, did);
830                 // FIXME: this doesn't really belong in `associated_item` (maybe `variant_field` is better?)
831                 // NOTE: it's different from variant_field because it only resolves struct fields,
832                 // not variant fields (2 path segments, not 3).
833                 //
834                 // We need to handle struct (and union) fields in this code because
835                 // syntactically their paths are identical to associated item paths:
836                 // `module::Type::field` and `module::Type::Assoc`.
837                 //
838                 // On the other hand, variant fields can't be mistaken for associated
839                 // items because they look like this: `module::Type::Variant::field`.
840                 //
841                 // Variants themselves don't need to be handled here, even though
842                 // they also look like associated items (`module::Type::Variant`),
843                 // because they are real Rust syntax (unlike the intra-doc links
844                 // field syntax) and are handled by the compiler's resolver.
845                 let def = match tcx.type_of(did).kind() {
846                     ty::Adt(def, _) if !def.is_enum() => def,
847                     _ => return None,
848                 };
849                 let field =
850                     def.non_enum_variant().fields.iter().find(|item| item.name == item_name)?;
851                 Some((root_res, ItemFragment(FragmentKind::StructField, field.did)))
852             }
853             Res::Def(DefKind::Trait, did) => tcx
854                 .associated_items(did)
855                 .find_by_name_and_namespace(tcx, Ident::with_dummy_span(item_name), ns, did)
856                 .map(|item| {
857                     let fragment = ItemFragment::from_assoc_item(item);
858                     let res = Res::Def(item.kind.as_def_kind(), item.def_id);
859                     (res, fragment)
860                 }),
861             _ => None,
862         }
863     }
864
865     /// Used for reporting better errors.
866     ///
867     /// Returns whether the link resolved 'fully' in another namespace.
868     /// 'fully' here means that all parts of the link resolved, not just some path segments.
869     /// This returns the `Res` even if it was erroneous for some reason
870     /// (such as having invalid URL fragments or being in the wrong namespace).
871     fn check_full_res(
872         &mut self,
873         ns: Namespace,
874         path_str: &str,
875         item_id: ItemId,
876         module_id: DefId,
877         extra_fragment: &Option<String>,
878     ) -> Option<Res> {
879         // resolve() can't be used for macro namespace
880         let result = match ns {
881             Namespace::MacroNS => self
882                 .resolve_macro(path_str, item_id, module_id)
883                 .map(|res| (res, None))
884                 .map_err(ErrorKind::from),
885             Namespace::TypeNS | Namespace::ValueNS => {
886                 self.resolve(path_str, ns, item_id, module_id, extra_fragment)
887             }
888         };
889
890         let res = match result {
891             Ok((res, frag)) => {
892                 if let Some(UrlFragment::Item(ItemFragment(_, id))) = frag {
893                     Some(Res::Def(self.cx.tcx.def_kind(id), id))
894                 } else {
895                     Some(res)
896                 }
897             }
898             Err(ErrorKind::Resolve(box kind)) => kind.full_res(),
899             Err(ErrorKind::AnchorFailure(AnchorFailure::RustdocAnchorConflict(res))) => Some(res),
900             Err(ErrorKind::AnchorFailure(AnchorFailure::MultipleAnchors)) => None,
901         };
902         res
903     }
904 }
905
906 /// Look to see if a resolved item has an associated item named `item_name`.
907 ///
908 /// Given `[std::io::Error::source]`, where `source` is unresolved, this would
909 /// find `std::error::Error::source` and return
910 /// `<io::Error as error::Error>::source`.
911 fn resolve_associated_trait_item<'a>(
912     ty: Ty<'a>,
913     module: DefId,
914     item_name: Symbol,
915     ns: Namespace,
916     cx: &mut DocContext<'a>,
917 ) -> Option<ty::AssocItem> {
918     // FIXME: this should also consider blanket impls (`impl<T> X for T`). Unfortunately
919     // `get_auto_trait_and_blanket_impls` is broken because the caching behavior is wrong. In the
920     // meantime, just don't look for these blanket impls.
921
922     // Next consider explicit impls: `impl MyTrait for MyType`
923     // Give precedence to inherent impls.
924     let traits = trait_impls_for(cx, ty, module);
925     debug!("considering traits {:?}", traits);
926     let mut candidates = traits.iter().filter_map(|&(impl_, trait_)| {
927         cx.tcx
928             .associated_items(trait_)
929             .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
930             .map(|trait_assoc| {
931                 trait_assoc_to_impl_assoc_item(cx.tcx, impl_, trait_assoc.def_id)
932                     .unwrap_or(trait_assoc)
933             })
934     });
935     // FIXME(#74563): warn about ambiguity
936     debug!("the candidates were {:?}", candidates.clone().collect::<Vec<_>>());
937     candidates.next().copied()
938 }
939
940 /// Find the associated item in the impl `impl_id` that corresponds to the
941 /// trait associated item `trait_assoc_id`.
942 ///
943 /// This function returns `None` if no associated item was found in the impl.
944 /// This can occur when the trait associated item has a default value that is
945 /// not overridden in the impl.
946 ///
947 /// This is just a wrapper around [`TyCtxt::impl_item_implementor_ids()`] and
948 /// [`TyCtxt::associated_item()`] (with some helpful logging added).
949 #[instrument(level = "debug", skip(tcx))]
950 fn trait_assoc_to_impl_assoc_item<'tcx>(
951     tcx: TyCtxt<'tcx>,
952     impl_id: DefId,
953     trait_assoc_id: DefId,
954 ) -> Option<&'tcx ty::AssocItem> {
955     let trait_to_impl_assoc_map = tcx.impl_item_implementor_ids(impl_id);
956     debug!(?trait_to_impl_assoc_map);
957     let impl_assoc_id = *trait_to_impl_assoc_map.get(&trait_assoc_id)?;
958     debug!(?impl_assoc_id);
959     let impl_assoc = tcx.associated_item(impl_assoc_id);
960     debug!(?impl_assoc);
961     Some(impl_assoc)
962 }
963
964 /// Given a type, return all trait impls in scope in `module` for that type.
965 /// Returns a set of pairs of `(impl_id, trait_id)`.
966 ///
967 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
968 /// So it is not stable to serialize cross-crate.
969 #[instrument(level = "debug", skip(cx))]
970 fn trait_impls_for<'a>(
971     cx: &mut DocContext<'a>,
972     ty: Ty<'a>,
973     module: DefId,
974 ) -> FxHashSet<(DefId, DefId)> {
975     let tcx = cx.tcx;
976     let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
977         let trait_ = trait_candidate.def_id;
978         trace!("considering explicit impl for trait {:?}", trait_);
979
980         // Look at each trait implementation to see if it's an impl for `did`
981         tcx.find_map_relevant_impl(trait_, ty, |impl_| {
982             let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
983             // Check if these are the same type.
984             let impl_type = trait_ref.self_ty();
985             trace!(
986                 "comparing type {} with kind {:?} against type {:?}",
987                 impl_type,
988                 impl_type.kind(),
989                 ty
990             );
991             // Fast path: if this is a primitive simple `==` will work
992             // NOTE: the `match` is necessary; see #92662.
993             // this allows us to ignore generics because the user input
994             // may not include the generic placeholders
995             // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
996             let saw_impl = impl_type == ty
997                 || match (impl_type.kind(), ty.kind()) {
998                     (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
999                         debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did(), ty_def.did());
1000                         impl_def.did() == ty_def.did()
1001                     }
1002                     _ => false,
1003                 };
1004
1005             if saw_impl { Some((impl_, trait_)) } else { None }
1006         })
1007     });
1008     iter.collect()
1009 }
1010
1011 /// Check for resolve collisions between a trait and its derive.
1012 ///
1013 /// These are common and we should just resolve to the trait in that case.
1014 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
1015     matches!(
1016         *ns,
1017         PerNS {
1018             type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
1019             macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
1020             ..
1021         }
1022     )
1023 }
1024
1025 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
1026     fn visit_item(&mut self, item: &Item) {
1027         let parent_node =
1028             item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
1029         if parent_node.is_some() {
1030             trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
1031         }
1032
1033         let inner_docs = item.inner_docs(self.cx.tcx);
1034
1035         if item.is_mod() && inner_docs {
1036             self.mod_ids.push(item.def_id.expect_def_id());
1037         }
1038
1039         // We want to resolve in the lexical scope of the documentation.
1040         // In the presence of re-exports, this is not the same as the module of the item.
1041         // Rather than merging all documentation into one, resolve it one attribute at a time
1042         // so we know which module it came from.
1043         for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
1044             debug!("combined_docs={}", doc);
1045             // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1046             // This is a degenerate case and it's not supported by rustdoc.
1047             let parent_node = parent_module.or(parent_node);
1048             for md_link in markdown_links(&doc) {
1049                 let link = self.resolve_link(&item, &doc, parent_node, md_link);
1050                 if let Some(link) = link {
1051                     self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
1052                 }
1053             }
1054         }
1055
1056         if item.is_mod() {
1057             if !inner_docs {
1058                 self.mod_ids.push(item.def_id.expect_def_id());
1059             }
1060
1061             self.visit_item_recur(item);
1062             self.mod_ids.pop();
1063         } else {
1064             self.visit_item_recur(item)
1065         }
1066     }
1067 }
1068
1069 enum PreprocessingError<'a> {
1070     Anchor(AnchorFailure),
1071     Disambiguator(Range<usize>, String),
1072     Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
1073 }
1074
1075 impl From<AnchorFailure> for PreprocessingError<'_> {
1076     fn from(err: AnchorFailure) -> Self {
1077         Self::Anchor(err)
1078     }
1079 }
1080
1081 struct PreprocessingInfo {
1082     path_str: String,
1083     disambiguator: Option<Disambiguator>,
1084     extra_fragment: Option<String>,
1085     link_text: String,
1086 }
1087
1088 /// Returns:
1089 /// - `None` if the link should be ignored.
1090 /// - `Some(Err)` if the link should emit an error
1091 /// - `Some(Ok)` if the link is valid
1092 ///
1093 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
1094 fn preprocess_link<'a>(
1095     ori_link: &'a MarkdownLink,
1096 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
1097     // [] is mostly likely not supposed to be a link
1098     if ori_link.link.is_empty() {
1099         return None;
1100     }
1101
1102     // Bail early for real links.
1103     if ori_link.link.contains('/') {
1104         return None;
1105     }
1106
1107     let stripped = ori_link.link.replace('`', "");
1108     let mut parts = stripped.split('#');
1109
1110     let link = parts.next().unwrap();
1111     if link.trim().is_empty() {
1112         // This is an anchor to an element of the current page, nothing to do in here!
1113         return None;
1114     }
1115     let extra_fragment = parts.next();
1116     if parts.next().is_some() {
1117         // A valid link can't have multiple #'s
1118         return Some(Err(AnchorFailure::MultipleAnchors.into()));
1119     }
1120
1121     // Parse and strip the disambiguator from the link, if present.
1122     let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1123         Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1124         Ok(None) => (None, link.trim(), link.trim()),
1125         Err((err_msg, relative_range)) => {
1126             // Only report error if we would not have ignored this link. See issue #83859.
1127             if !should_ignore_link_with_disambiguators(link) {
1128                 let no_backticks_range = range_between_backticks(ori_link);
1129                 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1130                     ..(no_backticks_range.start + relative_range.end);
1131                 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1132             } else {
1133                 return None;
1134             }
1135         }
1136     };
1137
1138     if should_ignore_link(path_str) {
1139         return None;
1140     }
1141
1142     // Strip generics from the path.
1143     let path_str = if path_str.contains(['<', '>'].as_slice()) {
1144         match strip_generics_from_path(path_str) {
1145             Ok(path) => path,
1146             Err(err_kind) => {
1147                 debug!("link has malformed generics: {}", path_str);
1148                 return Some(Err(PreprocessingError::Resolution(
1149                     err_kind,
1150                     path_str.to_owned(),
1151                     disambiguator,
1152                 )));
1153             }
1154         }
1155     } else {
1156         path_str.to_owned()
1157     };
1158
1159     // Sanity check to make sure we don't have any angle brackets after stripping generics.
1160     assert!(!path_str.contains(['<', '>'].as_slice()));
1161
1162     // The link is not an intra-doc link if it still contains spaces after stripping generics.
1163     if path_str.contains(' ') {
1164         return None;
1165     }
1166
1167     Some(Ok(PreprocessingInfo {
1168         path_str,
1169         disambiguator,
1170         extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1171         link_text: link_text.to_owned(),
1172     }))
1173 }
1174
1175 impl LinkCollector<'_, '_> {
1176     /// This is the entry point for resolving an intra-doc link.
1177     ///
1178     /// FIXME(jynelson): this is way too many arguments
1179     fn resolve_link(
1180         &mut self,
1181         item: &Item,
1182         dox: &str,
1183         parent_node: Option<DefId>,
1184         ori_link: MarkdownLink,
1185     ) -> Option<ItemLink> {
1186         trace!("considering link '{}'", ori_link.link);
1187
1188         let diag_info = DiagnosticInfo {
1189             item,
1190             dox,
1191             ori_link: &ori_link.link,
1192             link_range: ori_link.range.clone(),
1193         };
1194
1195         let PreprocessingInfo { ref path_str, disambiguator, extra_fragment, link_text } =
1196             match preprocess_link(&ori_link)? {
1197                 Ok(x) => x,
1198                 Err(err) => {
1199                     match err {
1200                         PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1201                         PreprocessingError::Disambiguator(range, msg) => {
1202                             disambiguator_error(self.cx, diag_info, range, &msg)
1203                         }
1204                         PreprocessingError::Resolution(err, path_str, disambiguator) => {
1205                             resolution_failure(
1206                                 self,
1207                                 diag_info,
1208                                 &path_str,
1209                                 disambiguator,
1210                                 smallvec![err],
1211                             );
1212                         }
1213                     }
1214                     return None;
1215                 }
1216             };
1217
1218         let inner_docs = item.inner_docs(self.cx.tcx);
1219
1220         // In order to correctly resolve intra-doc links we need to
1221         // pick a base AST node to work from.  If the documentation for
1222         // this module came from an inner comment (//!) then we anchor
1223         // our name resolution *inside* the module.  If, on the other
1224         // hand it was an outer comment (///) then we anchor the name
1225         // resolution in the parent module on the basis that the names
1226         // used are more likely to be intended to be parent names.  For
1227         // this, we set base_node to None for inner comments since
1228         // we've already pushed this node onto the resolution stack but
1229         // for outer comments we explicitly try and resolve against the
1230         // parent_node first.
1231         let base_node =
1232             if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1233
1234         let Some(module_id) = base_node else {
1235             // This is a bug.
1236             debug!("attempting to resolve item without parent module: {}", path_str);
1237             resolution_failure(
1238                 self,
1239                 diag_info,
1240                 path_str,
1241                 disambiguator,
1242                 smallvec![ResolutionFailure::NoParentItem],
1243             );
1244             return None;
1245         };
1246
1247         let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1248             ResolutionInfo {
1249                 item_id: item.def_id,
1250                 module_id,
1251                 dis: disambiguator,
1252                 path_str: path_str.to_owned(),
1253                 extra_fragment,
1254             },
1255             diag_info.clone(), // this struct should really be Copy, but Range is not :(
1256             matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1257         )?;
1258
1259         // Check for a primitive which might conflict with a module
1260         // Report the ambiguity and require that the user specify which one they meant.
1261         // FIXME: could there ever be a primitive not in the type namespace?
1262         if matches!(
1263             disambiguator,
1264             None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1265         ) && !matches!(res, Res::Primitive(_))
1266         {
1267             if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1268                 // `prim@char`
1269                 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1270                     res = prim;
1271                 } else {
1272                     // `[char]` when a `char` module is in scope
1273                     let candidates = vec![res, prim];
1274                     ambiguity_error(self.cx, diag_info, path_str, candidates);
1275                     return None;
1276                 }
1277             }
1278         }
1279
1280         match res {
1281             Res::Primitive(prim) => {
1282                 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1283                     // We're actually resolving an associated item of a primitive, so we need to
1284                     // verify the disambiguator (if any) matches the type of the associated item.
1285                     // This case should really follow the same flow as the `Res::Def` branch below,
1286                     // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1287                     // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1288                     // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1289                     // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1290                     // for discussion on the matter.
1291                     let kind = self.cx.tcx.def_kind(id);
1292                     self.verify_disambiguator(
1293                         path_str,
1294                         &ori_link,
1295                         kind,
1296                         id,
1297                         disambiguator,
1298                         item,
1299                         &diag_info,
1300                     )?;
1301
1302                     // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1303                     // However I'm not sure how to check that across crates.
1304                     if prim == PrimitiveType::RawPointer
1305                         && item.def_id.is_local()
1306                         && !self.cx.tcx.features().intra_doc_pointers
1307                     {
1308                         self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1309                     }
1310                 } else {
1311                     match disambiguator {
1312                         Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1313                         Some(other) => {
1314                             self.report_disambiguator_mismatch(
1315                                 path_str, &ori_link, other, res, &diag_info,
1316                             );
1317                             return None;
1318                         }
1319                     }
1320                 }
1321
1322                 Some(ItemLink {
1323                     link: ori_link.link,
1324                     link_text,
1325                     did: res.def_id(self.cx.tcx),
1326                     fragment,
1327                 })
1328             }
1329             Res::Def(kind, id) => {
1330                 let (kind_for_dis, id_for_dis) =
1331                     if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1332                         (self.cx.tcx.def_kind(id), id)
1333                     } else {
1334                         (kind, id)
1335                     };
1336                 self.verify_disambiguator(
1337                     path_str,
1338                     &ori_link,
1339                     kind_for_dis,
1340                     id_for_dis,
1341                     disambiguator,
1342                     item,
1343                     &diag_info,
1344                 )?;
1345                 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1346                 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1347             }
1348         }
1349     }
1350
1351     fn verify_disambiguator(
1352         &self,
1353         path_str: &str,
1354         ori_link: &MarkdownLink,
1355         kind: DefKind,
1356         id: DefId,
1357         disambiguator: Option<Disambiguator>,
1358         item: &Item,
1359         diag_info: &DiagnosticInfo<'_>,
1360     ) -> Option<()> {
1361         debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1362
1363         // Disallow e.g. linking to enums with `struct@`
1364         debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1365         match (kind, disambiguator) {
1366                 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1367                 // NOTE: this allows 'method' to mean both normal functions and associated functions
1368                 // This can't cause ambiguity because both are in the same namespace.
1369                 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1370                 // These are namespaces; allow anything in the namespace to match
1371                 | (_, Some(Disambiguator::Namespace(_)))
1372                 // If no disambiguator given, allow anything
1373                 | (_, None)
1374                 // All of these are valid, so do nothing
1375                 => {}
1376                 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1377                 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1378                     self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1379                     return None;
1380                 }
1381             }
1382
1383         // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1384         if let Some((src_id, dst_id)) = id
1385             .as_local()
1386             // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1387             // would presumably panic if a fake `DefIndex` were passed.
1388             .and_then(|dst_id| {
1389                 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1390             })
1391         {
1392             if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1393                 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1394             {
1395                 privacy_error(self.cx, diag_info, path_str);
1396             }
1397         }
1398
1399         Some(())
1400     }
1401
1402     fn report_disambiguator_mismatch(
1403         &self,
1404         path_str: &str,
1405         ori_link: &MarkdownLink,
1406         specified: Disambiguator,
1407         resolved: Res,
1408         diag_info: &DiagnosticInfo<'_>,
1409     ) {
1410         // The resolved item did not match the disambiguator; give a better error than 'not found'
1411         let msg = format!("incompatible link kind for `{}`", path_str);
1412         let callback = |diag: &mut Diagnostic, sp: Option<rustc_span::Span>| {
1413             let note = format!(
1414                 "this link resolved to {} {}, which is not {} {}",
1415                 resolved.article(),
1416                 resolved.descr(),
1417                 specified.article(),
1418                 specified.descr(),
1419             );
1420             if let Some(sp) = sp {
1421                 diag.span_label(sp, &note);
1422             } else {
1423                 diag.note(&note);
1424             }
1425             suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1426         };
1427         report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1428     }
1429
1430     fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1431         let span =
1432             super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1433                 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1434         rustc_session::parse::feature_err(
1435             &self.cx.tcx.sess.parse_sess,
1436             sym::intra_doc_pointers,
1437             span,
1438             "linking to associated items of raw pointers is experimental",
1439         )
1440         .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1441         .emit();
1442     }
1443
1444     fn resolve_with_disambiguator_cached(
1445         &mut self,
1446         key: ResolutionInfo,
1447         diag: DiagnosticInfo<'_>,
1448         cache_resolution_failure: bool,
1449     ) -> Option<(Res, Option<UrlFragment>)> {
1450         if let Some(ref cached) = self.visited_links.get(&key) {
1451             match cached {
1452                 Some(cached) => {
1453                     return Some(cached.res.clone());
1454                 }
1455                 None if cache_resolution_failure => return None,
1456                 None => {
1457                     // Although we hit the cache and found a resolution error, this link isn't
1458                     // supposed to cache those. Run link resolution again to emit the expected
1459                     // resolution error.
1460                 }
1461             }
1462         }
1463
1464         let res = self.resolve_with_disambiguator(&key, diag);
1465
1466         // Cache only if resolved successfully - don't silence duplicate errors
1467         if let Some(res) = res {
1468             // Store result for the actual namespace
1469             self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1470
1471             Some(res)
1472         } else {
1473             if cache_resolution_failure {
1474                 // For reference-style links we only want to report one resolution error
1475                 // so let's cache them as well.
1476                 self.visited_links.insert(key, None);
1477             }
1478
1479             None
1480         }
1481     }
1482
1483     /// After parsing the disambiguator, resolve the main part of the link.
1484     // FIXME(jynelson): wow this is just so much
1485     fn resolve_with_disambiguator(
1486         &mut self,
1487         key: &ResolutionInfo,
1488         diag: DiagnosticInfo<'_>,
1489     ) -> Option<(Res, Option<UrlFragment>)> {
1490         let disambiguator = key.dis;
1491         let path_str = &key.path_str;
1492         let item_id = key.item_id;
1493         let base_node = key.module_id;
1494         let extra_fragment = &key.extra_fragment;
1495
1496         match disambiguator.map(Disambiguator::ns) {
1497             Some(expected_ns @ (ValueNS | TypeNS)) => {
1498                 match self.resolve(path_str, expected_ns, item_id, base_node, extra_fragment) {
1499                     Ok(res) => Some(res),
1500                     Err(ErrorKind::Resolve(box mut kind)) => {
1501                         // We only looked in one namespace. Try to give a better error if possible.
1502                         if kind.full_res().is_none() {
1503                             let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1504                             // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1505                             // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1506                             for new_ns in [other_ns, MacroNS] {
1507                                 if let Some(res) = self.check_full_res(
1508                                     new_ns,
1509                                     path_str,
1510                                     item_id,
1511                                     base_node,
1512                                     extra_fragment,
1513                                 ) {
1514                                     kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1515                                     break;
1516                                 }
1517                             }
1518                         }
1519                         resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1520                         // This could just be a normal link or a broken link
1521                         // we could potentially check if something is
1522                         // "intra-doc-link-like" and warn in that case.
1523                         None
1524                     }
1525                     Err(ErrorKind::AnchorFailure(msg)) => {
1526                         anchor_failure(self.cx, diag, msg);
1527                         None
1528                     }
1529                 }
1530             }
1531             None => {
1532                 // Try everything!
1533                 let mut candidates = PerNS {
1534                     macro_ns: self
1535                         .resolve_macro(path_str, item_id, base_node)
1536                         .map(|res| (res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1537                     type_ns: match self.resolve(
1538                         path_str,
1539                         TypeNS,
1540                         item_id,
1541                         base_node,
1542                         extra_fragment,
1543                     ) {
1544                         Ok(res) => {
1545                             debug!("got res in TypeNS: {:?}", res);
1546                             Ok(res)
1547                         }
1548                         Err(ErrorKind::AnchorFailure(msg)) => {
1549                             anchor_failure(self.cx, diag, msg);
1550                             return None;
1551                         }
1552                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1553                     },
1554                     value_ns: match self.resolve(
1555                         path_str,
1556                         ValueNS,
1557                         item_id,
1558                         base_node,
1559                         extra_fragment,
1560                     ) {
1561                         Ok(res) => Ok(res),
1562                         Err(ErrorKind::AnchorFailure(msg)) => {
1563                             anchor_failure(self.cx, diag, msg);
1564                             return None;
1565                         }
1566                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1567                     }
1568                     .and_then(|(res, fragment)| {
1569                         // Constructors are picked up in the type namespace.
1570                         match res {
1571                             Res::Def(DefKind::Ctor(..), _) => {
1572                                 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1573                             }
1574                             _ => {
1575                                 match (fragment, extra_fragment.clone()) {
1576                                     (Some(fragment), Some(_)) => {
1577                                         // Shouldn't happen but who knows?
1578                                         Ok((res, Some(fragment)))
1579                                     }
1580                                     (fragment, None) => Ok((res, fragment)),
1581                                     (None, fragment) => {
1582                                         Ok((res, fragment.map(UrlFragment::UserWritten)))
1583                                     }
1584                                 }
1585                             }
1586                         }
1587                     }),
1588                 };
1589
1590                 let len = candidates.iter().filter(|res| res.is_ok()).count();
1591
1592                 if len == 0 {
1593                     resolution_failure(
1594                         self,
1595                         diag,
1596                         path_str,
1597                         disambiguator,
1598                         candidates.into_iter().filter_map(|res| res.err()).collect(),
1599                     );
1600                     // this could just be a normal link
1601                     return None;
1602                 }
1603
1604                 if len == 1 {
1605                     Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1606                 } else if len == 2 && is_derive_trait_collision(&candidates) {
1607                     Some(candidates.type_ns.unwrap())
1608                 } else {
1609                     if is_derive_trait_collision(&candidates) {
1610                         candidates.macro_ns = Err(ResolutionFailure::Dummy);
1611                     }
1612                     // If we're reporting an ambiguity, don't mention the namespaces that failed
1613                     let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1614                     ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1615                     None
1616                 }
1617             }
1618             Some(MacroNS) => {
1619                 match self.resolve_macro(path_str, item_id, base_node) {
1620                     Ok(res) => Some((res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1621                     Err(mut kind) => {
1622                         // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1623                         for ns in [TypeNS, ValueNS] {
1624                             if let Some(res) = self.check_full_res(
1625                                 ns,
1626                                 path_str,
1627                                 item_id,
1628                                 base_node,
1629                                 extra_fragment,
1630                             ) {
1631                                 kind =
1632                                     ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1633                                 break;
1634                             }
1635                         }
1636                         resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1637                         None
1638                     }
1639                 }
1640             }
1641         }
1642     }
1643 }
1644
1645 /// Get the section of a link between the backticks,
1646 /// or the whole link if there aren't any backticks.
1647 ///
1648 /// For example:
1649 ///
1650 /// ```text
1651 /// [`Foo`]
1652 ///   ^^^
1653 /// ```
1654 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1655     let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1656     let before_second_backtick_group = ori_link
1657         .link
1658         .bytes()
1659         .skip(after_first_backtick_group)
1660         .position(|b| b == b'`')
1661         .unwrap_or(ori_link.link.len());
1662     (ori_link.range.start + after_first_backtick_group)
1663         ..(ori_link.range.start + before_second_backtick_group)
1664 }
1665
1666 /// Returns true if we should ignore `link` due to it being unlikely
1667 /// that it is an intra-doc link. `link` should still have disambiguators
1668 /// if there were any.
1669 ///
1670 /// The difference between this and [`should_ignore_link()`] is that this
1671 /// check should only be used on links that still have disambiguators.
1672 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1673     link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1674 }
1675
1676 /// Returns true if we should ignore `path_str` due to it being unlikely
1677 /// that it is an intra-doc link.
1678 fn should_ignore_link(path_str: &str) -> bool {
1679     path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1680 }
1681
1682 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1683 /// Disambiguators for a link.
1684 enum Disambiguator {
1685     /// `prim@`
1686     ///
1687     /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1688     Primitive,
1689     /// `struct@` or `f()`
1690     Kind(DefKind),
1691     /// `type@`
1692     Namespace(Namespace),
1693 }
1694
1695 impl Disambiguator {
1696     /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1697     ///
1698     /// This returns `Ok(Some(...))` if a disambiguator was found,
1699     /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1700     /// if there was a problem with the disambiguator.
1701     fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1702         use Disambiguator::{Kind, Namespace as NS, Primitive};
1703
1704         if let Some(idx) = link.find('@') {
1705             let (prefix, rest) = link.split_at(idx);
1706             let d = match prefix {
1707                 "struct" => Kind(DefKind::Struct),
1708                 "enum" => Kind(DefKind::Enum),
1709                 "trait" => Kind(DefKind::Trait),
1710                 "union" => Kind(DefKind::Union),
1711                 "module" | "mod" => Kind(DefKind::Mod),
1712                 "const" | "constant" => Kind(DefKind::Const),
1713                 "static" => Kind(DefKind::Static(Mutability::Not)),
1714                 "function" | "fn" | "method" => Kind(DefKind::Fn),
1715                 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1716                 "type" => NS(Namespace::TypeNS),
1717                 "value" => NS(Namespace::ValueNS),
1718                 "macro" => NS(Namespace::MacroNS),
1719                 "prim" | "primitive" => Primitive,
1720                 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1721             };
1722             Ok(Some((d, &rest[1..], &rest[1..])))
1723         } else {
1724             let suffixes = [
1725                 ("!()", DefKind::Macro(MacroKind::Bang)),
1726                 ("!{}", DefKind::Macro(MacroKind::Bang)),
1727                 ("![]", DefKind::Macro(MacroKind::Bang)),
1728                 ("()", DefKind::Fn),
1729                 ("!", DefKind::Macro(MacroKind::Bang)),
1730             ];
1731             for (suffix, kind) in suffixes {
1732                 if let Some(path_str) = link.strip_suffix(suffix) {
1733                     // Avoid turning `!` or `()` into an empty string
1734                     if !path_str.is_empty() {
1735                         return Ok(Some((Kind(kind), path_str, link)));
1736                     }
1737                 }
1738             }
1739             Ok(None)
1740         }
1741     }
1742
1743     fn ns(self) -> Namespace {
1744         match self {
1745             Self::Namespace(n) => n,
1746             Self::Kind(k) => {
1747                 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1748             }
1749             Self::Primitive => TypeNS,
1750         }
1751     }
1752
1753     fn article(self) -> &'static str {
1754         match self {
1755             Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1756             Self::Kind(k) => k.article(),
1757             Self::Primitive => "a",
1758         }
1759     }
1760
1761     fn descr(self) -> &'static str {
1762         match self {
1763             Self::Namespace(n) => n.descr(),
1764             // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1765             // printing "module" vs "crate" so using the wrong ID is not a huge problem
1766             Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1767             Self::Primitive => "builtin type",
1768         }
1769     }
1770 }
1771
1772 /// A suggestion to show in a diagnostic.
1773 enum Suggestion {
1774     /// `struct@`
1775     Prefix(&'static str),
1776     /// `f()`
1777     Function,
1778     /// `m!`
1779     Macro,
1780     /// `foo` without any disambiguator
1781     RemoveDisambiguator,
1782 }
1783
1784 impl Suggestion {
1785     fn descr(&self) -> Cow<'static, str> {
1786         match self {
1787             Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1788             Self::Function => "add parentheses".into(),
1789             Self::Macro => "add an exclamation mark".into(),
1790             Self::RemoveDisambiguator => "remove the disambiguator".into(),
1791         }
1792     }
1793
1794     fn as_help(&self, path_str: &str) -> String {
1795         // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1796         match self {
1797             Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1798             Self::Function => format!("{}()", path_str),
1799             Self::Macro => format!("{}!", path_str),
1800             Self::RemoveDisambiguator => path_str.into(),
1801         }
1802     }
1803
1804     fn as_help_span(
1805         &self,
1806         path_str: &str,
1807         ori_link: &str,
1808         sp: rustc_span::Span,
1809     ) -> Vec<(rustc_span::Span, String)> {
1810         let inner_sp = match ori_link.find('(') {
1811             Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1812             None => sp,
1813         };
1814         let inner_sp = match ori_link.find('!') {
1815             Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1816             None => inner_sp,
1817         };
1818         let inner_sp = match ori_link.find('@') {
1819             Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1820             None => inner_sp,
1821         };
1822         match self {
1823             Self::Prefix(prefix) => {
1824                 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1825                 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1826                 if sp.hi() != inner_sp.hi() {
1827                     sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1828                 }
1829                 sugg
1830             }
1831             Self::Function => {
1832                 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1833                 if sp.lo() != inner_sp.lo() {
1834                     sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1835                 }
1836                 sugg
1837             }
1838             Self::Macro => {
1839                 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1840                 if sp.lo() != inner_sp.lo() {
1841                     sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1842                 }
1843                 sugg
1844             }
1845             Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1846         }
1847     }
1848 }
1849
1850 /// Reports a diagnostic for an intra-doc link.
1851 ///
1852 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1853 /// the entire documentation block is used for the lint. If a range is provided but the span
1854 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1855 ///
1856 /// The `decorate` callback is invoked in all cases to allow further customization of the
1857 /// diagnostic before emission. If the span of the link was able to be determined, the second
1858 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1859 /// to it.
1860 fn report_diagnostic(
1861     tcx: TyCtxt<'_>,
1862     lint: &'static Lint,
1863     msg: &str,
1864     DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1865     decorate: impl FnOnce(&mut Diagnostic, Option<rustc_span::Span>),
1866 ) {
1867     let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.def_id)
1868     else {
1869         // If non-local, no need to check anything.
1870         info!("ignoring warning from parent crate: {}", msg);
1871         return;
1872     };
1873
1874     let sp = item.attr_span(tcx);
1875
1876     tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1877         let mut diag = lint.build(msg);
1878
1879         let span =
1880             super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1881                 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1882                     && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1883                 {
1884                     sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1885                 } else {
1886                     sp
1887                 }
1888             });
1889
1890         if let Some(sp) = span {
1891             diag.set_span(sp);
1892         } else {
1893             // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1894             //                       ^     ~~~~
1895             //                       |     link_range
1896             //                       last_new_line_offset
1897             let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1898             let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1899
1900             // Print the line containing the `link_range` and manually mark it with '^'s.
1901             diag.note(&format!(
1902                 "the link appears in this line:\n\n{line}\n\
1903                      {indicator: <before$}{indicator:^<found$}",
1904                 line = line,
1905                 indicator = "",
1906                 before = link_range.start - last_new_line_offset,
1907                 found = link_range.len(),
1908             ));
1909         }
1910
1911         decorate(&mut diag, span);
1912
1913         diag.emit();
1914     });
1915 }
1916
1917 /// Reports a link that failed to resolve.
1918 ///
1919 /// This also tries to resolve any intermediate path segments that weren't
1920 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1921 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1922 fn resolution_failure(
1923     collector: &mut LinkCollector<'_, '_>,
1924     diag_info: DiagnosticInfo<'_>,
1925     path_str: &str,
1926     disambiguator: Option<Disambiguator>,
1927     kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1928 ) {
1929     let tcx = collector.cx.tcx;
1930     report_diagnostic(
1931         tcx,
1932         BROKEN_INTRA_DOC_LINKS,
1933         &format!("unresolved link to `{}`", path_str),
1934         &diag_info,
1935         |diag, sp| {
1936             let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1937             let assoc_item_not_allowed = |res: Res| {
1938                 let name = res.name(tcx);
1939                 format!(
1940                     "`{}` is {} {}, not a module or type, and cannot have associated items",
1941                     name,
1942                     res.article(),
1943                     res.descr()
1944                 )
1945             };
1946             // ignore duplicates
1947             let mut variants_seen = SmallVec::<[_; 3]>::new();
1948             for mut failure in kinds {
1949                 let variant = std::mem::discriminant(&failure);
1950                 if variants_seen.contains(&variant) {
1951                     continue;
1952                 }
1953                 variants_seen.push(variant);
1954
1955                 if let ResolutionFailure::NotResolved {
1956                     item_id,
1957                     module_id,
1958                     partial_res,
1959                     unresolved,
1960                 } = &mut failure
1961                 {
1962                     use DefKind::*;
1963
1964                     let item_id = *item_id;
1965                     let module_id = *module_id;
1966                     // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1967                     // FIXME: maybe use itertools `collect_tuple` instead?
1968                     fn split(path: &str) -> Option<(&str, &str)> {
1969                         let mut splitter = path.rsplitn(2, "::");
1970                         splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1971                     }
1972
1973                     // Check if _any_ parent of the path gets resolved.
1974                     // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1975                     let mut name = path_str;
1976                     'outer: loop {
1977                         let Some((start, end)) = split(name) else {
1978                             // avoid bug that marked [Quux::Z] as missing Z, not Quux
1979                             if partial_res.is_none() {
1980                                 *unresolved = name.into();
1981                             }
1982                             break;
1983                         };
1984                         name = start;
1985                         for ns in [TypeNS, ValueNS, MacroNS] {
1986                             if let Some(res) =
1987                                 collector.check_full_res(ns, start, item_id, module_id, &None)
1988                             {
1989                                 debug!("found partial_res={:?}", res);
1990                                 *partial_res = Some(res);
1991                                 *unresolved = end.into();
1992                                 break 'outer;
1993                             }
1994                         }
1995                         *unresolved = end.into();
1996                     }
1997
1998                     let last_found_module = match *partial_res {
1999                         Some(Res::Def(DefKind::Mod, id)) => Some(id),
2000                         None => Some(module_id),
2001                         _ => None,
2002                     };
2003                     // See if this was a module: `[path]` or `[std::io::nope]`
2004                     if let Some(module) = last_found_module {
2005                         let note = if partial_res.is_some() {
2006                             // Part of the link resolved; e.g. `std::io::nonexistent`
2007                             let module_name = tcx.item_name(module);
2008                             format!("no item named `{}` in module `{}`", unresolved, module_name)
2009                         } else {
2010                             // None of the link resolved; e.g. `Notimported`
2011                             format!("no item named `{}` in scope", unresolved)
2012                         };
2013                         if let Some(span) = sp {
2014                             diag.span_label(span, &note);
2015                         } else {
2016                             diag.note(&note);
2017                         }
2018
2019                         // If the link has `::` in it, assume it was meant to be an intra-doc link.
2020                         // Otherwise, the `[]` might be unrelated.
2021                         // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
2022                         if !path_str.contains("::") {
2023                             diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
2024                         }
2025
2026                         continue;
2027                     }
2028
2029                     // Otherwise, it must be an associated item or variant
2030                     let res = partial_res.expect("None case was handled by `last_found_module`");
2031                     let name = res.name(tcx);
2032                     let kind = match res {
2033                         Res::Def(kind, _) => Some(kind),
2034                         Res::Primitive(_) => None,
2035                     };
2036                     let path_description = if let Some(kind) = kind {
2037                         match kind {
2038                             Mod | ForeignMod => "inner item",
2039                             Struct => "field or associated item",
2040                             Enum | Union => "variant or associated item",
2041                             Variant
2042                             | Field
2043                             | Closure
2044                             | Generator
2045                             | AssocTy
2046                             | AssocConst
2047                             | AssocFn
2048                             | Fn
2049                             | Macro(_)
2050                             | Const
2051                             | ConstParam
2052                             | ExternCrate
2053                             | Use
2054                             | LifetimeParam
2055                             | Ctor(_, _)
2056                             | AnonConst
2057                             | InlineConst => {
2058                                 let note = assoc_item_not_allowed(res);
2059                                 if let Some(span) = sp {
2060                                     diag.span_label(span, &note);
2061                                 } else {
2062                                     diag.note(&note);
2063                                 }
2064                                 return;
2065                             }
2066                             Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
2067                             | Static(_) => "associated item",
2068                             Impl | GlobalAsm => unreachable!("not a path"),
2069                         }
2070                     } else {
2071                         "associated item"
2072                     };
2073                     let note = format!(
2074                         "the {} `{}` has no {} named `{}`",
2075                         res.descr(),
2076                         name,
2077                         disambiguator.map_or(path_description, |d| d.descr()),
2078                         unresolved,
2079                     );
2080                     if let Some(span) = sp {
2081                         diag.span_label(span, &note);
2082                     } else {
2083                         diag.note(&note);
2084                     }
2085
2086                     continue;
2087                 }
2088                 let note = match failure {
2089                     ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2090                     ResolutionFailure::Dummy => continue,
2091                     ResolutionFailure::WrongNamespace { res, expected_ns } => {
2092                         suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2093
2094                         format!(
2095                             "this link resolves to {}, which is not in the {} namespace",
2096                             item(res),
2097                             expected_ns.descr()
2098                         )
2099                     }
2100                     ResolutionFailure::NoParentItem => {
2101                         // FIXME(eddyb) this doesn't belong here, whatever made
2102                         // the `ResolutionFailure::NoParentItem` should emit an
2103                         // immediate or delayed `span_bug` about the issue.
2104                         tcx.sess.delay_span_bug(
2105                             sp.unwrap_or(DUMMY_SP),
2106                             "intra-doc link missing parent item",
2107                         );
2108
2109                         "BUG: all intra-doc links should have a parent item".to_owned()
2110                     }
2111                     ResolutionFailure::MalformedGenerics(variant) => match variant {
2112                         MalformedGenerics::UnbalancedAngleBrackets => {
2113                             String::from("unbalanced angle brackets")
2114                         }
2115                         MalformedGenerics::MissingType => {
2116                             String::from("missing type for generic parameters")
2117                         }
2118                         MalformedGenerics::HasFullyQualifiedSyntax => {
2119                             diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2120                             String::from("fully-qualified syntax is unsupported")
2121                         }
2122                         MalformedGenerics::InvalidPathSeparator => {
2123                             String::from("has invalid path separator")
2124                         }
2125                         MalformedGenerics::TooManyAngleBrackets => {
2126                             String::from("too many angle brackets")
2127                         }
2128                         MalformedGenerics::EmptyAngleBrackets => {
2129                             String::from("empty angle brackets")
2130                         }
2131                     },
2132                 };
2133                 if let Some(span) = sp {
2134                     diag.span_label(span, &note);
2135                 } else {
2136                     diag.note(&note);
2137                 }
2138             }
2139         },
2140     );
2141 }
2142
2143 /// Report an anchor failure.
2144 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2145     let (msg, anchor_idx) = match failure {
2146         AnchorFailure::MultipleAnchors => {
2147             (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2148         }
2149         AnchorFailure::RustdocAnchorConflict(res) => (
2150             format!(
2151                 "`{}` contains an anchor, but links to {kind}s are already anchored",
2152                 diag_info.ori_link,
2153                 kind = res.descr(),
2154             ),
2155             0,
2156         ),
2157     };
2158
2159     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2160         if let Some(mut sp) = sp {
2161             if let Some((fragment_offset, _)) =
2162                 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2163             {
2164                 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2165             }
2166             diag.span_label(sp, "invalid anchor");
2167         }
2168         if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2169             if let Some(sp) = sp {
2170                 span_bug!(sp, "anchors should be allowed now");
2171             } else {
2172                 bug!("anchors should be allowed now");
2173             }
2174         }
2175     });
2176 }
2177
2178 /// Report an error in the link disambiguator.
2179 fn disambiguator_error(
2180     cx: &DocContext<'_>,
2181     mut diag_info: DiagnosticInfo<'_>,
2182     disambiguator_range: Range<usize>,
2183     msg: &str,
2184 ) {
2185     diag_info.link_range = disambiguator_range;
2186     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2187         let msg = format!(
2188             "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2189             crate::DOC_RUST_LANG_ORG_CHANNEL
2190         );
2191         diag.note(&msg);
2192     });
2193 }
2194
2195 /// Report an ambiguity error, where there were multiple possible resolutions.
2196 fn ambiguity_error(
2197     cx: &DocContext<'_>,
2198     diag_info: DiagnosticInfo<'_>,
2199     path_str: &str,
2200     candidates: Vec<Res>,
2201 ) {
2202     let mut msg = format!("`{}` is ", path_str);
2203
2204     match candidates.as_slice() {
2205         [first_def, second_def] => {
2206             msg += &format!(
2207                 "both {} {} and {} {}",
2208                 first_def.article(),
2209                 first_def.descr(),
2210                 second_def.article(),
2211                 second_def.descr(),
2212             );
2213         }
2214         _ => {
2215             let mut candidates = candidates.iter().peekable();
2216             while let Some(res) = candidates.next() {
2217                 if candidates.peek().is_some() {
2218                     msg += &format!("{} {}, ", res.article(), res.descr());
2219                 } else {
2220                     msg += &format!("and {} {}", res.article(), res.descr());
2221                 }
2222             }
2223         }
2224     }
2225
2226     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2227         if let Some(sp) = sp {
2228             diag.span_label(sp, "ambiguous link");
2229         } else {
2230             diag.note("ambiguous link");
2231         }
2232
2233         for res in candidates {
2234             suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2235         }
2236     });
2237 }
2238
2239 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2240 /// disambiguator.
2241 fn suggest_disambiguator(
2242     res: Res,
2243     diag: &mut Diagnostic,
2244     path_str: &str,
2245     ori_link: &str,
2246     sp: Option<rustc_span::Span>,
2247 ) {
2248     let suggestion = res.disambiguator_suggestion();
2249     let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2250
2251     if let Some(sp) = sp {
2252         let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2253         if spans.len() > 1 {
2254             diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2255         } else {
2256             let (sp, suggestion_text) = spans.pop().unwrap();
2257             diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2258         }
2259     } else {
2260         diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2261     }
2262 }
2263
2264 /// Report a link from a public item to a private one.
2265 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2266     let sym;
2267     let item_name = match diag_info.item.name {
2268         Some(name) => {
2269             sym = name;
2270             sym.as_str()
2271         }
2272         None => "<unknown>",
2273     };
2274     let msg =
2275         format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2276
2277     report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2278         if let Some(sp) = sp {
2279             diag.span_label(sp, "this item is private");
2280         }
2281
2282         let note_msg = if cx.render_options.document_private {
2283             "this link resolves only because you passed `--document-private-items`, but will break without"
2284         } else {
2285             "this link will resolve properly if you pass `--document-private-items`"
2286         };
2287         diag.note(note_msg);
2288     });
2289 }
2290
2291 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2292 fn handle_variant(
2293     cx: &DocContext<'_>,
2294     res: Res,
2295 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'static>> {
2296     cx.tcx
2297         .parent(res.def_id(cx.tcx))
2298         .map(|parent| {
2299             let parent_def = Res::Def(DefKind::Enum, parent);
2300             let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2301             (parent_def, Some(ItemFragment(FragmentKind::Variant, variant.def_id)))
2302         })
2303         .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2304 }
2305
2306 /// Resolve a primitive type or value.
2307 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2308     if ns != TypeNS {
2309         return None;
2310     }
2311     use PrimitiveType::*;
2312     let prim = match path_str {
2313         "isize" => Isize,
2314         "i8" => I8,
2315         "i16" => I16,
2316         "i32" => I32,
2317         "i64" => I64,
2318         "i128" => I128,
2319         "usize" => Usize,
2320         "u8" => U8,
2321         "u16" => U16,
2322         "u32" => U32,
2323         "u64" => U64,
2324         "u128" => U128,
2325         "f32" => F32,
2326         "f64" => F64,
2327         "char" => Char,
2328         "bool" | "true" | "false" => Bool,
2329         "str" | "&str" => Str,
2330         // See #80181 for why these don't have symbols associated.
2331         "slice" => Slice,
2332         "array" => Array,
2333         "tuple" => Tuple,
2334         "unit" => Unit,
2335         "pointer" | "*const" | "*mut" => RawPointer,
2336         "reference" | "&" | "&mut" => Reference,
2337         "fn" => Fn,
2338         "never" | "!" => Never,
2339         _ => return None,
2340     };
2341     debug!("resolved primitives {:?}", prim);
2342     Some(Res::Primitive(prim))
2343 }
2344
2345 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2346     let mut stripped_segments = vec![];
2347     let mut path = path_str.chars().peekable();
2348     let mut segment = Vec::new();
2349
2350     while let Some(chr) = path.next() {
2351         match chr {
2352             ':' => {
2353                 if path.next_if_eq(&':').is_some() {
2354                     let stripped_segment =
2355                         strip_generics_from_path_segment(mem::take(&mut segment))?;
2356                     if !stripped_segment.is_empty() {
2357                         stripped_segments.push(stripped_segment);
2358                     }
2359                 } else {
2360                     return Err(ResolutionFailure::MalformedGenerics(
2361                         MalformedGenerics::InvalidPathSeparator,
2362                     ));
2363                 }
2364             }
2365             '<' => {
2366                 segment.push(chr);
2367
2368                 match path.next() {
2369                     Some('<') => {
2370                         return Err(ResolutionFailure::MalformedGenerics(
2371                             MalformedGenerics::TooManyAngleBrackets,
2372                         ));
2373                     }
2374                     Some('>') => {
2375                         return Err(ResolutionFailure::MalformedGenerics(
2376                             MalformedGenerics::EmptyAngleBrackets,
2377                         ));
2378                     }
2379                     Some(chr) => {
2380                         segment.push(chr);
2381
2382                         while let Some(chr) = path.next_if(|c| *c != '>') {
2383                             segment.push(chr);
2384                         }
2385                     }
2386                     None => break,
2387                 }
2388             }
2389             _ => segment.push(chr),
2390         }
2391         trace!("raw segment: {:?}", segment);
2392     }
2393
2394     if !segment.is_empty() {
2395         let stripped_segment = strip_generics_from_path_segment(segment)?;
2396         if !stripped_segment.is_empty() {
2397             stripped_segments.push(stripped_segment);
2398         }
2399     }
2400
2401     debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2402
2403     let stripped_path = stripped_segments.join("::");
2404
2405     if !stripped_path.is_empty() {
2406         Ok(stripped_path)
2407     } else {
2408         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2409     }
2410 }
2411
2412 fn strip_generics_from_path_segment(
2413     segment: Vec<char>,
2414 ) -> Result<String, ResolutionFailure<'static>> {
2415     let mut stripped_segment = String::new();
2416     let mut param_depth = 0;
2417
2418     let mut latest_generics_chunk = String::new();
2419
2420     for c in segment {
2421         if c == '<' {
2422             param_depth += 1;
2423             latest_generics_chunk.clear();
2424         } else if c == '>' {
2425             param_depth -= 1;
2426             if latest_generics_chunk.contains(" as ") {
2427                 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2428                 // Give a helpful error message instead of completely ignoring the angle brackets.
2429                 return Err(ResolutionFailure::MalformedGenerics(
2430                     MalformedGenerics::HasFullyQualifiedSyntax,
2431                 ));
2432             }
2433         } else {
2434             if param_depth == 0 {
2435                 stripped_segment.push(c);
2436             } else {
2437                 latest_generics_chunk.push(c);
2438             }
2439         }
2440     }
2441
2442     if param_depth == 0 {
2443         Ok(stripped_segment)
2444     } else {
2445         // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2446         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))
2447     }
2448 }