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