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