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