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