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