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