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