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