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