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