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