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