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