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