]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_intra_doc_links.rs
Fix intra-doc links for associated constants
[rust.git] / src / librustdoc / passes / collect_intra_doc_links.rs
1 use rustc_ast as ast;
2 use rustc_data_structures::stable_set::FxHashSet;
3 use rustc_errors::{Applicability, DiagnosticBuilder};
4 use rustc_expand::base::SyntaxExtensionKind;
5 use rustc_feature::UnstableFeatures;
6 use rustc_hir as hir;
7 use rustc_hir::def::{
8     DefKind,
9     Namespace::{self, *},
10     PerNS, Res,
11 };
12 use rustc_hir::def_id::DefId;
13 use rustc_middle::ty;
14 use rustc_resolve::ParentScope;
15 use rustc_session::lint;
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::symbol::Ident;
18 use rustc_span::symbol::Symbol;
19 use rustc_span::DUMMY_SP;
20 use smallvec::SmallVec;
21
22 use std::cell::Cell;
23 use std::ops::Range;
24
25 use crate::clean::*;
26 use crate::core::DocContext;
27 use crate::fold::DocFolder;
28 use crate::html::markdown::markdown_links;
29 use crate::passes::Pass;
30
31 use super::span_of_attrs;
32
33 pub const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
34     name: "collect-intra-doc-links",
35     run: collect_intra_doc_links,
36     description: "reads a crate's documentation to resolve intra-doc-links",
37 };
38
39 pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
40     if !UnstableFeatures::from_environment().is_nightly_build() {
41         krate
42     } else {
43         let mut coll = LinkCollector::new(cx);
44
45         coll.fold_crate(krate)
46     }
47 }
48
49 enum ErrorKind {
50     ResolutionFailure,
51     AnchorFailure(AnchorFailure),
52 }
53
54 enum AnchorFailure {
55     MultipleAnchors,
56     Primitive,
57     Variant,
58     AssocConstant,
59     AssocType,
60     Field,
61     Method,
62 }
63
64 struct LinkCollector<'a, 'tcx> {
65     cx: &'a DocContext<'tcx>,
66     // NOTE: this may not necessarily be a module in the current crate
67     mod_ids: Vec<DefId>,
68     /// This is used to store the kind of associated items,
69     /// because `clean` and the disambiguator code expect them to be different.
70     /// See the code for associated items on inherent impls for details.
71     kind_side_channel: Cell<Option<DefKind>>,
72 }
73
74 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
75     fn new(cx: &'a DocContext<'tcx>) -> Self {
76         LinkCollector { cx, mod_ids: Vec::new(), kind_side_channel: Cell::new(None) }
77     }
78
79     fn variant_field(
80         &self,
81         path_str: &str,
82         current_item: &Option<String>,
83         module_id: DefId,
84     ) -> Result<(Res, Option<String>), ErrorKind> {
85         let cx = self.cx;
86
87         let mut split = path_str.rsplitn(3, "::");
88         let variant_field_name =
89             split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
90         let variant_name =
91             split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
92         let path = split
93             .next()
94             .map(|f| {
95                 if f == "self" || f == "Self" {
96                     if let Some(name) = current_item.as_ref() {
97                         return name.clone();
98                     }
99                 }
100                 f.to_owned()
101             })
102             .ok_or(ErrorKind::ResolutionFailure)?;
103         let (_, ty_res) = cx
104             .enter_resolver(|resolver| {
105                 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
106             })
107             .map_err(|_| ErrorKind::ResolutionFailure)?;
108         if let Res::Err = ty_res {
109             return Err(ErrorKind::ResolutionFailure);
110         }
111         let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
112         match ty_res {
113             Res::Def(DefKind::Enum, did) => {
114                 if cx
115                     .tcx
116                     .inherent_impls(did)
117                     .iter()
118                     .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
119                     .any(|item| item.ident.name == variant_name)
120                 {
121                     return Err(ErrorKind::ResolutionFailure);
122                 }
123                 match cx.tcx.type_of(did).kind {
124                     ty::Adt(def, _) if def.is_enum() => {
125                         if def.all_fields().any(|item| item.ident.name == variant_field_name) {
126                             Ok((
127                                 ty_res,
128                                 Some(format!(
129                                     "variant.{}.field.{}",
130                                     variant_name, variant_field_name
131                                 )),
132                             ))
133                         } else {
134                             Err(ErrorKind::ResolutionFailure)
135                         }
136                     }
137                     _ => Err(ErrorKind::ResolutionFailure),
138                 }
139             }
140             _ => Err(ErrorKind::ResolutionFailure),
141         }
142     }
143
144     /// Resolves a string as a macro.
145     fn macro_resolve(&self, path_str: &str, parent_id: Option<DefId>) -> Option<Res> {
146         let cx = self.cx;
147         let path = ast::Path::from_ident(Ident::from_str(path_str));
148         cx.enter_resolver(|resolver| {
149             if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
150                 &path,
151                 None,
152                 &ParentScope::module(resolver.graph_root()),
153                 false,
154                 false,
155             ) {
156                 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
157                     return Some(res.map_id(|_| panic!("unexpected id")));
158                 }
159             }
160             if let Some(res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
161                 return Some(res.map_id(|_| panic!("unexpected id")));
162             }
163             if let Some(module_id) = parent_id {
164                 if let Ok((_, res)) =
165                     resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
166                 {
167                     // don't resolve builtins like `#[derive]`
168                     if let Res::Def(..) = res {
169                         let res = res.map_id(|_| panic!("unexpected node_id"));
170                         return Some(res);
171                     }
172                 }
173             } else {
174                 debug!("attempting to resolve item without parent module: {}", path_str);
175             }
176             None
177         })
178     }
179     /// Resolves a string as a path within a particular namespace. Also returns an optional
180     /// URL fragment in the case of variants and methods.
181     fn resolve(
182         &self,
183         path_str: &str,
184         ns: Namespace,
185         current_item: &Option<String>,
186         parent_id: Option<DefId>,
187         extra_fragment: &Option<String>,
188     ) -> Result<(Res, Option<String>), ErrorKind> {
189         let cx = self.cx;
190
191         // In case we're in a module, try to resolve the relative path.
192         if let Some(module_id) = parent_id {
193             let result = cx.enter_resolver(|resolver| {
194                 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
195             });
196             debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
197             let result = match result {
198                 Ok((_, Res::Err)) => Err(ErrorKind::ResolutionFailure),
199                 _ => result.map_err(|_| ErrorKind::ResolutionFailure),
200             };
201
202             if let Ok((_, res)) = result {
203                 let res = res.map_id(|_| panic!("unexpected node_id"));
204                 // In case this is a trait item, skip the
205                 // early return and try looking for the trait.
206                 let value = match res {
207                     Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => true,
208                     Res::Def(DefKind::AssocTy, _) => false,
209                     Res::Def(DefKind::Variant, _) => {
210                         return handle_variant(cx, res, extra_fragment);
211                     }
212                     // Not a trait item; just return what we found.
213                     Res::PrimTy(..) => {
214                         if extra_fragment.is_some() {
215                             return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
216                         }
217                         return Ok((res, Some(path_str.to_owned())));
218                     }
219                     Res::Def(DefKind::Mod, _) => {
220                         return Ok((res, extra_fragment.clone()));
221                     }
222                     _ => {
223                         return Ok((res, extra_fragment.clone()));
224                     }
225                 };
226
227                 if value != (ns == ValueNS) {
228                     return Err(ErrorKind::ResolutionFailure);
229                 }
230             } else if let Some((path, prim)) = is_primitive(path_str, ns) {
231                 if extra_fragment.is_some() {
232                     return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
233                 }
234                 return Ok((prim, Some(path.to_owned())));
235             }
236
237             // Try looking for methods and associated items.
238             let mut split = path_str.rsplitn(2, "::");
239             let item_name =
240                 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
241             let path = split
242                 .next()
243                 .map(|f| {
244                     if f == "self" || f == "Self" {
245                         if let Some(name) = current_item.as_ref() {
246                             return name.clone();
247                         }
248                     }
249                     f.to_owned()
250                 })
251                 .ok_or(ErrorKind::ResolutionFailure)?;
252
253             if let Some((path, prim)) = is_primitive(&path, TypeNS) {
254                 for &impl_ in primitive_impl(cx, &path).ok_or(ErrorKind::ResolutionFailure)? {
255                     let link = cx
256                         .tcx
257                         .associated_items(impl_)
258                         .find_by_name_and_namespace(
259                             cx.tcx,
260                             Ident::with_dummy_span(item_name),
261                             ns,
262                             impl_,
263                         )
264                         .map(|item| match item.kind {
265                             ty::AssocKind::Fn => "method",
266                             ty::AssocKind::Const => "associatedconstant",
267                             ty::AssocKind::Type => "associatedtype",
268                         })
269                         .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name))));
270                     if let Some(link) = link {
271                         return Ok(link);
272                     }
273                 }
274                 return Err(ErrorKind::ResolutionFailure);
275             }
276
277             let (_, ty_res) = cx
278                 .enter_resolver(|resolver| {
279                     resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
280                 })
281                 .map_err(|_| ErrorKind::ResolutionFailure)?;
282             if let Res::Err = ty_res {
283                 return if ns == Namespace::ValueNS {
284                     self.variant_field(path_str, current_item, module_id)
285                 } else {
286                     Err(ErrorKind::ResolutionFailure)
287                 };
288             }
289             let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
290             let res = match ty_res {
291                 Res::Def(
292                     DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::TyAlias,
293                     did,
294                 ) => {
295                     debug!("looking for associated item named {} for item {:?}", item_name, did);
296                     // Checks if item_name belongs to `impl SomeItem`
297                     let kind = cx
298                         .tcx
299                         .inherent_impls(did)
300                         .iter()
301                         .flat_map(|&imp| {
302                             cx.tcx.associated_items(imp).find_by_name_and_namespace(
303                                 cx.tcx,
304                                 Ident::with_dummy_span(item_name),
305                                 ns,
306                                 imp,
307                             )
308                         })
309                         .map(|item| item.kind)
310                         // There should only ever be one associated item that matches from any inherent impl
311                         .next()
312                         // Check if item_name belongs to `impl SomeTrait for SomeItem`
313                         // This gives precedence to `impl SomeItem`:
314                         // Although having both would be ambiguous, use impl version for compat. sake.
315                         // To handle that properly resolve() would have to support
316                         // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
317                         .or_else(|| {
318                             let kind = resolve_associated_trait_item(
319                                 did, module_id, item_name, ns, &self.cx,
320                             );
321                             debug!("got associated item kind {:?}", kind);
322                             kind
323                         });
324
325                     if let Some(kind) = kind {
326                         let out = match kind {
327                             ty::AssocKind::Fn => "method",
328                             ty::AssocKind::Const => "associatedconstant",
329                             ty::AssocKind::Type => "associatedtype",
330                         };
331                         Some(if extra_fragment.is_some() {
332                             Err(ErrorKind::AnchorFailure(if kind == ty::AssocKind::Fn {
333                                 AnchorFailure::Method
334                             } else {
335                                 AnchorFailure::AssocConstant
336                             }))
337                         } else {
338                             // HACK(jynelson): `clean` expects the type, not the associated item.
339                             // but the disambiguator logic expects the associated item.
340                             // Store the kind in a side channel so that only the disambiguator logic looks at it.
341                             self.kind_side_channel.set(Some(kind.as_def_kind()));
342                             Ok((ty_res, Some(format!("{}.{}", out, item_name))))
343                         })
344                     } else if ns == Namespace::ValueNS {
345                         match cx.tcx.type_of(did).kind {
346                             ty::Adt(def, _) => {
347                                 let field = if def.is_enum() {
348                                     def.all_fields().find(|item| item.ident.name == item_name)
349                                 } else {
350                                     def.non_enum_variant()
351                                         .fields
352                                         .iter()
353                                         .find(|item| item.ident.name == item_name)
354                                 };
355                                 field.map(|item| {
356                                     if extra_fragment.is_some() {
357                                         Err(ErrorKind::AnchorFailure(if def.is_enum() {
358                                             AnchorFailure::Variant
359                                         } else {
360                                             AnchorFailure::Field
361                                         }))
362                                     } else {
363                                         Ok((
364                                             ty_res,
365                                             Some(format!(
366                                                 "{}.{}",
367                                                 if def.is_enum() {
368                                                     "variant"
369                                                 } else {
370                                                     "structfield"
371                                                 },
372                                                 item.ident
373                                             )),
374                                         ))
375                                     }
376                                 })
377                             }
378                             _ => None,
379                         }
380                     } else {
381                         // We already know this isn't in ValueNS, so no need to check variant_field
382                         return Err(ErrorKind::ResolutionFailure);
383                     }
384                 }
385                 Res::Def(DefKind::Trait, did) => cx
386                     .tcx
387                     .associated_items(did)
388                     .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, did)
389                     .map(|item| {
390                         let kind = match item.kind {
391                             ty::AssocKind::Const => "associatedconstant",
392                             ty::AssocKind::Type => "associatedtype",
393                             ty::AssocKind::Fn => {
394                                 if item.defaultness.has_value() {
395                                     "method"
396                                 } else {
397                                     "tymethod"
398                                 }
399                             }
400                         };
401
402                         if extra_fragment.is_some() {
403                             Err(ErrorKind::AnchorFailure(if item.kind == ty::AssocKind::Const {
404                                 AnchorFailure::AssocConstant
405                             } else if item.kind == ty::AssocKind::Type {
406                                 AnchorFailure::AssocType
407                             } else {
408                                 AnchorFailure::Method
409                             }))
410                         } else {
411                             let res = Res::Def(item.kind.as_def_kind(), item.def_id);
412                             Ok((res, Some(format!("{}.{}", kind, item_name))))
413                         }
414                     }),
415                 _ => None,
416             };
417             res.unwrap_or_else(|| {
418                 if ns == Namespace::ValueNS {
419                     self.variant_field(path_str, current_item, module_id)
420                 } else {
421                     Err(ErrorKind::ResolutionFailure)
422                 }
423             })
424         } else {
425             debug!("attempting to resolve item without parent module: {}", path_str);
426             Err(ErrorKind::ResolutionFailure)
427         }
428     }
429 }
430
431 fn resolve_associated_trait_item(
432     did: DefId,
433     module: DefId,
434     item_name: Symbol,
435     ns: Namespace,
436     cx: &DocContext<'_>,
437 ) -> Option<ty::AssocKind> {
438     let ty = cx.tcx.type_of(did);
439     // First consider automatic impls: `impl From<T> for T`
440     let implicit_impls = crate::clean::get_auto_trait_and_blanket_impls(cx, ty, did);
441     let mut candidates: Vec<_> = implicit_impls
442         .flat_map(|impl_outer| {
443             match impl_outer.inner {
444                 ImplItem(impl_) => {
445                     debug!("considering auto or blanket impl for trait {:?}", impl_.trait_);
446                     // Give precedence to methods that were overridden
447                     if !impl_.provided_trait_methods.contains(&*item_name.as_str()) {
448                         let mut items = impl_.items.into_iter().filter_map(|assoc| {
449                             if assoc.name.as_deref() != Some(&*item_name.as_str()) {
450                                 return None;
451                             }
452                             let kind = assoc
453                                 .inner
454                                 .as_assoc_kind()
455                                 .expect("inner items for a trait should be associated items");
456                             if kind.namespace() != ns {
457                                 return None;
458                             }
459
460                             trace!("considering associated item {:?}", assoc.inner);
461                             // We have a slight issue: normal methods come from `clean` types,
462                             // but provided methods come directly from `tcx`.
463                             // Fortunately, we don't need the whole method, we just need to know
464                             // what kind of associated item it is.
465                             Some((assoc.def_id, kind))
466                         });
467                         let assoc = items.next();
468                         debug_assert_eq!(items.count(), 0);
469                         assoc
470                     } else {
471                         // These are provided methods or default types:
472                         // ```
473                         // trait T {
474                         //   type A = usize;
475                         //   fn has_default() -> A { 0 }
476                         // }
477                         // ```
478                         let trait_ = impl_.trait_.unwrap().def_id().unwrap();
479                         cx.tcx
480                             .associated_items(trait_)
481                             .find_by_name_and_namespace(
482                                 cx.tcx,
483                                 Ident::with_dummy_span(item_name),
484                                 ns,
485                                 trait_,
486                             )
487                             .map(|assoc| (assoc.def_id, assoc.kind))
488                     }
489                 }
490                 _ => panic!("get_impls returned something that wasn't an impl"),
491             }
492         })
493         .collect();
494
495     // Next consider explicit impls: `impl MyTrait for MyType`
496     // Give precedence to inherent impls.
497     if candidates.is_empty() {
498         let traits = traits_implemented_by(cx, did, module);
499         debug!("considering traits {:?}", traits);
500         candidates.extend(traits.iter().filter_map(|&trait_| {
501             cx.tcx
502                 .associated_items(trait_)
503                 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
504                 .map(|assoc| (assoc.def_id, assoc.kind))
505         }));
506     }
507     // FIXME: warn about ambiguity
508     debug!("the candidates were {:?}", candidates);
509     candidates.pop().map(|(_, kind)| kind)
510 }
511
512 /// Given a type, return all traits in scope in `module` implemented by that type.
513 ///
514 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
515 /// So it is not stable to serialize cross-crate.
516 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
517     let mut cache = cx.module_trait_cache.borrow_mut();
518     let in_scope_traits = cache.entry(module).or_insert_with(|| {
519         cx.enter_resolver(|resolver| {
520             resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
521         })
522     });
523
524     let ty = cx.tcx.type_of(type_);
525     let iter = in_scope_traits.iter().flat_map(|&trait_| {
526         trace!("considering explicit impl for trait {:?}", trait_);
527         let mut saw_impl = false;
528         // Look at each trait implementation to see if it's an impl for `did`
529         cx.tcx.for_each_relevant_impl(trait_, ty, |impl_| {
530             // FIXME: this is inefficient, find a way to short-circuit for_each_* so this doesn't take as long
531             if saw_impl {
532                 return;
533             }
534
535             let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
536             // Check if these are the same type.
537             let impl_type = trait_ref.self_ty();
538             debug!(
539                 "comparing type {} with kind {:?} against type {:?}",
540                 impl_type, impl_type.kind, type_
541             );
542             // Fast path: if this is a primitive simple `==` will work
543             saw_impl = impl_type == ty
544                 || match impl_type.kind {
545                     // Check if these are the same def_id
546                     ty::Adt(def, _) => {
547                         debug!("adt def_id: {:?}", def.did);
548                         def.did == type_
549                     }
550                     ty::Foreign(def_id) => def_id == type_,
551                     _ => false,
552                 };
553         });
554         if saw_impl { Some(trait_) } else { None }
555     });
556     iter.collect()
557 }
558
559 /// Check for resolve collisions between a trait and its derive
560 ///
561 /// These are common and we should just resolve to the trait in that case
562 fn is_derive_trait_collision<T>(ns: &PerNS<Option<(Res, T)>>) -> bool {
563     if let PerNS {
564         type_ns: Some((Res::Def(DefKind::Trait, _), _)),
565         macro_ns: Some((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
566         ..
567     } = *ns
568     {
569         true
570     } else {
571         false
572     }
573 }
574
575 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
576     fn fold_item(&mut self, mut item: Item) -> Option<Item> {
577         use rustc_middle::ty::DefIdTree;
578
579         let parent_node = if item.is_fake() {
580             // FIXME: is this correct?
581             None
582         } else {
583             let mut current = item.def_id;
584             // The immediate parent might not always be a module.
585             // Find the first parent which is.
586             loop {
587                 if let Some(parent) = self.cx.tcx.parent(current) {
588                     if self.cx.tcx.def_kind(parent) == DefKind::Mod {
589                         break Some(parent);
590                     }
591                     current = parent;
592                 } else {
593                     break None;
594                 }
595             }
596         };
597
598         if parent_node.is_some() {
599             trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
600         }
601
602         let current_item = match item.inner {
603             ModuleItem(..) => {
604                 if item.attrs.inner_docs {
605                     if item.def_id.is_top_level_module() { item.name.clone() } else { None }
606                 } else {
607                     match parent_node.or(self.mod_ids.last().copied()) {
608                         Some(parent) if !parent.is_top_level_module() => {
609                             // FIXME: can we pull the parent module's name from elsewhere?
610                             Some(self.cx.tcx.item_name(parent).to_string())
611                         }
612                         _ => None,
613                     }
614                 }
615             }
616             ImplItem(Impl { ref for_, .. }) => {
617                 for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
618             }
619             // we don't display docs on `extern crate` items anyway, so don't process them.
620             ExternCrateItem(..) => {
621                 debug!("ignoring extern crate item {:?}", item.def_id);
622                 return self.fold_item_recur(item);
623             }
624             ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
625             MacroItem(..) => None,
626             _ => item.name.clone(),
627         };
628
629         if item.is_mod() && item.attrs.inner_docs {
630             self.mod_ids.push(item.def_id);
631         }
632
633         let cx = self.cx;
634         let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
635         trace!("got documentation '{}'", dox);
636
637         // find item's parent to resolve `Self` in item's docs below
638         let parent_name = self.cx.as_local_hir_id(item.def_id).and_then(|item_hir| {
639             let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
640             let item_parent = self.cx.tcx.hir().find(parent_hir);
641             match item_parent {
642                 Some(hir::Node::Item(hir::Item {
643                     kind:
644                         hir::ItemKind::Impl {
645                             self_ty:
646                                 hir::Ty {
647                                     kind:
648                                         hir::TyKind::Path(hir::QPath::Resolved(
649                                             _,
650                                             hir::Path { segments, .. },
651                                         )),
652                                     ..
653                                 },
654                             ..
655                         },
656                     ..
657                 })) => segments.first().map(|seg| seg.ident.to_string()),
658                 Some(hir::Node::Item(hir::Item {
659                     ident, kind: hir::ItemKind::Enum(..), ..
660                 }))
661                 | Some(hir::Node::Item(hir::Item {
662                     ident, kind: hir::ItemKind::Struct(..), ..
663                 }))
664                 | Some(hir::Node::Item(hir::Item {
665                     ident, kind: hir::ItemKind::Union(..), ..
666                 }))
667                 | Some(hir::Node::Item(hir::Item {
668                     ident, kind: hir::ItemKind::Trait(..), ..
669                 })) => Some(ident.to_string()),
670                 _ => None,
671             }
672         });
673
674         for (ori_link, link_range) in markdown_links(&dox) {
675             trace!("considering link '{}'", ori_link);
676
677             // Bail early for real links.
678             if ori_link.contains('/') {
679                 continue;
680             }
681
682             // [] is mostly likely not supposed to be a link
683             if ori_link.is_empty() {
684                 continue;
685             }
686
687             let link = ori_link.replace("`", "");
688             let parts = link.split('#').collect::<Vec<_>>();
689             let (link, extra_fragment) = if parts.len() > 2 {
690                 anchor_failure(cx, &item, &link, &dox, link_range, AnchorFailure::MultipleAnchors);
691                 continue;
692             } else if parts.len() == 2 {
693                 if parts[0].trim().is_empty() {
694                     // This is an anchor to an element of the current page, nothing to do in here!
695                     continue;
696                 }
697                 (parts[0].to_owned(), Some(parts[1].to_owned()))
698             } else {
699                 (parts[0].to_owned(), None)
700             };
701             let resolved_self;
702             let mut path_str;
703             let disambiguator;
704             let (mut res, mut fragment) = {
705                 path_str = if let Ok((d, path)) = Disambiguator::from_str(&link) {
706                     disambiguator = Some(d);
707                     path
708                 } else {
709                     disambiguator = None;
710                     &link
711                 }
712                 .trim();
713
714                 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ch == ':' || ch == '_')) {
715                     continue;
716                 }
717
718                 // In order to correctly resolve intra-doc-links we need to
719                 // pick a base AST node to work from.  If the documentation for
720                 // this module came from an inner comment (//!) then we anchor
721                 // our name resolution *inside* the module.  If, on the other
722                 // hand it was an outer comment (///) then we anchor the name
723                 // resolution in the parent module on the basis that the names
724                 // used are more likely to be intended to be parent names.  For
725                 // this, we set base_node to None for inner comments since
726                 // we've already pushed this node onto the resolution stack but
727                 // for outer comments we explicitly try and resolve against the
728                 // parent_node first.
729                 let base_node = if item.is_mod() && item.attrs.inner_docs {
730                     self.mod_ids.last().copied()
731                 } else {
732                     parent_node
733                 };
734
735                 // replace `Self` with suitable item's parent name
736                 if path_str.starts_with("Self::") {
737                     if let Some(ref name) = parent_name {
738                         resolved_self = format!("{}::{}", name, &path_str[6..]);
739                         path_str = &resolved_self;
740                     }
741                 }
742
743                 match disambiguator.map(Disambiguator::ns) {
744                     Some(ns @ (ValueNS | TypeNS)) => {
745                         match self.resolve(path_str, ns, &current_item, base_node, &extra_fragment)
746                         {
747                             Ok(res) => res,
748                             Err(ErrorKind::ResolutionFailure) => {
749                                 resolution_failure(cx, &item, path_str, &dox, link_range);
750                                 // This could just be a normal link or a broken link
751                                 // we could potentially check if something is
752                                 // "intra-doc-link-like" and warn in that case.
753                                 continue;
754                             }
755                             Err(ErrorKind::AnchorFailure(msg)) => {
756                                 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
757                                 continue;
758                             }
759                         }
760                     }
761                     None => {
762                         // Try everything!
763                         let mut candidates = PerNS {
764                             macro_ns: self
765                                 .macro_resolve(path_str, base_node)
766                                 .map(|res| (res, extra_fragment.clone())),
767                             type_ns: match self.resolve(
768                                 path_str,
769                                 TypeNS,
770                                 &current_item,
771                                 base_node,
772                                 &extra_fragment,
773                             ) {
774                                 Ok(res) => {
775                                     debug!("got res in TypeNS: {:?}", res);
776                                     Some(res)
777                                 }
778                                 Err(ErrorKind::AnchorFailure(msg)) => {
779                                     anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
780                                     continue;
781                                 }
782                                 Err(ErrorKind::ResolutionFailure) => None,
783                             },
784                             value_ns: match self.resolve(
785                                 path_str,
786                                 ValueNS,
787                                 &current_item,
788                                 base_node,
789                                 &extra_fragment,
790                             ) {
791                                 Ok(res) => Some(res),
792                                 Err(ErrorKind::AnchorFailure(msg)) => {
793                                     anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
794                                     continue;
795                                 }
796                                 Err(ErrorKind::ResolutionFailure) => None,
797                             }
798                             .and_then(|(res, fragment)| {
799                                 // Constructors are picked up in the type namespace.
800                                 match res {
801                                     Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
802                                     _ => match (fragment, extra_fragment) {
803                                         (Some(fragment), Some(_)) => {
804                                             // Shouldn't happen but who knows?
805                                             Some((res, Some(fragment)))
806                                         }
807                                         (fragment, None) | (None, fragment) => {
808                                             Some((res, fragment))
809                                         }
810                                     },
811                                 }
812                             }),
813                         };
814
815                         if candidates.is_empty() {
816                             resolution_failure(cx, &item, path_str, &dox, link_range);
817                             // this could just be a normal link
818                             continue;
819                         }
820
821                         let len = candidates.clone().present_items().count();
822
823                         if len == 1 {
824                             candidates.present_items().next().unwrap()
825                         } else if len == 2 && is_derive_trait_collision(&candidates) {
826                             candidates.type_ns.unwrap()
827                         } else {
828                             if is_derive_trait_collision(&candidates) {
829                                 candidates.macro_ns = None;
830                             }
831                             let candidates =
832                                 candidates.map(|candidate| candidate.map(|(res, _)| res));
833                             ambiguity_error(
834                                 cx,
835                                 &item,
836                                 path_str,
837                                 &dox,
838                                 link_range,
839                                 candidates.present_items().collect(),
840                             );
841                             continue;
842                         }
843                     }
844                     Some(MacroNS) => {
845                         if let Some(res) = self.macro_resolve(path_str, base_node) {
846                             (res, extra_fragment)
847                         } else {
848                             resolution_failure(cx, &item, path_str, &dox, link_range);
849                             continue;
850                         }
851                     }
852                 }
853             };
854
855             // Check for a primitive which might conflict with a module
856             // Report the ambiguity and require that the user specify which one they meant.
857             // FIXME: could there ever be a primitive not in the type namespace?
858             if matches!(
859                 disambiguator,
860                 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
861             ) && !matches!(res, Res::PrimTy(_))
862             {
863                 if let Some((path, prim)) = is_primitive(path_str, TypeNS) {
864                     // `prim@char`
865                     if matches!(disambiguator, Some(Disambiguator::Primitive)) {
866                         if fragment.is_some() {
867                             anchor_failure(
868                                 cx,
869                                 &item,
870                                 path_str,
871                                 &dox,
872                                 link_range,
873                                 AnchorFailure::Primitive,
874                             );
875                             continue;
876                         }
877                         res = prim;
878                         fragment = Some(path.to_owned());
879                     } else {
880                         // `[char]` when a `char` module is in scope
881                         let candidates = vec![res, prim];
882                         ambiguity_error(cx, &item, path_str, &dox, link_range, candidates);
883                         continue;
884                     }
885                 }
886             }
887
888             let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
889                 // The resolved item did not match the disambiguator; give a better error than 'not found'
890                 let msg = format!("incompatible link kind for `{}`", path_str);
891                 report_diagnostic(cx, &msg, &item, &dox, link_range.clone(), |diag, sp| {
892                     let note = format!(
893                         "this link resolved to {} {}, which is not {} {}",
894                         resolved.article(),
895                         resolved.descr(),
896                         specified.article(),
897                         specified.descr()
898                     );
899                     diag.note(&note);
900                     suggest_disambiguator(resolved, diag, path_str, &dox, sp, &link_range);
901                 });
902             };
903             if let Res::PrimTy(_) = res {
904                 match disambiguator {
905                     Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
906                         item.attrs.links.push((ori_link, None, fragment))
907                     }
908                     Some(other) => {
909                         report_mismatch(other, Disambiguator::Primitive);
910                         continue;
911                     }
912                 }
913             } else {
914                 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
915
916                 // Disallow e.g. linking to enums with `struct@`
917                 if let Res::Def(kind, _) = res {
918                     debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
919                     match (self.kind_side_channel.take().unwrap_or(kind), disambiguator) {
920                         | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
921                         // NOTE: this allows 'method' to mean both normal functions and associated functions
922                         // This can't cause ambiguity because both are in the same namespace.
923                         | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
924                         // These are namespaces; allow anything in the namespace to match
925                         | (_, Some(Disambiguator::Namespace(_)))
926                         // If no disambiguator given, allow anything
927                         | (_, None)
928                         // All of these are valid, so do nothing
929                         => {}
930                         (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
931                         (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
932                             report_mismatch(specified, Disambiguator::Kind(kind));
933                             continue;
934                         }
935                     }
936                 }
937
938                 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
939                 if let Some((src_id, dst_id)) = res
940                     .opt_def_id()
941                     .and_then(|def_id| def_id.as_local())
942                     .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
943                 {
944                     use rustc_hir::def_id::LOCAL_CRATE;
945
946                     let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
947                     let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
948
949                     if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
950                         && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
951                     {
952                         privacy_error(cx, &item, &path_str, &dox, link_range);
953                         continue;
954                     }
955                 }
956                 let id = register_res(cx, res);
957                 item.attrs.links.push((ori_link, Some(id), fragment));
958             }
959         }
960
961         if item.is_mod() && !item.attrs.inner_docs {
962             self.mod_ids.push(item.def_id);
963         }
964
965         if item.is_mod() {
966             let ret = self.fold_item_recur(item);
967
968             self.mod_ids.pop();
969
970             ret
971         } else {
972             self.fold_item_recur(item)
973         }
974     }
975
976     // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
977     // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
978     // will never resolve properly
979     fn fold_crate(&mut self, mut c: Crate) -> Crate {
980         c.module = c.module.take().and_then(|module| self.fold_item(module));
981
982         c
983     }
984 }
985
986 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
987 enum Disambiguator {
988     Primitive,
989     Kind(DefKind),
990     Namespace(Namespace),
991 }
992
993 impl Disambiguator {
994     /// (disambiguator, path_str)
995     fn from_str(link: &str) -> Result<(Self, &str), ()> {
996         use Disambiguator::{Kind, Namespace as NS, Primitive};
997
998         let find_suffix = || {
999             let suffixes = [
1000                 ("!()", DefKind::Macro(MacroKind::Bang)),
1001                 ("()", DefKind::Fn),
1002                 ("!", DefKind::Macro(MacroKind::Bang)),
1003             ];
1004             for &(suffix, kind) in &suffixes {
1005                 if link.ends_with(suffix) {
1006                     return Ok((Kind(kind), link.trim_end_matches(suffix)));
1007                 }
1008             }
1009             Err(())
1010         };
1011
1012         if let Some(idx) = link.find('@') {
1013             let (prefix, rest) = link.split_at(idx);
1014             let d = match prefix {
1015                 "struct" => Kind(DefKind::Struct),
1016                 "enum" => Kind(DefKind::Enum),
1017                 "trait" => Kind(DefKind::Trait),
1018                 "union" => Kind(DefKind::Union),
1019                 "module" | "mod" => Kind(DefKind::Mod),
1020                 "const" | "constant" => Kind(DefKind::Const),
1021                 "static" => Kind(DefKind::Static),
1022                 "function" | "fn" | "method" => Kind(DefKind::Fn),
1023                 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1024                 "type" => NS(Namespace::TypeNS),
1025                 "value" => NS(Namespace::ValueNS),
1026                 "macro" => NS(Namespace::MacroNS),
1027                 "prim" | "primitive" => Primitive,
1028                 _ => return find_suffix(),
1029             };
1030             Ok((d, &rest[1..]))
1031         } else {
1032             find_suffix()
1033         }
1034     }
1035
1036     /// WARNING: panics on `Res::Err`
1037     fn from_res(res: Res) -> Self {
1038         match res {
1039             Res::Def(kind, _) => Disambiguator::Kind(kind),
1040             Res::PrimTy(_) => Disambiguator::Primitive,
1041             _ => Disambiguator::Namespace(res.ns().expect("can't call `from_res` on Res::err")),
1042         }
1043     }
1044
1045     /// Return (description of the change, suggestion)
1046     fn display_for(self, path_str: &str) -> (&'static str, String) {
1047         const PREFIX: &str = "prefix with the item kind";
1048         const FUNCTION: &str = "add parentheses";
1049         const MACRO: &str = "add an exclamation mark";
1050
1051         let kind = match self {
1052             Disambiguator::Primitive => return (PREFIX, format!("prim@{}", path_str)),
1053             Disambiguator::Kind(kind) => kind,
1054             Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1055         };
1056         if kind == DefKind::Macro(MacroKind::Bang) {
1057             return (MACRO, format!("{}!", path_str));
1058         } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1059             return (FUNCTION, format!("{}()", path_str));
1060         }
1061
1062         let prefix = match kind {
1063             DefKind::Struct => "struct",
1064             DefKind::Enum => "enum",
1065             DefKind::Trait => "trait",
1066             DefKind::Union => "union",
1067             DefKind::Mod => "mod",
1068             DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1069                 "const"
1070             }
1071             DefKind::Static => "static",
1072             DefKind::Macro(MacroKind::Derive) => "derive",
1073             // Now handle things that don't have a specific disambiguator
1074             _ => match kind
1075                 .ns()
1076                 .expect("tried to calculate a disambiguator for a def without a namespace?")
1077             {
1078                 Namespace::TypeNS => "type",
1079                 Namespace::ValueNS => "value",
1080                 Namespace::MacroNS => "macro",
1081             },
1082         };
1083
1084         // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1085         (PREFIX, format!("{}@{}", prefix, path_str))
1086     }
1087
1088     fn ns(self) -> Namespace {
1089         match self {
1090             Self::Namespace(n) => n,
1091             Self::Kind(k) => {
1092                 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1093             }
1094             Self::Primitive => TypeNS,
1095         }
1096     }
1097
1098     fn article(self) -> &'static str {
1099         match self {
1100             Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1101             Self::Kind(k) => k.article(),
1102             Self::Primitive => "a",
1103         }
1104     }
1105
1106     fn descr(self) -> &'static str {
1107         match self {
1108             Self::Namespace(n) => n.descr(),
1109             // HACK(jynelson): by looking at the source I saw the DefId we pass
1110             // for `expected.descr()` doesn't matter, since it's not a crate
1111             Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1112             Self::Primitive => "builtin type",
1113         }
1114     }
1115 }
1116
1117 /// Reports a diagnostic for an intra-doc link.
1118 ///
1119 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1120 /// the entire documentation block is used for the lint. If a range is provided but the span
1121 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1122 ///
1123 /// The `decorate` callback is invoked in all cases to allow further customization of the
1124 /// diagnostic before emission. If the span of the link was able to be determined, the second
1125 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1126 /// to it.
1127 fn report_diagnostic(
1128     cx: &DocContext<'_>,
1129     msg: &str,
1130     item: &Item,
1131     dox: &str,
1132     link_range: Option<Range<usize>>,
1133     decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1134 ) {
1135     let hir_id = match cx.as_local_hir_id(item.def_id) {
1136         Some(hir_id) => hir_id,
1137         None => {
1138             // If non-local, no need to check anything.
1139             info!("ignoring warning from parent crate: {}", msg);
1140             return;
1141         }
1142     };
1143
1144     let attrs = &item.attrs;
1145     let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1146
1147     cx.tcx.struct_span_lint_hir(lint::builtin::BROKEN_INTRA_DOC_LINKS, hir_id, sp, |lint| {
1148         let mut diag = lint.build(msg);
1149
1150         let span = link_range
1151             .as_ref()
1152             .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
1153
1154         if let Some(link_range) = link_range {
1155             if let Some(sp) = span {
1156                 diag.set_span(sp);
1157             } else {
1158                 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1159                 //                       ^     ~~~~
1160                 //                       |     link_range
1161                 //                       last_new_line_offset
1162                 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1163                 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1164
1165                 // Print the line containing the `link_range` and manually mark it with '^'s.
1166                 diag.note(&format!(
1167                     "the link appears in this line:\n\n{line}\n\
1168                          {indicator: <before$}{indicator:^<found$}",
1169                     line = line,
1170                     indicator = "",
1171                     before = link_range.start - last_new_line_offset,
1172                     found = link_range.len(),
1173                 ));
1174             }
1175         }
1176
1177         decorate(&mut diag, span);
1178
1179         diag.emit();
1180     });
1181 }
1182
1183 fn resolution_failure(
1184     cx: &DocContext<'_>,
1185     item: &Item,
1186     path_str: &str,
1187     dox: &str,
1188     link_range: Option<Range<usize>>,
1189 ) {
1190     report_diagnostic(
1191         cx,
1192         &format!("unresolved link to `{}`", path_str),
1193         item,
1194         dox,
1195         link_range,
1196         |diag, sp| {
1197             if let Some(sp) = sp {
1198                 diag.span_label(sp, "unresolved link");
1199             }
1200
1201             diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1202         },
1203     );
1204 }
1205
1206 fn anchor_failure(
1207     cx: &DocContext<'_>,
1208     item: &Item,
1209     path_str: &str,
1210     dox: &str,
1211     link_range: Option<Range<usize>>,
1212     failure: AnchorFailure,
1213 ) {
1214     let msg = match failure {
1215         AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1216         AnchorFailure::Primitive
1217         | AnchorFailure::Variant
1218         | AnchorFailure::AssocConstant
1219         | AnchorFailure::AssocType
1220         | AnchorFailure::Field
1221         | AnchorFailure::Method => {
1222             let kind = match failure {
1223                 AnchorFailure::Primitive => "primitive type",
1224                 AnchorFailure::Variant => "enum variant",
1225                 AnchorFailure::AssocConstant => "associated constant",
1226                 AnchorFailure::AssocType => "associated type",
1227                 AnchorFailure::Field => "struct field",
1228                 AnchorFailure::Method => "method",
1229                 AnchorFailure::MultipleAnchors => unreachable!("should be handled already"),
1230             };
1231
1232             format!(
1233                 "`{}` contains an anchor, but links to {kind}s are already anchored",
1234                 path_str,
1235                 kind = kind
1236             )
1237         }
1238     };
1239
1240     report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1241         if let Some(sp) = sp {
1242             diag.span_label(sp, "contains invalid anchor");
1243         }
1244     });
1245 }
1246
1247 fn ambiguity_error(
1248     cx: &DocContext<'_>,
1249     item: &Item,
1250     path_str: &str,
1251     dox: &str,
1252     link_range: Option<Range<usize>>,
1253     candidates: Vec<Res>,
1254 ) {
1255     let mut msg = format!("`{}` is ", path_str);
1256
1257     match candidates.as_slice() {
1258         [first_def, second_def] => {
1259             msg += &format!(
1260                 "both {} {} and {} {}",
1261                 first_def.article(),
1262                 first_def.descr(),
1263                 second_def.article(),
1264                 second_def.descr(),
1265             );
1266         }
1267         _ => {
1268             let mut candidates = candidates.iter().peekable();
1269             while let Some(res) = candidates.next() {
1270                 if candidates.peek().is_some() {
1271                     msg += &format!("{} {}, ", res.article(), res.descr());
1272                 } else {
1273                     msg += &format!("and {} {}", res.article(), res.descr());
1274                 }
1275             }
1276         }
1277     }
1278
1279     report_diagnostic(cx, &msg, item, dox, link_range.clone(), |diag, sp| {
1280         if let Some(sp) = sp {
1281             diag.span_label(sp, "ambiguous link");
1282         } else {
1283             diag.note("ambiguous link");
1284         }
1285
1286         for res in candidates {
1287             let disambiguator = Disambiguator::from_res(res);
1288             suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1289         }
1290     });
1291 }
1292
1293 fn suggest_disambiguator(
1294     disambiguator: Disambiguator,
1295     diag: &mut DiagnosticBuilder<'_>,
1296     path_str: &str,
1297     dox: &str,
1298     sp: Option<rustc_span::Span>,
1299     link_range: &Option<Range<usize>>,
1300 ) {
1301     let (action, mut suggestion) = disambiguator.display_for(path_str);
1302     let help = format!("to link to the {}, {}", disambiguator.descr(), action);
1303
1304     if let Some(sp) = sp {
1305         let link_range = link_range.as_ref().expect("must have a link range if we have a span");
1306         if dox.bytes().nth(link_range.start) == Some(b'`') {
1307             suggestion = format!("`{}`", suggestion);
1308         }
1309
1310         diag.span_suggestion(sp, &help, suggestion, Applicability::MaybeIncorrect);
1311     } else {
1312         diag.help(&format!("{}: {}", help, suggestion));
1313     }
1314 }
1315
1316 fn privacy_error(
1317     cx: &DocContext<'_>,
1318     item: &Item,
1319     path_str: &str,
1320     dox: &str,
1321     link_range: Option<Range<usize>>,
1322 ) {
1323     let item_name = item.name.as_deref().unwrap_or("<unknown>");
1324     let msg =
1325         format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1326
1327     report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1328         if let Some(sp) = sp {
1329             diag.span_label(sp, "this item is private");
1330         }
1331
1332         let note_msg = if cx.render_options.document_private {
1333             "this link resolves only because you passed `--document-private-items`, but will break without"
1334         } else {
1335             "this link will resolve properly if you pass `--document-private-items`"
1336         };
1337         diag.note(note_msg);
1338     });
1339 }
1340
1341 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1342 fn handle_variant(
1343     cx: &DocContext<'_>,
1344     res: Res,
1345     extra_fragment: &Option<String>,
1346 ) -> Result<(Res, Option<String>), ErrorKind> {
1347     use rustc_middle::ty::DefIdTree;
1348
1349     if extra_fragment.is_some() {
1350         return Err(ErrorKind::AnchorFailure(AnchorFailure::Variant));
1351     }
1352     let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
1353         parent
1354     } else {
1355         return Err(ErrorKind::ResolutionFailure);
1356     };
1357     let parent_def = Res::Def(DefKind::Enum, parent);
1358     let variant = cx.tcx.expect_variant_res(res);
1359     Ok((parent_def, Some(format!("variant.{}", variant.ident.name))))
1360 }
1361
1362 const PRIMITIVES: &[(&str, Res)] = &[
1363     ("u8", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
1364     ("u16", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
1365     ("u32", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
1366     ("u64", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
1367     ("u128", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
1368     ("usize", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
1369     ("i8", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
1370     ("i16", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
1371     ("i32", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
1372     ("i64", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
1373     ("i128", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
1374     ("isize", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
1375     ("f32", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
1376     ("f64", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
1377     ("str", Res::PrimTy(hir::PrimTy::Str)),
1378     ("bool", Res::PrimTy(hir::PrimTy::Bool)),
1379     ("true", Res::PrimTy(hir::PrimTy::Bool)),
1380     ("false", Res::PrimTy(hir::PrimTy::Bool)),
1381     ("char", Res::PrimTy(hir::PrimTy::Char)),
1382 ];
1383
1384 fn is_primitive(path_str: &str, ns: Namespace) -> Option<(&'static str, Res)> {
1385     if ns == TypeNS {
1386         PRIMITIVES
1387             .iter()
1388             .filter(|x| x.0 == path_str)
1389             .copied()
1390             .map(|x| if x.0 == "true" || x.0 == "false" { ("bool", x.1) } else { x })
1391             .next()
1392     } else {
1393         None
1394     }
1395 }
1396
1397 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<&'static SmallVec<[DefId; 4]>> {
1398     Some(PrimitiveType::from_symbol(Symbol::intern(path_str))?.impls(cx.tcx))
1399 }