]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_intra_doc_links.rs
Auto merge of #93081 - nikic:aarch64-fix, r=cuviper
[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;
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.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 tcx = cx.tcx;
929     let iter = cx.resolver_caches.traits_in_scope[&module].iter().flat_map(|trait_candidate| {
930         let trait_ = trait_candidate.def_id;
931         trace!("considering explicit impl for trait {:?}", trait_);
932
933         // Look at each trait implementation to see if it's an impl for `did`
934         tcx.find_map_relevant_impl(trait_, ty, |impl_| {
935             let trait_ref = tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
936             // Check if these are the same type.
937             let impl_type = trait_ref.self_ty();
938             trace!(
939                 "comparing type {} with kind {:?} against type {:?}",
940                 impl_type,
941                 impl_type.kind(),
942                 ty
943             );
944             // Fast path: if this is a primitive simple `==` will work
945             // NOTE: the `match` is necessary; see #92662.
946             // this allows us to ignore generics because the user input
947             // may not include the generic placeholders
948             // e.g. this allows us to match Foo (user comment) with Foo<T> (actual type)
949             let saw_impl = impl_type == ty
950                 || match (impl_type.kind(), ty.kind()) {
951                     (ty::Adt(impl_def, _), ty::Adt(ty_def, _)) => {
952                         debug!("impl def_id: {:?}, ty def_id: {:?}", impl_def.did, ty_def.did);
953                         impl_def.did == ty_def.did
954                     }
955                     _ => false,
956                 };
957
958             if saw_impl { Some((impl_, trait_)) } else { None }
959         })
960     });
961     iter.collect()
962 }
963
964 /// Check for resolve collisions between a trait and its derive.
965 ///
966 /// These are common and we should just resolve to the trait in that case.
967 fn is_derive_trait_collision<T>(ns: &PerNS<Result<(Res, T), ResolutionFailure<'_>>>) -> bool {
968     matches!(
969         *ns,
970         PerNS {
971             type_ns: Ok((Res::Def(DefKind::Trait, _), _)),
972             macro_ns: Ok((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
973             ..
974         }
975     )
976 }
977
978 impl<'a, 'tcx> DocVisitor for LinkCollector<'a, 'tcx> {
979     fn visit_item(&mut self, item: &Item) {
980         let parent_node =
981             item.def_id.as_def_id().and_then(|did| find_nearest_parent_module(self.cx.tcx, did));
982         if parent_node.is_some() {
983             trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
984         }
985
986         // find item's parent to resolve `Self` in item's docs below
987         debug!("looking for the `Self` type");
988         let self_id = match item.def_id.as_def_id() {
989             None => None,
990             Some(did)
991                 if (matches!(self.cx.tcx.def_kind(did), DefKind::Field)
992                     && matches!(
993                         self.cx.tcx.def_kind(self.cx.tcx.parent(did).unwrap()),
994                         DefKind::Variant
995                     )) =>
996             {
997                 self.cx.tcx.parent(did).and_then(|item_id| self.cx.tcx.parent(item_id))
998             }
999             Some(did)
1000                 if matches!(
1001                     self.cx.tcx.def_kind(did),
1002                     DefKind::AssocConst
1003                         | DefKind::AssocFn
1004                         | DefKind::AssocTy
1005                         | DefKind::Variant
1006                         | DefKind::Field
1007                 ) =>
1008             {
1009                 self.cx.tcx.parent(did)
1010             }
1011             Some(did) => Some(did),
1012         };
1013
1014         // FIXME(jynelson): this shouldn't go through stringification, rustdoc should just use the DefId directly
1015         let self_name = self_id.and_then(|self_id| {
1016             if matches!(self.cx.tcx.def_kind(self_id), DefKind::Impl) {
1017                 // using `ty.to_string()` (or any variant) has issues with raw idents
1018                 let ty = self.cx.tcx.type_of(self_id);
1019                 let name = match ty.kind() {
1020                     ty::Adt(def, _) => Some(self.cx.tcx.item_name(def.did).to_string()),
1021                     other if other.is_primitive() => Some(ty.to_string()),
1022                     _ => None,
1023                 };
1024                 debug!("using type_of(): {:?}", name);
1025                 name
1026             } else {
1027                 let name = self.cx.tcx.opt_item_name(self_id).map(|sym| sym.to_string());
1028                 debug!("using item_name(): {:?}", name);
1029                 name
1030             }
1031         });
1032
1033         let inner_docs = item.inner_docs(self.cx.tcx);
1034
1035         if item.is_mod() && inner_docs {
1036             self.mod_ids.push(item.def_id.expect_def_id());
1037         }
1038
1039         // We want to resolve in the lexical scope of the documentation.
1040         // In the presence of re-exports, this is not the same as the module of the item.
1041         // Rather than merging all documentation into one, resolve it one attribute at a time
1042         // so we know which module it came from.
1043         for (parent_module, doc) in item.attrs.collapsed_doc_value_by_module_level() {
1044             debug!("combined_docs={}", doc);
1045
1046             let (krate, parent_node) = if let Some(id) = parent_module {
1047                 (id.krate, Some(id))
1048             } else {
1049                 (item.def_id.krate(), parent_node)
1050             };
1051             // NOTE: if there are links that start in one crate and end in another, this will not resolve them.
1052             // This is a degenerate case and it's not supported by rustdoc.
1053             for md_link in markdown_links(&doc) {
1054                 let link = self.resolve_link(&item, &doc, &self_name, parent_node, krate, md_link);
1055                 if let Some(link) = link {
1056                     self.cx.cache.intra_doc_links.entry(item.def_id).or_default().push(link);
1057                 }
1058             }
1059         }
1060
1061         if item.is_mod() {
1062             if !inner_docs {
1063                 self.mod_ids.push(item.def_id.expect_def_id());
1064             }
1065
1066             self.visit_item_recur(item);
1067             self.mod_ids.pop();
1068         } else {
1069             self.visit_item_recur(item)
1070         }
1071     }
1072 }
1073
1074 enum PreprocessingError<'a> {
1075     Anchor(AnchorFailure),
1076     Disambiguator(Range<usize>, String),
1077     Resolution(ResolutionFailure<'a>, String, Option<Disambiguator>),
1078 }
1079
1080 impl From<AnchorFailure> for PreprocessingError<'_> {
1081     fn from(err: AnchorFailure) -> Self {
1082         Self::Anchor(err)
1083     }
1084 }
1085
1086 struct PreprocessingInfo {
1087     path_str: String,
1088     disambiguator: Option<Disambiguator>,
1089     extra_fragment: Option<String>,
1090     link_text: String,
1091 }
1092
1093 /// Returns:
1094 /// - `None` if the link should be ignored.
1095 /// - `Some(Err)` if the link should emit an error
1096 /// - `Some(Ok)` if the link is valid
1097 ///
1098 /// `link_buffer` is needed for lifetime reasons; it will always be overwritten and the contents ignored.
1099 fn preprocess_link<'a>(
1100     ori_link: &'a MarkdownLink,
1101 ) -> Option<Result<PreprocessingInfo, PreprocessingError<'a>>> {
1102     // [] is mostly likely not supposed to be a link
1103     if ori_link.link.is_empty() {
1104         return None;
1105     }
1106
1107     // Bail early for real links.
1108     if ori_link.link.contains('/') {
1109         return None;
1110     }
1111
1112     let stripped = ori_link.link.replace('`', "");
1113     let mut parts = stripped.split('#');
1114
1115     let link = parts.next().unwrap();
1116     if link.trim().is_empty() {
1117         // This is an anchor to an element of the current page, nothing to do in here!
1118         return None;
1119     }
1120     let extra_fragment = parts.next();
1121     if parts.next().is_some() {
1122         // A valid link can't have multiple #'s
1123         return Some(Err(AnchorFailure::MultipleAnchors.into()));
1124     }
1125
1126     // Parse and strip the disambiguator from the link, if present.
1127     let (disambiguator, path_str, link_text) = match Disambiguator::from_str(link) {
1128         Ok(Some((d, path, link_text))) => (Some(d), path.trim(), link_text.trim()),
1129         Ok(None) => (None, link.trim(), link.trim()),
1130         Err((err_msg, relative_range)) => {
1131             // Only report error if we would not have ignored this link. See issue #83859.
1132             if !should_ignore_link_with_disambiguators(link) {
1133                 let no_backticks_range = range_between_backticks(ori_link);
1134                 let disambiguator_range = (no_backticks_range.start + relative_range.start)
1135                     ..(no_backticks_range.start + relative_range.end);
1136                 return Some(Err(PreprocessingError::Disambiguator(disambiguator_range, err_msg)));
1137             } else {
1138                 return None;
1139             }
1140         }
1141     };
1142
1143     if should_ignore_link(path_str) {
1144         return None;
1145     }
1146
1147     // Strip generics from the path.
1148     let path_str = if path_str.contains(['<', '>'].as_slice()) {
1149         match strip_generics_from_path(path_str) {
1150             Ok(path) => path,
1151             Err(err_kind) => {
1152                 debug!("link has malformed generics: {}", path_str);
1153                 return Some(Err(PreprocessingError::Resolution(
1154                     err_kind,
1155                     path_str.to_owned(),
1156                     disambiguator,
1157                 )));
1158             }
1159         }
1160     } else {
1161         path_str.to_owned()
1162     };
1163
1164     // Sanity check to make sure we don't have any angle brackets after stripping generics.
1165     assert!(!path_str.contains(['<', '>'].as_slice()));
1166
1167     // The link is not an intra-doc link if it still contains spaces after stripping generics.
1168     if path_str.contains(' ') {
1169         return None;
1170     }
1171
1172     Some(Ok(PreprocessingInfo {
1173         path_str,
1174         disambiguator,
1175         extra_fragment: extra_fragment.map(|frag| frag.to_owned()),
1176         link_text: link_text.to_owned(),
1177     }))
1178 }
1179
1180 impl LinkCollector<'_, '_> {
1181     /// This is the entry point for resolving an intra-doc link.
1182     ///
1183     /// FIXME(jynelson): this is way too many arguments
1184     fn resolve_link(
1185         &mut self,
1186         item: &Item,
1187         dox: &str,
1188         self_name: &Option<String>,
1189         parent_node: Option<DefId>,
1190         krate: CrateNum,
1191         ori_link: MarkdownLink,
1192     ) -> Option<ItemLink> {
1193         trace!("considering link '{}'", ori_link.link);
1194
1195         let diag_info = DiagnosticInfo {
1196             item,
1197             dox,
1198             ori_link: &ori_link.link,
1199             link_range: ori_link.range.clone(),
1200         };
1201
1202         let PreprocessingInfo { path_str, disambiguator, extra_fragment, link_text } =
1203             match preprocess_link(&ori_link)? {
1204                 Ok(x) => x,
1205                 Err(err) => {
1206                     match err {
1207                         PreprocessingError::Anchor(err) => anchor_failure(self.cx, diag_info, err),
1208                         PreprocessingError::Disambiguator(range, msg) => {
1209                             disambiguator_error(self.cx, diag_info, range, &msg)
1210                         }
1211                         PreprocessingError::Resolution(err, path_str, disambiguator) => {
1212                             resolution_failure(
1213                                 self,
1214                                 diag_info,
1215                                 &path_str,
1216                                 disambiguator,
1217                                 smallvec![err],
1218                             );
1219                         }
1220                     }
1221                     return None;
1222                 }
1223             };
1224         let mut path_str = &*path_str;
1225
1226         let inner_docs = item.inner_docs(self.cx.tcx);
1227
1228         // In order to correctly resolve intra-doc links we need to
1229         // pick a base AST node to work from.  If the documentation for
1230         // this module came from an inner comment (//!) then we anchor
1231         // our name resolution *inside* the module.  If, on the other
1232         // hand it was an outer comment (///) then we anchor the name
1233         // resolution in the parent module on the basis that the names
1234         // used are more likely to be intended to be parent names.  For
1235         // this, we set base_node to None for inner comments since
1236         // we've already pushed this node onto the resolution stack but
1237         // for outer comments we explicitly try and resolve against the
1238         // parent_node first.
1239         let base_node =
1240             if item.is_mod() && inner_docs { self.mod_ids.last().copied() } else { parent_node };
1241
1242         let mut module_id = if let Some(id) = base_node {
1243             id
1244         } else {
1245             // This is a bug.
1246             debug!("attempting to resolve item without parent module: {}", path_str);
1247             resolution_failure(
1248                 self,
1249                 diag_info,
1250                 path_str,
1251                 disambiguator,
1252                 smallvec![ResolutionFailure::NoParentItem],
1253             );
1254             return None;
1255         };
1256
1257         let resolved_self;
1258         // replace `Self` with suitable item's parent name
1259         let is_lone_self = path_str == "Self";
1260         let is_lone_crate = path_str == "crate";
1261         if path_str.starts_with("Self::") || is_lone_self {
1262             if let Some(ref name) = self_name {
1263                 if is_lone_self {
1264                     path_str = name;
1265                 } else {
1266                     resolved_self = format!("{}::{}", name, &path_str[6..]);
1267                     path_str = &resolved_self;
1268                 }
1269             }
1270         } else if path_str.starts_with("crate::") || is_lone_crate {
1271             use rustc_span::def_id::CRATE_DEF_INDEX;
1272
1273             // HACK(jynelson): rustc_resolve thinks that `crate` is the crate currently being documented.
1274             // But rustdoc wants it to mean the crate this item was originally present in.
1275             // To work around this, remove it and resolve relative to the crate root instead.
1276             // HACK(jynelson)(2): If we just strip `crate::` then suddenly primitives become ambiguous
1277             // (consider `crate::char`). Instead, change it to `self::`. This works because 'self' is now the crate root.
1278             // FIXME(#78696): This doesn't always work.
1279             if is_lone_crate {
1280                 path_str = "self";
1281             } else {
1282                 resolved_self = format!("self::{}", &path_str["crate::".len()..]);
1283                 path_str = &resolved_self;
1284             }
1285             module_id = DefId { krate, index: CRATE_DEF_INDEX };
1286         }
1287
1288         let (mut res, fragment) = self.resolve_with_disambiguator_cached(
1289             ResolutionInfo {
1290                 module_id,
1291                 dis: disambiguator,
1292                 path_str: path_str.to_owned(),
1293                 extra_fragment,
1294             },
1295             diag_info.clone(), // this struct should really be Copy, but Range is not :(
1296             matches!(ori_link.kind, LinkType::Reference | LinkType::Shortcut),
1297         )?;
1298
1299         // Check for a primitive which might conflict with a module
1300         // Report the ambiguity and require that the user specify which one they meant.
1301         // FIXME: could there ever be a primitive not in the type namespace?
1302         if matches!(
1303             disambiguator,
1304             None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
1305         ) && !matches!(res, Res::Primitive(_))
1306         {
1307             if let Some(prim) = resolve_primitive(path_str, TypeNS) {
1308                 // `prim@char`
1309                 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
1310                     res = prim;
1311                 } else {
1312                     // `[char]` when a `char` module is in scope
1313                     let candidates = vec![res, prim];
1314                     ambiguity_error(self.cx, diag_info, path_str, candidates);
1315                     return None;
1316                 }
1317             }
1318         }
1319
1320         match res {
1321             Res::Primitive(prim) => {
1322                 if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1323                     // We're actually resolving an associated item of a primitive, so we need to
1324                     // verify the disambiguator (if any) matches the type of the associated item.
1325                     // This case should really follow the same flow as the `Res::Def` branch below,
1326                     // but attempting to add a call to `clean::register_res` causes an ICE. @jyn514
1327                     // thinks `register_res` is only needed for cross-crate re-exports, but Rust
1328                     // doesn't allow statements like `use str::trim;`, making this a (hopefully)
1329                     // valid omission. See https://github.com/rust-lang/rust/pull/80660#discussion_r551585677
1330                     // for discussion on the matter.
1331                     let kind = self.cx.tcx.def_kind(id);
1332                     self.verify_disambiguator(
1333                         path_str,
1334                         &ori_link,
1335                         kind,
1336                         id,
1337                         disambiguator,
1338                         item,
1339                         &diag_info,
1340                     )?;
1341
1342                     // FIXME: it would be nice to check that the feature gate was enabled in the original crate, not just ignore it altogether.
1343                     // However I'm not sure how to check that across crates.
1344                     if prim == PrimitiveType::RawPointer
1345                         && item.def_id.is_local()
1346                         && !self.cx.tcx.features().intra_doc_pointers
1347                     {
1348                         self.report_rawptr_assoc_feature_gate(dox, &ori_link, item);
1349                     }
1350                 } else {
1351                     match disambiguator {
1352                         Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {}
1353                         Some(other) => {
1354                             self.report_disambiguator_mismatch(
1355                                 path_str, &ori_link, other, res, &diag_info,
1356                             );
1357                             return None;
1358                         }
1359                     }
1360                 }
1361
1362                 Some(ItemLink {
1363                     link: ori_link.link,
1364                     link_text,
1365                     did: res.def_id(self.cx.tcx),
1366                     fragment,
1367                 })
1368             }
1369             Res::Def(kind, id) => {
1370                 let (kind_for_dis, id_for_dis) =
1371                     if let Some(UrlFragment::Item(ItemFragment(_, id))) = fragment {
1372                         (self.cx.tcx.def_kind(id), id)
1373                     } else {
1374                         (kind, id)
1375                     };
1376                 self.verify_disambiguator(
1377                     path_str,
1378                     &ori_link,
1379                     kind_for_dis,
1380                     id_for_dis,
1381                     disambiguator,
1382                     item,
1383                     &diag_info,
1384                 )?;
1385                 let id = clean::register_res(self.cx, rustc_hir::def::Res::Def(kind, id));
1386                 Some(ItemLink { link: ori_link.link, link_text, did: id, fragment })
1387             }
1388         }
1389     }
1390
1391     fn verify_disambiguator(
1392         &self,
1393         path_str: &str,
1394         ori_link: &MarkdownLink,
1395         kind: DefKind,
1396         id: DefId,
1397         disambiguator: Option<Disambiguator>,
1398         item: &Item,
1399         diag_info: &DiagnosticInfo<'_>,
1400     ) -> Option<()> {
1401         debug!("intra-doc link to {} resolved to {:?}", path_str, (kind, id));
1402
1403         // Disallow e.g. linking to enums with `struct@`
1404         debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
1405         match (kind, disambiguator) {
1406                 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
1407                 // NOTE: this allows 'method' to mean both normal functions and associated functions
1408                 // This can't cause ambiguity because both are in the same namespace.
1409                 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
1410                 // These are namespaces; allow anything in the namespace to match
1411                 | (_, Some(Disambiguator::Namespace(_)))
1412                 // If no disambiguator given, allow anything
1413                 | (_, None)
1414                 // All of these are valid, so do nothing
1415                 => {}
1416                 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
1417                 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
1418                     self.report_disambiguator_mismatch(path_str,ori_link,specified, Res::Def(kind, id),diag_info);
1419                     return None;
1420                 }
1421             }
1422
1423         // item can be non-local e.g. when using #[doc(primitive = "pointer")]
1424         if let Some((src_id, dst_id)) = id
1425             .as_local()
1426             // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
1427             // would presumably panic if a fake `DefIndex` were passed.
1428             .and_then(|dst_id| {
1429                 item.def_id.expect_def_id().as_local().map(|src_id| (src_id, dst_id))
1430             })
1431         {
1432             if self.cx.tcx.privacy_access_levels(()).is_exported(src_id)
1433                 && !self.cx.tcx.privacy_access_levels(()).is_exported(dst_id)
1434             {
1435                 privacy_error(self.cx, diag_info, path_str);
1436             }
1437         }
1438
1439         Some(())
1440     }
1441
1442     fn report_disambiguator_mismatch(
1443         &self,
1444         path_str: &str,
1445         ori_link: &MarkdownLink,
1446         specified: Disambiguator,
1447         resolved: Res,
1448         diag_info: &DiagnosticInfo<'_>,
1449     ) {
1450         // The resolved item did not match the disambiguator; give a better error than 'not found'
1451         let msg = format!("incompatible link kind for `{}`", path_str);
1452         let callback = |diag: &mut DiagnosticBuilder<'_>, sp: Option<rustc_span::Span>| {
1453             let note = format!(
1454                 "this link resolved to {} {}, which is not {} {}",
1455                 resolved.article(),
1456                 resolved.descr(),
1457                 specified.article(),
1458                 specified.descr(),
1459             );
1460             if let Some(sp) = sp {
1461                 diag.span_label(sp, &note);
1462             } else {
1463                 diag.note(&note);
1464             }
1465             suggest_disambiguator(resolved, diag, path_str, &ori_link.link, sp);
1466         };
1467         report_diagnostic(self.cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, callback);
1468     }
1469
1470     fn report_rawptr_assoc_feature_gate(&self, dox: &str, ori_link: &MarkdownLink, item: &Item) {
1471         let span =
1472             super::source_span_for_markdown_range(self.cx.tcx, dox, &ori_link.range, &item.attrs)
1473                 .unwrap_or_else(|| item.attr_span(self.cx.tcx));
1474         rustc_session::parse::feature_err(
1475             &self.cx.tcx.sess.parse_sess,
1476             sym::intra_doc_pointers,
1477             span,
1478             "linking to associated items of raw pointers is experimental",
1479         )
1480         .note("rustdoc does not allow disambiguating between `*const` and `*mut`, and pointers are unstable until it does")
1481         .emit();
1482     }
1483
1484     fn resolve_with_disambiguator_cached(
1485         &mut self,
1486         key: ResolutionInfo,
1487         diag: DiagnosticInfo<'_>,
1488         cache_resolution_failure: bool,
1489     ) -> Option<(Res, Option<UrlFragment>)> {
1490         if let Some(ref cached) = self.visited_links.get(&key) {
1491             match cached {
1492                 Some(cached) => {
1493                     return Some(cached.res.clone());
1494                 }
1495                 None if cache_resolution_failure => return None,
1496                 None => {
1497                     // Although we hit the cache and found a resolution error, this link isn't
1498                     // supposed to cache those. Run link resolution again to emit the expected
1499                     // resolution error.
1500                 }
1501             }
1502         }
1503
1504         let res = self.resolve_with_disambiguator(&key, diag);
1505
1506         // Cache only if resolved successfully - don't silence duplicate errors
1507         if let Some(res) = res {
1508             // Store result for the actual namespace
1509             self.visited_links.insert(key, Some(CachedLink { res: res.clone() }));
1510
1511             Some(res)
1512         } else {
1513             if cache_resolution_failure {
1514                 // For reference-style links we only want to report one resolution error
1515                 // so let's cache them as well.
1516                 self.visited_links.insert(key, None);
1517             }
1518
1519             None
1520         }
1521     }
1522
1523     /// After parsing the disambiguator, resolve the main part of the link.
1524     // FIXME(jynelson): wow this is just so much
1525     fn resolve_with_disambiguator(
1526         &mut self,
1527         key: &ResolutionInfo,
1528         diag: DiagnosticInfo<'_>,
1529     ) -> Option<(Res, Option<UrlFragment>)> {
1530         let disambiguator = key.dis;
1531         let path_str = &key.path_str;
1532         let base_node = key.module_id;
1533         let extra_fragment = &key.extra_fragment;
1534
1535         match disambiguator.map(Disambiguator::ns) {
1536             Some(expected_ns @ (ValueNS | TypeNS)) => {
1537                 match self.resolve(path_str, expected_ns, base_node, extra_fragment) {
1538                     Ok(res) => Some(res),
1539                     Err(ErrorKind::Resolve(box mut kind)) => {
1540                         // We only looked in one namespace. Try to give a better error if possible.
1541                         if kind.full_res().is_none() {
1542                             let other_ns = if expected_ns == ValueNS { TypeNS } else { ValueNS };
1543                             // FIXME: really it should be `resolution_failure` that does this, not `resolve_with_disambiguator`
1544                             // See https://github.com/rust-lang/rust/pull/76955#discussion_r493953382 for a good approach
1545                             for new_ns in [other_ns, MacroNS] {
1546                                 if let Some(res) =
1547                                     self.check_full_res(new_ns, path_str, base_node, extra_fragment)
1548                                 {
1549                                     kind = ResolutionFailure::WrongNamespace { res, expected_ns };
1550                                     break;
1551                                 }
1552                             }
1553                         }
1554                         resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1555                         // This could just be a normal link or a broken link
1556                         // we could potentially check if something is
1557                         // "intra-doc-link-like" and warn in that case.
1558                         None
1559                     }
1560                     Err(ErrorKind::AnchorFailure(msg)) => {
1561                         anchor_failure(self.cx, diag, msg);
1562                         None
1563                     }
1564                 }
1565             }
1566             None => {
1567                 // Try everything!
1568                 let mut candidates = PerNS {
1569                     macro_ns: self
1570                         .resolve_macro(path_str, base_node)
1571                         .map(|res| (res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1572                     type_ns: match self.resolve(path_str, TypeNS, base_node, extra_fragment) {
1573                         Ok(res) => {
1574                             debug!("got res in TypeNS: {:?}", res);
1575                             Ok(res)
1576                         }
1577                         Err(ErrorKind::AnchorFailure(msg)) => {
1578                             anchor_failure(self.cx, diag, msg);
1579                             return None;
1580                         }
1581                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1582                     },
1583                     value_ns: match self.resolve(path_str, ValueNS, base_node, extra_fragment) {
1584                         Ok(res) => Ok(res),
1585                         Err(ErrorKind::AnchorFailure(msg)) => {
1586                             anchor_failure(self.cx, diag, msg);
1587                             return None;
1588                         }
1589                         Err(ErrorKind::Resolve(box kind)) => Err(kind),
1590                     }
1591                     .and_then(|(res, fragment)| {
1592                         // Constructors are picked up in the type namespace.
1593                         match res {
1594                             Res::Def(DefKind::Ctor(..), _) => {
1595                                 Err(ResolutionFailure::WrongNamespace { res, expected_ns: TypeNS })
1596                             }
1597                             _ => {
1598                                 match (fragment, extra_fragment.clone()) {
1599                                     (Some(fragment), Some(_)) => {
1600                                         // Shouldn't happen but who knows?
1601                                         Ok((res, Some(fragment)))
1602                                     }
1603                                     (fragment, None) => Ok((res, fragment)),
1604                                     (None, fragment) => {
1605                                         Ok((res, fragment.map(UrlFragment::UserWritten)))
1606                                     }
1607                                 }
1608                             }
1609                         }
1610                     }),
1611                 };
1612
1613                 let len = candidates.iter().filter(|res| res.is_ok()).count();
1614
1615                 if len == 0 {
1616                     resolution_failure(
1617                         self,
1618                         diag,
1619                         path_str,
1620                         disambiguator,
1621                         candidates.into_iter().filter_map(|res| res.err()).collect(),
1622                     );
1623                     // this could just be a normal link
1624                     return None;
1625                 }
1626
1627                 if len == 1 {
1628                     Some(candidates.into_iter().find_map(|res| res.ok()).unwrap())
1629                 } else if len == 2 && is_derive_trait_collision(&candidates) {
1630                     Some(candidates.type_ns.unwrap())
1631                 } else {
1632                     if is_derive_trait_collision(&candidates) {
1633                         candidates.macro_ns = Err(ResolutionFailure::Dummy);
1634                     }
1635                     // If we're reporting an ambiguity, don't mention the namespaces that failed
1636                     let candidates = candidates.map(|candidate| candidate.ok().map(|(res, _)| res));
1637                     ambiguity_error(self.cx, diag, path_str, candidates.present_items().collect());
1638                     None
1639                 }
1640             }
1641             Some(MacroNS) => {
1642                 match self.resolve_macro(path_str, base_node) {
1643                     Ok(res) => Some((res, extra_fragment.clone().map(UrlFragment::UserWritten))),
1644                     Err(mut kind) => {
1645                         // `resolve_macro` only looks in the macro namespace. Try to give a better error if possible.
1646                         for ns in [TypeNS, ValueNS] {
1647                             if let Some(res) =
1648                                 self.check_full_res(ns, path_str, base_node, extra_fragment)
1649                             {
1650                                 kind =
1651                                     ResolutionFailure::WrongNamespace { res, expected_ns: MacroNS };
1652                                 break;
1653                             }
1654                         }
1655                         resolution_failure(self, diag, path_str, disambiguator, smallvec![kind]);
1656                         None
1657                     }
1658                 }
1659             }
1660         }
1661     }
1662 }
1663
1664 /// Get the section of a link between the backticks,
1665 /// or the whole link if there aren't any backticks.
1666 ///
1667 /// For example:
1668 ///
1669 /// ```text
1670 /// [`Foo`]
1671 ///   ^^^
1672 /// ```
1673 fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
1674     let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
1675     let before_second_backtick_group = ori_link
1676         .link
1677         .bytes()
1678         .skip(after_first_backtick_group)
1679         .position(|b| b == b'`')
1680         .unwrap_or(ori_link.link.len());
1681     (ori_link.range.start + after_first_backtick_group)
1682         ..(ori_link.range.start + before_second_backtick_group)
1683 }
1684
1685 /// Returns true if we should ignore `link` due to it being unlikely
1686 /// that it is an intra-doc link. `link` should still have disambiguators
1687 /// if there were any.
1688 ///
1689 /// The difference between this and [`should_ignore_link()`] is that this
1690 /// check should only be used on links that still have disambiguators.
1691 fn should_ignore_link_with_disambiguators(link: &str) -> bool {
1692     link.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;@()".contains(ch)))
1693 }
1694
1695 /// Returns true if we should ignore `path_str` due to it being unlikely
1696 /// that it is an intra-doc link.
1697 fn should_ignore_link(path_str: &str) -> bool {
1698     path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch)))
1699 }
1700
1701 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1702 /// Disambiguators for a link.
1703 enum Disambiguator {
1704     /// `prim@`
1705     ///
1706     /// This is buggy, see <https://github.com/rust-lang/rust/pull/77875#discussion_r503583103>
1707     Primitive,
1708     /// `struct@` or `f()`
1709     Kind(DefKind),
1710     /// `type@`
1711     Namespace(Namespace),
1712 }
1713
1714 impl Disambiguator {
1715     /// Given a link, parse and return `(disambiguator, path_str, link_text)`.
1716     ///
1717     /// This returns `Ok(Some(...))` if a disambiguator was found,
1718     /// `Ok(None)` if no disambiguator was found, or `Err(...)`
1719     /// if there was a problem with the disambiguator.
1720     fn from_str(link: &str) -> Result<Option<(Self, &str, &str)>, (String, Range<usize>)> {
1721         use Disambiguator::{Kind, Namespace as NS, Primitive};
1722
1723         if let Some(idx) = link.find('@') {
1724             let (prefix, rest) = link.split_at(idx);
1725             let d = match prefix {
1726                 "struct" => Kind(DefKind::Struct),
1727                 "enum" => Kind(DefKind::Enum),
1728                 "trait" => Kind(DefKind::Trait),
1729                 "union" => Kind(DefKind::Union),
1730                 "module" | "mod" => Kind(DefKind::Mod),
1731                 "const" | "constant" => Kind(DefKind::Const),
1732                 "static" => Kind(DefKind::Static),
1733                 "function" | "fn" | "method" => Kind(DefKind::Fn),
1734                 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1735                 "type" => NS(Namespace::TypeNS),
1736                 "value" => NS(Namespace::ValueNS),
1737                 "macro" => NS(Namespace::MacroNS),
1738                 "prim" | "primitive" => Primitive,
1739                 _ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
1740             };
1741             Ok(Some((d, &rest[1..], &rest[1..])))
1742         } else {
1743             let suffixes = [
1744                 ("!()", DefKind::Macro(MacroKind::Bang)),
1745                 ("!{}", DefKind::Macro(MacroKind::Bang)),
1746                 ("![]", DefKind::Macro(MacroKind::Bang)),
1747                 ("()", DefKind::Fn),
1748                 ("!", DefKind::Macro(MacroKind::Bang)),
1749             ];
1750             for (suffix, kind) in suffixes {
1751                 if let Some(path_str) = link.strip_suffix(suffix) {
1752                     // Avoid turning `!` or `()` into an empty string
1753                     if !path_str.is_empty() {
1754                         return Ok(Some((Kind(kind), path_str, link)));
1755                     }
1756                 }
1757             }
1758             Ok(None)
1759         }
1760     }
1761
1762     fn ns(self) -> Namespace {
1763         match self {
1764             Self::Namespace(n) => n,
1765             Self::Kind(k) => {
1766                 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1767             }
1768             Self::Primitive => TypeNS,
1769         }
1770     }
1771
1772     fn article(self) -> &'static str {
1773         match self {
1774             Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1775             Self::Kind(k) => k.article(),
1776             Self::Primitive => "a",
1777         }
1778     }
1779
1780     fn descr(self) -> &'static str {
1781         match self {
1782             Self::Namespace(n) => n.descr(),
1783             // HACK(jynelson): the source of `DefKind::descr` only uses the DefId for
1784             // printing "module" vs "crate" so using the wrong ID is not a huge problem
1785             Self::Kind(k) => k.descr(CRATE_DEF_ID.to_def_id()),
1786             Self::Primitive => "builtin type",
1787         }
1788     }
1789 }
1790
1791 /// A suggestion to show in a diagnostic.
1792 enum Suggestion {
1793     /// `struct@`
1794     Prefix(&'static str),
1795     /// `f()`
1796     Function,
1797     /// `m!`
1798     Macro,
1799     /// `foo` without any disambiguator
1800     RemoveDisambiguator,
1801 }
1802
1803 impl Suggestion {
1804     fn descr(&self) -> Cow<'static, str> {
1805         match self {
1806             Self::Prefix(x) => format!("prefix with `{}@`", x).into(),
1807             Self::Function => "add parentheses".into(),
1808             Self::Macro => "add an exclamation mark".into(),
1809             Self::RemoveDisambiguator => "remove the disambiguator".into(),
1810         }
1811     }
1812
1813     fn as_help(&self, path_str: &str) -> String {
1814         // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1815         match self {
1816             Self::Prefix(prefix) => format!("{}@{}", prefix, path_str),
1817             Self::Function => format!("{}()", path_str),
1818             Self::Macro => format!("{}!", path_str),
1819             Self::RemoveDisambiguator => path_str.into(),
1820         }
1821     }
1822
1823     fn as_help_span(
1824         &self,
1825         path_str: &str,
1826         ori_link: &str,
1827         sp: rustc_span::Span,
1828     ) -> Vec<(rustc_span::Span, String)> {
1829         let inner_sp = match ori_link.find('(') {
1830             Some(index) => sp.with_hi(sp.lo() + BytePos(index as _)),
1831             None => sp,
1832         };
1833         let inner_sp = match ori_link.find('!') {
1834             Some(index) => inner_sp.with_hi(inner_sp.lo() + BytePos(index as _)),
1835             None => inner_sp,
1836         };
1837         let inner_sp = match ori_link.find('@') {
1838             Some(index) => inner_sp.with_lo(inner_sp.lo() + BytePos(index as u32 + 1)),
1839             None => inner_sp,
1840         };
1841         match self {
1842             Self::Prefix(prefix) => {
1843                 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1844                 let mut sugg = vec![(sp.with_hi(inner_sp.lo()), format!("{}@", prefix))];
1845                 if sp.hi() != inner_sp.hi() {
1846                     sugg.push((inner_sp.shrink_to_hi().with_hi(sp.hi()), String::new()));
1847                 }
1848                 sugg
1849             }
1850             Self::Function => {
1851                 let mut sugg = vec![(inner_sp.shrink_to_hi().with_hi(sp.hi()), "()".to_string())];
1852                 if sp.lo() != inner_sp.lo() {
1853                     sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1854                 }
1855                 sugg
1856             }
1857             Self::Macro => {
1858                 let mut sugg = vec![(inner_sp.shrink_to_hi(), "!".to_string())];
1859                 if sp.lo() != inner_sp.lo() {
1860                     sugg.push((inner_sp.shrink_to_lo().with_lo(sp.lo()), String::new()));
1861                 }
1862                 sugg
1863             }
1864             Self::RemoveDisambiguator => vec![(sp, path_str.into())],
1865         }
1866     }
1867 }
1868
1869 /// Reports a diagnostic for an intra-doc link.
1870 ///
1871 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1872 /// the entire documentation block is used for the lint. If a range is provided but the span
1873 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1874 ///
1875 /// The `decorate` callback is invoked in all cases to allow further customization of the
1876 /// diagnostic before emission. If the span of the link was able to be determined, the second
1877 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1878 /// to it.
1879 fn report_diagnostic(
1880     tcx: TyCtxt<'_>,
1881     lint: &'static Lint,
1882     msg: &str,
1883     DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>,
1884     decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1885 ) {
1886     let hir_id = match DocContext::as_local_hir_id(tcx, item.def_id) {
1887         Some(hir_id) => hir_id,
1888         None => {
1889             // If non-local, no need to check anything.
1890             info!("ignoring warning from parent crate: {}", msg);
1891             return;
1892         }
1893     };
1894
1895     let sp = item.attr_span(tcx);
1896
1897     tcx.struct_span_lint_hir(lint, hir_id, sp, |lint| {
1898         let mut diag = lint.build(msg);
1899
1900         let span =
1901             super::source_span_for_markdown_range(tcx, dox, link_range, &item.attrs).map(|sp| {
1902                 if dox.as_bytes().get(link_range.start) == Some(&b'`')
1903                     && dox.as_bytes().get(link_range.end - 1) == Some(&b'`')
1904                 {
1905                     sp.with_lo(sp.lo() + BytePos(1)).with_hi(sp.hi() - BytePos(1))
1906                 } else {
1907                     sp
1908                 }
1909             });
1910
1911         if let Some(sp) = span {
1912             diag.set_span(sp);
1913         } else {
1914             // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1915             //                       ^     ~~~~
1916             //                       |     link_range
1917             //                       last_new_line_offset
1918             let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1919             let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1920
1921             // Print the line containing the `link_range` and manually mark it with '^'s.
1922             diag.note(&format!(
1923                 "the link appears in this line:\n\n{line}\n\
1924                      {indicator: <before$}{indicator:^<found$}",
1925                 line = line,
1926                 indicator = "",
1927                 before = link_range.start - last_new_line_offset,
1928                 found = link_range.len(),
1929             ));
1930         }
1931
1932         decorate(&mut diag, span);
1933
1934         diag.emit();
1935     });
1936 }
1937
1938 /// Reports a link that failed to resolve.
1939 ///
1940 /// This also tries to resolve any intermediate path segments that weren't
1941 /// handled earlier. For example, if passed `Item::Crate(std)` and `path_str`
1942 /// `std::io::Error::x`, this will resolve `std::io::Error`.
1943 fn resolution_failure(
1944     collector: &mut LinkCollector<'_, '_>,
1945     diag_info: DiagnosticInfo<'_>,
1946     path_str: &str,
1947     disambiguator: Option<Disambiguator>,
1948     kinds: SmallVec<[ResolutionFailure<'_>; 3]>,
1949 ) {
1950     let tcx = collector.cx.tcx;
1951     report_diagnostic(
1952         tcx,
1953         BROKEN_INTRA_DOC_LINKS,
1954         &format!("unresolved link to `{}`", path_str),
1955         &diag_info,
1956         |diag, sp| {
1957             let item = |res: Res| format!("the {} `{}`", res.descr(), res.name(tcx),);
1958             let assoc_item_not_allowed = |res: Res| {
1959                 let name = res.name(tcx);
1960                 format!(
1961                     "`{}` is {} {}, not a module or type, and cannot have associated items",
1962                     name,
1963                     res.article(),
1964                     res.descr()
1965                 )
1966             };
1967             // ignore duplicates
1968             let mut variants_seen = SmallVec::<[_; 3]>::new();
1969             for mut failure in kinds {
1970                 let variant = std::mem::discriminant(&failure);
1971                 if variants_seen.contains(&variant) {
1972                     continue;
1973                 }
1974                 variants_seen.push(variant);
1975
1976                 if let ResolutionFailure::NotResolved { module_id, partial_res, unresolved } =
1977                     &mut failure
1978                 {
1979                     use DefKind::*;
1980
1981                     let module_id = *module_id;
1982                     // FIXME(jynelson): this might conflict with my `Self` fix in #76467
1983                     // FIXME: maybe use itertools `collect_tuple` instead?
1984                     fn split(path: &str) -> Option<(&str, &str)> {
1985                         let mut splitter = path.rsplitn(2, "::");
1986                         splitter.next().and_then(|right| splitter.next().map(|left| (left, right)))
1987                     }
1988
1989                     // Check if _any_ parent of the path gets resolved.
1990                     // If so, report it and say the first which failed; if not, say the first path segment didn't resolve.
1991                     let mut name = path_str;
1992                     'outer: loop {
1993                         let (start, end) = if let Some(x) = split(name) {
1994                             x
1995                         } else {
1996                             // avoid bug that marked [Quux::Z] as missing Z, not Quux
1997                             if partial_res.is_none() {
1998                                 *unresolved = name.into();
1999                             }
2000                             break;
2001                         };
2002                         name = start;
2003                         for ns in [TypeNS, ValueNS, MacroNS] {
2004                             if let Some(res) = collector.check_full_res(ns, start, module_id, &None)
2005                             {
2006                                 debug!("found partial_res={:?}", res);
2007                                 *partial_res = Some(res);
2008                                 *unresolved = end.into();
2009                                 break 'outer;
2010                             }
2011                         }
2012                         *unresolved = end.into();
2013                     }
2014
2015                     let last_found_module = match *partial_res {
2016                         Some(Res::Def(DefKind::Mod, id)) => Some(id),
2017                         None => Some(module_id),
2018                         _ => None,
2019                     };
2020                     // See if this was a module: `[path]` or `[std::io::nope]`
2021                     if let Some(module) = last_found_module {
2022                         let note = if partial_res.is_some() {
2023                             // Part of the link resolved; e.g. `std::io::nonexistent`
2024                             let module_name = tcx.item_name(module);
2025                             format!("no item named `{}` in module `{}`", unresolved, module_name)
2026                         } else {
2027                             // None of the link resolved; e.g. `Notimported`
2028                             format!("no item named `{}` in scope", unresolved)
2029                         };
2030                         if let Some(span) = sp {
2031                             diag.span_label(span, &note);
2032                         } else {
2033                             diag.note(&note);
2034                         }
2035
2036                         // If the link has `::` in it, assume it was meant to be an intra-doc link.
2037                         // Otherwise, the `[]` might be unrelated.
2038                         // FIXME: don't show this for autolinks (`<>`), `()` style links, or reference links
2039                         if !path_str.contains("::") {
2040                             diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
2041                         }
2042
2043                         continue;
2044                     }
2045
2046                     // Otherwise, it must be an associated item or variant
2047                     let res = partial_res.expect("None case was handled by `last_found_module`");
2048                     let name = res.name(tcx);
2049                     let kind = match res {
2050                         Res::Def(kind, _) => Some(kind),
2051                         Res::Primitive(_) => None,
2052                     };
2053                     let path_description = if let Some(kind) = kind {
2054                         match kind {
2055                             Mod | ForeignMod => "inner item",
2056                             Struct => "field or associated item",
2057                             Enum | Union => "variant or associated item",
2058                             Variant
2059                             | Field
2060                             | Closure
2061                             | Generator
2062                             | AssocTy
2063                             | AssocConst
2064                             | AssocFn
2065                             | Fn
2066                             | Macro(_)
2067                             | Const
2068                             | ConstParam
2069                             | ExternCrate
2070                             | Use
2071                             | LifetimeParam
2072                             | Ctor(_, _)
2073                             | AnonConst
2074                             | InlineConst => {
2075                                 let note = assoc_item_not_allowed(res);
2076                                 if let Some(span) = sp {
2077                                     diag.span_label(span, &note);
2078                                 } else {
2079                                     diag.note(&note);
2080                                 }
2081                                 return;
2082                             }
2083                             Trait | TyAlias | ForeignTy | OpaqueTy | TraitAlias | TyParam
2084                             | Static => "associated item",
2085                             Impl | GlobalAsm => unreachable!("not a path"),
2086                         }
2087                     } else {
2088                         "associated item"
2089                     };
2090                     let note = format!(
2091                         "the {} `{}` has no {} named `{}`",
2092                         res.descr(),
2093                         name,
2094                         disambiguator.map_or(path_description, |d| d.descr()),
2095                         unresolved,
2096                     );
2097                     if let Some(span) = sp {
2098                         diag.span_label(span, &note);
2099                     } else {
2100                         diag.note(&note);
2101                     }
2102
2103                     continue;
2104                 }
2105                 let note = match failure {
2106                     ResolutionFailure::NotResolved { .. } => unreachable!("handled above"),
2107                     ResolutionFailure::Dummy => continue,
2108                     ResolutionFailure::WrongNamespace { res, expected_ns } => {
2109                         suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2110
2111                         format!(
2112                             "this link resolves to {}, which is not in the {} namespace",
2113                             item(res),
2114                             expected_ns.descr()
2115                         )
2116                     }
2117                     ResolutionFailure::NoParentItem => {
2118                         diag.level = rustc_errors::Level::Bug;
2119                         "all intra-doc links should have a parent item".to_owned()
2120                     }
2121                     ResolutionFailure::MalformedGenerics(variant) => match variant {
2122                         MalformedGenerics::UnbalancedAngleBrackets => {
2123                             String::from("unbalanced angle brackets")
2124                         }
2125                         MalformedGenerics::MissingType => {
2126                             String::from("missing type for generic parameters")
2127                         }
2128                         MalformedGenerics::HasFullyQualifiedSyntax => {
2129                             diag.note("see https://github.com/rust-lang/rust/issues/74563 for more information");
2130                             String::from("fully-qualified syntax is unsupported")
2131                         }
2132                         MalformedGenerics::InvalidPathSeparator => {
2133                             String::from("has invalid path separator")
2134                         }
2135                         MalformedGenerics::TooManyAngleBrackets => {
2136                             String::from("too many angle brackets")
2137                         }
2138                         MalformedGenerics::EmptyAngleBrackets => {
2139                             String::from("empty angle brackets")
2140                         }
2141                     },
2142                 };
2143                 if let Some(span) = sp {
2144                     diag.span_label(span, &note);
2145                 } else {
2146                     diag.note(&note);
2147                 }
2148             }
2149         },
2150     );
2151 }
2152
2153 /// Report an anchor failure.
2154 fn anchor_failure(cx: &DocContext<'_>, diag_info: DiagnosticInfo<'_>, failure: AnchorFailure) {
2155     let (msg, anchor_idx) = match failure {
2156         AnchorFailure::MultipleAnchors => {
2157             (format!("`{}` contains multiple anchors", diag_info.ori_link), 1)
2158         }
2159         AnchorFailure::RustdocAnchorConflict(res) => (
2160             format!(
2161                 "`{}` contains an anchor, but links to {kind}s are already anchored",
2162                 diag_info.ori_link,
2163                 kind = res.descr(),
2164             ),
2165             0,
2166         ),
2167     };
2168
2169     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2170         if let Some(mut sp) = sp {
2171             if let Some((fragment_offset, _)) =
2172                 diag_info.ori_link.char_indices().filter(|(_, x)| *x == '#').nth(anchor_idx)
2173             {
2174                 sp = sp.with_lo(sp.lo() + BytePos(fragment_offset as _));
2175             }
2176             diag.span_label(sp, "invalid anchor");
2177         }
2178         if let AnchorFailure::RustdocAnchorConflict(Res::Primitive(_)) = failure {
2179             if let Some(sp) = sp {
2180                 span_bug!(sp, "anchors should be allowed now");
2181             } else {
2182                 bug!("anchors should be allowed now");
2183             }
2184         }
2185     });
2186 }
2187
2188 /// Report an error in the link disambiguator.
2189 fn disambiguator_error(
2190     cx: &DocContext<'_>,
2191     mut diag_info: DiagnosticInfo<'_>,
2192     disambiguator_range: Range<usize>,
2193     msg: &str,
2194 ) {
2195     diag_info.link_range = disambiguator_range;
2196     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp| {
2197         let msg = format!(
2198             "see {}/rustdoc/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators",
2199             crate::DOC_RUST_LANG_ORG_CHANNEL
2200         );
2201         diag.note(&msg);
2202     });
2203 }
2204
2205 /// Report an ambiguity error, where there were multiple possible resolutions.
2206 fn ambiguity_error(
2207     cx: &DocContext<'_>,
2208     diag_info: DiagnosticInfo<'_>,
2209     path_str: &str,
2210     candidates: Vec<Res>,
2211 ) {
2212     let mut msg = format!("`{}` is ", path_str);
2213
2214     match candidates.as_slice() {
2215         [first_def, second_def] => {
2216             msg += &format!(
2217                 "both {} {} and {} {}",
2218                 first_def.article(),
2219                 first_def.descr(),
2220                 second_def.article(),
2221                 second_def.descr(),
2222             );
2223         }
2224         _ => {
2225             let mut candidates = candidates.iter().peekable();
2226             while let Some(res) = candidates.next() {
2227                 if candidates.peek().is_some() {
2228                     msg += &format!("{} {}, ", res.article(), res.descr());
2229                 } else {
2230                     msg += &format!("and {} {}", res.article(), res.descr());
2231                 }
2232             }
2233         }
2234     }
2235
2236     report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, &msg, &diag_info, |diag, sp| {
2237         if let Some(sp) = sp {
2238             diag.span_label(sp, "ambiguous link");
2239         } else {
2240             diag.note("ambiguous link");
2241         }
2242
2243         for res in candidates {
2244             suggest_disambiguator(res, diag, path_str, diag_info.ori_link, sp);
2245         }
2246     });
2247 }
2248
2249 /// In case of an ambiguity or mismatched disambiguator, suggest the correct
2250 /// disambiguator.
2251 fn suggest_disambiguator(
2252     res: Res,
2253     diag: &mut DiagnosticBuilder<'_>,
2254     path_str: &str,
2255     ori_link: &str,
2256     sp: Option<rustc_span::Span>,
2257 ) {
2258     let suggestion = res.disambiguator_suggestion();
2259     let help = format!("to link to the {}, {}", res.descr(), suggestion.descr());
2260
2261     if let Some(sp) = sp {
2262         let mut spans = suggestion.as_help_span(path_str, ori_link, sp);
2263         if spans.len() > 1 {
2264             diag.multipart_suggestion(&help, spans, Applicability::MaybeIncorrect);
2265         } else {
2266             let (sp, suggestion_text) = spans.pop().unwrap();
2267             diag.span_suggestion_verbose(sp, &help, suggestion_text, Applicability::MaybeIncorrect);
2268         }
2269     } else {
2270         diag.help(&format!("{}: {}", help, suggestion.as_help(path_str)));
2271     }
2272 }
2273
2274 /// Report a link from a public item to a private one.
2275 fn privacy_error(cx: &DocContext<'_>, diag_info: &DiagnosticInfo<'_>, path_str: &str) {
2276     let sym;
2277     let item_name = match diag_info.item.name {
2278         Some(name) => {
2279             sym = name;
2280             sym.as_str()
2281         }
2282         None => "<unknown>",
2283     };
2284     let msg =
2285         format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
2286
2287     report_diagnostic(cx.tcx, PRIVATE_INTRA_DOC_LINKS, &msg, diag_info, |diag, sp| {
2288         if let Some(sp) = sp {
2289             diag.span_label(sp, "this item is private");
2290         }
2291
2292         let note_msg = if cx.render_options.document_private {
2293             "this link resolves only because you passed `--document-private-items`, but will break without"
2294         } else {
2295             "this link will resolve properly if you pass `--document-private-items`"
2296         };
2297         diag.note(note_msg);
2298     });
2299 }
2300
2301 /// Given an enum variant's res, return the res of its enum and the associated fragment.
2302 fn handle_variant(
2303     cx: &DocContext<'_>,
2304     res: Res,
2305 ) -> Result<(Res, Option<ItemFragment>), ErrorKind<'static>> {
2306     cx.tcx
2307         .parent(res.def_id(cx.tcx))
2308         .map(|parent| {
2309             let parent_def = Res::Def(DefKind::Enum, parent);
2310             let variant = cx.tcx.expect_variant_res(res.as_hir_res().unwrap());
2311             (parent_def, Some(ItemFragment(FragmentKind::Variant, variant.def_id)))
2312         })
2313         .ok_or_else(|| ResolutionFailure::NoParentItem.into())
2314 }
2315
2316 /// Resolve a primitive type or value.
2317 fn resolve_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
2318     if ns != TypeNS {
2319         return None;
2320     }
2321     use PrimitiveType::*;
2322     let prim = match path_str {
2323         "isize" => Isize,
2324         "i8" => I8,
2325         "i16" => I16,
2326         "i32" => I32,
2327         "i64" => I64,
2328         "i128" => I128,
2329         "usize" => Usize,
2330         "u8" => U8,
2331         "u16" => U16,
2332         "u32" => U32,
2333         "u64" => U64,
2334         "u128" => U128,
2335         "f32" => F32,
2336         "f64" => F64,
2337         "char" => Char,
2338         "bool" | "true" | "false" => Bool,
2339         "str" | "&str" => Str,
2340         // See #80181 for why these don't have symbols associated.
2341         "slice" => Slice,
2342         "array" => Array,
2343         "tuple" => Tuple,
2344         "unit" => Unit,
2345         "pointer" | "*const" | "*mut" => RawPointer,
2346         "reference" | "&" | "&mut" => Reference,
2347         "fn" => Fn,
2348         "never" | "!" => Never,
2349         _ => return None,
2350     };
2351     debug!("resolved primitives {:?}", prim);
2352     Some(Res::Primitive(prim))
2353 }
2354
2355 fn strip_generics_from_path(path_str: &str) -> Result<String, ResolutionFailure<'static>> {
2356     let mut stripped_segments = vec![];
2357     let mut path = path_str.chars().peekable();
2358     let mut segment = Vec::new();
2359
2360     while let Some(chr) = path.next() {
2361         match chr {
2362             ':' => {
2363                 if path.next_if_eq(&':').is_some() {
2364                     let stripped_segment =
2365                         strip_generics_from_path_segment(mem::take(&mut segment))?;
2366                     if !stripped_segment.is_empty() {
2367                         stripped_segments.push(stripped_segment);
2368                     }
2369                 } else {
2370                     return Err(ResolutionFailure::MalformedGenerics(
2371                         MalformedGenerics::InvalidPathSeparator,
2372                     ));
2373                 }
2374             }
2375             '<' => {
2376                 segment.push(chr);
2377
2378                 match path.next() {
2379                     Some('<') => {
2380                         return Err(ResolutionFailure::MalformedGenerics(
2381                             MalformedGenerics::TooManyAngleBrackets,
2382                         ));
2383                     }
2384                     Some('>') => {
2385                         return Err(ResolutionFailure::MalformedGenerics(
2386                             MalformedGenerics::EmptyAngleBrackets,
2387                         ));
2388                     }
2389                     Some(chr) => {
2390                         segment.push(chr);
2391
2392                         while let Some(chr) = path.next_if(|c| *c != '>') {
2393                             segment.push(chr);
2394                         }
2395                     }
2396                     None => break,
2397                 }
2398             }
2399             _ => segment.push(chr),
2400         }
2401         trace!("raw segment: {:?}", segment);
2402     }
2403
2404     if !segment.is_empty() {
2405         let stripped_segment = strip_generics_from_path_segment(segment)?;
2406         if !stripped_segment.is_empty() {
2407             stripped_segments.push(stripped_segment);
2408         }
2409     }
2410
2411     debug!("path_str: {:?}\nstripped segments: {:?}", path_str, &stripped_segments);
2412
2413     let stripped_path = stripped_segments.join("::");
2414
2415     if !stripped_path.is_empty() {
2416         Ok(stripped_path)
2417     } else {
2418         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::MissingType))
2419     }
2420 }
2421
2422 fn strip_generics_from_path_segment(
2423     segment: Vec<char>,
2424 ) -> Result<String, ResolutionFailure<'static>> {
2425     let mut stripped_segment = String::new();
2426     let mut param_depth = 0;
2427
2428     let mut latest_generics_chunk = String::new();
2429
2430     for c in segment {
2431         if c == '<' {
2432             param_depth += 1;
2433             latest_generics_chunk.clear();
2434         } else if c == '>' {
2435             param_depth -= 1;
2436             if latest_generics_chunk.contains(" as ") {
2437                 // The segment tries to use fully-qualified syntax, which is currently unsupported.
2438                 // Give a helpful error message instead of completely ignoring the angle brackets.
2439                 return Err(ResolutionFailure::MalformedGenerics(
2440                     MalformedGenerics::HasFullyQualifiedSyntax,
2441                 ));
2442             }
2443         } else {
2444             if param_depth == 0 {
2445                 stripped_segment.push(c);
2446             } else {
2447                 latest_generics_chunk.push(c);
2448             }
2449         }
2450     }
2451
2452     if param_depth == 0 {
2453         Ok(stripped_segment)
2454     } else {
2455         // The segment has unbalanced angle brackets, e.g. `Vec<T` or `Vec<T>>`
2456         Err(ResolutionFailure::MalformedGenerics(MalformedGenerics::UnbalancedAngleBrackets))
2457     }
2458 }