]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_intra_doc_links.rs
Fix font color for help button in ayu and dark themes
[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) => {
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                     Some(ns @ TypeNS) => {
664                         match self.resolve(
665                             path_str,
666                             disambiguator,
667                             ns,
668                             &current_item,
669                             base_node,
670                             &extra_fragment,
671                             Some(&item),
672                         ) {
673                             Ok(res) => res,
674                             Err(ErrorKind::ResolutionFailure) => {
675                                 resolution_failure(cx, &item, path_str, &dox, link_range);
676                                 // This could just be a normal link.
677                                 continue;
678                             }
679                             Err(ErrorKind::AnchorFailure(msg)) => {
680                                 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
681                                 continue;
682                             }
683                         }
684                     }
685                     None => {
686                         // Try everything!
687                         let mut candidates = PerNS {
688                             macro_ns: self
689                                 .macro_resolve(path_str, base_node)
690                                 .map(|res| (res, extra_fragment.clone())),
691                             type_ns: match self.resolve(
692                                 path_str,
693                                 disambiguator,
694                                 TypeNS,
695                                 &current_item,
696                                 base_node,
697                                 &extra_fragment,
698                                 Some(&item),
699                             ) {
700                                 Err(ErrorKind::AnchorFailure(msg)) => {
701                                     anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
702                                     continue;
703                                 }
704                                 x => x.ok(),
705                             },
706                             value_ns: match self.resolve(
707                                 path_str,
708                                 disambiguator,
709                                 ValueNS,
710                                 &current_item,
711                                 base_node,
712                                 &extra_fragment,
713                                 Some(&item),
714                             ) {
715                                 Err(ErrorKind::AnchorFailure(msg)) => {
716                                     anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
717                                     continue;
718                                 }
719                                 x => x.ok(),
720                             }
721                             .and_then(|(res, fragment)| {
722                                 // Constructors are picked up in the type namespace.
723                                 match res {
724                                     Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
725                                     _ => match (fragment, extra_fragment) {
726                                         (Some(fragment), Some(_)) => {
727                                             // Shouldn't happen but who knows?
728                                             Some((res, Some(fragment)))
729                                         }
730                                         (fragment, None) | (None, fragment) => {
731                                             Some((res, fragment))
732                                         }
733                                     },
734                                 }
735                             }),
736                         };
737
738                         if candidates.is_empty() {
739                             resolution_failure(cx, &item, path_str, &dox, link_range);
740                             // this could just be a normal link
741                             continue;
742                         }
743
744                         let len = candidates.clone().present_items().count();
745
746                         if len == 1 {
747                             candidates.present_items().next().unwrap()
748                         } else if len == 2 && is_derive_trait_collision(&candidates) {
749                             candidates.type_ns.unwrap()
750                         } else {
751                             if is_derive_trait_collision(&candidates) {
752                                 candidates.macro_ns = None;
753                             }
754                             ambiguity_error(
755                                 cx,
756                                 &item,
757                                 path_str,
758                                 &dox,
759                                 link_range,
760                                 candidates.map(|candidate| candidate.map(|(res, _)| res)),
761                             );
762                             continue;
763                         }
764                     }
765                     Some(MacroNS) => {
766                         if let Some(res) = self.macro_resolve(path_str, base_node) {
767                             (res, extra_fragment)
768                         } else {
769                             resolution_failure(cx, &item, path_str, &dox, link_range);
770                             continue;
771                         }
772                     }
773                 }
774             };
775
776             if let Res::PrimTy(_) = res {
777                 item.attrs.links.push((ori_link, None, fragment));
778             } else {
779                 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
780
781                 // Disallow e.g. linking to enums with `struct@`
782                 if let Res::Def(kind, id) = res {
783                     debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
784                     match (self.kind_side_channel.take().unwrap_or(kind), disambiguator) {
785                         | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
786                         // NOTE: this allows 'method' to mean both normal functions and associated functions
787                         // This can't cause ambiguity because both are in the same namespace.
788                         | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
789                         // These are namespaces; allow anything in the namespace to match
790                         | (_, Some(Disambiguator::Namespace(_)))
791                         // If no disambiguator given, allow anything
792                         | (_, None)
793                         // All of these are valid, so do nothing
794                         => {}
795                         (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
796                         (_, Some(Disambiguator::Kind(expected))) => {
797                             // The resolved item did not match the disambiguator; give a better error than 'not found'
798                             let msg = format!("incompatible link kind for `{}`", path_str);
799                             report_diagnostic(cx, &msg, &item, &dox, link_range, |diag, sp| {
800                                 // HACK(jynelson): by looking at the source I saw the DefId we pass
801                                 // for `expected.descr()` doesn't matter, since it's not a crate
802                                 let note = format!("this link resolved to {} {}, which is not {} {}", kind.article(), kind.descr(id), expected.article(), expected.descr(id));
803                                 let suggestion = Disambiguator::display_for(kind, path_str);
804                                 let help_msg = format!("to link to the {}, use its disambiguator", kind.descr(id));
805                                 diag.note(&note);
806                                 if let Some(sp) = sp {
807                                     diag.span_suggestion(sp, &help_msg, suggestion, Applicability::MaybeIncorrect);
808                                 } else {
809                                     diag.help(&format!("{}: {}", help_msg, suggestion));
810                                 }
811                             });
812                             continue;
813                         }
814                     }
815                 }
816
817                 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
818                 if let Some((src_id, dst_id)) = res
819                     .opt_def_id()
820                     .and_then(|def_id| def_id.as_local())
821                     .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
822                 {
823                     use rustc_hir::def_id::LOCAL_CRATE;
824
825                     let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
826                     let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
827
828                     if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
829                         && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
830                     {
831                         privacy_error(cx, &item, &path_str, &dox, link_range);
832                         continue;
833                     }
834                 }
835                 let id = register_res(cx, res);
836                 item.attrs.links.push((ori_link, Some(id), fragment));
837             }
838         }
839
840         if item.is_mod() && !item.attrs.inner_docs {
841             self.mod_ids.push(item.def_id);
842         }
843
844         if item.is_mod() {
845             let ret = self.fold_item_recur(item);
846
847             self.mod_ids.pop();
848
849             ret
850         } else {
851             self.fold_item_recur(item)
852         }
853     }
854
855     // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
856     // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
857     // will never resolve properly
858     fn fold_crate(&mut self, mut c: Crate) -> Crate {
859         c.module = c.module.take().and_then(|module| self.fold_item(module));
860
861         c
862     }
863 }
864
865 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
866 enum Disambiguator {
867     Kind(DefKind),
868     Namespace(Namespace),
869 }
870
871 impl Disambiguator {
872     /// (disambiguator, path_str)
873     fn from_str(link: &str) -> Result<(Self, &str), ()> {
874         use Disambiguator::{Kind, Namespace as NS};
875
876         let find_suffix = || {
877             let suffixes = [
878                 ("!()", DefKind::Macro(MacroKind::Bang)),
879                 ("()", DefKind::Fn),
880                 ("!", DefKind::Macro(MacroKind::Bang)),
881             ];
882             for &(suffix, kind) in &suffixes {
883                 if link.ends_with(suffix) {
884                     return Ok((Kind(kind), link.trim_end_matches(suffix)));
885                 }
886             }
887             Err(())
888         };
889
890         if let Some(idx) = link.find('@') {
891             let (prefix, rest) = link.split_at(idx);
892             let d = match prefix {
893                 "struct" => Kind(DefKind::Struct),
894                 "enum" => Kind(DefKind::Enum),
895                 "trait" => Kind(DefKind::Trait),
896                 "union" => Kind(DefKind::Union),
897                 "module" | "mod" => Kind(DefKind::Mod),
898                 "const" | "constant" => Kind(DefKind::Const),
899                 "static" => Kind(DefKind::Static),
900                 "function" | "fn" | "method" => Kind(DefKind::Fn),
901                 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
902                 "type" => NS(Namespace::TypeNS),
903                 "value" => NS(Namespace::ValueNS),
904                 "macro" => NS(Namespace::MacroNS),
905                 _ => return find_suffix(),
906             };
907             Ok((d, &rest[1..]))
908         } else {
909             find_suffix()
910         }
911     }
912
913     fn display_for(kind: DefKind, path_str: &str) -> String {
914         if kind == DefKind::Macro(MacroKind::Bang) {
915             return format!("{}!", path_str);
916         } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
917             return format!("{}()", path_str);
918         }
919         let prefix = match kind {
920             DefKind::Struct => "struct",
921             DefKind::Enum => "enum",
922             DefKind::Trait => "trait",
923             DefKind::Union => "union",
924             DefKind::Mod => "mod",
925             DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
926                 "const"
927             }
928             DefKind::Static => "static",
929             DefKind::Macro(MacroKind::Derive) => "derive",
930             // Now handle things that don't have a specific disambiguator
931             _ => match kind
932                 .ns()
933                 .expect("tried to calculate a disambiguator for a def without a namespace?")
934             {
935                 Namespace::TypeNS => "type",
936                 Namespace::ValueNS => "value",
937                 Namespace::MacroNS => "macro",
938             },
939         };
940         format!("{}@{}", prefix, path_str)
941     }
942
943     fn ns(self) -> Namespace {
944         match self {
945             Self::Namespace(n) => n,
946             Self::Kind(k) => {
947                 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
948             }
949         }
950     }
951 }
952
953 /// Reports a diagnostic for an intra-doc link.
954 ///
955 /// If no link range is provided, or the source span of the link cannot be determined, the span of
956 /// the entire documentation block is used for the lint. If a range is provided but the span
957 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
958 ///
959 /// The `decorate` callback is invoked in all cases to allow further customization of the
960 /// diagnostic before emission. If the span of the link was able to be determined, the second
961 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
962 /// to it.
963 fn report_diagnostic(
964     cx: &DocContext<'_>,
965     msg: &str,
966     item: &Item,
967     dox: &str,
968     link_range: Option<Range<usize>>,
969     decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
970 ) {
971     let hir_id = match cx.as_local_hir_id(item.def_id) {
972         Some(hir_id) => hir_id,
973         None => {
974             // If non-local, no need to check anything.
975             info!("ignoring warning from parent crate: {}", msg);
976             return;
977         }
978     };
979
980     let attrs = &item.attrs;
981     let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
982
983     cx.tcx.struct_span_lint_hir(lint::builtin::BROKEN_INTRA_DOC_LINKS, hir_id, sp, |lint| {
984         let mut diag = lint.build(msg);
985
986         let span = link_range
987             .as_ref()
988             .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
989
990         if let Some(link_range) = link_range {
991             if let Some(sp) = span {
992                 diag.set_span(sp);
993             } else {
994                 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
995                 //                       ^     ~~~~
996                 //                       |     link_range
997                 //                       last_new_line_offset
998                 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
999                 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1000
1001                 // Print the line containing the `link_range` and manually mark it with '^'s.
1002                 diag.note(&format!(
1003                     "the link appears in this line:\n\n{line}\n\
1004                          {indicator: <before$}{indicator:^<found$}",
1005                     line = line,
1006                     indicator = "",
1007                     before = link_range.start - last_new_line_offset,
1008                     found = link_range.len(),
1009                 ));
1010             }
1011         }
1012
1013         decorate(&mut diag, span);
1014
1015         diag.emit();
1016     });
1017 }
1018
1019 fn resolution_failure(
1020     cx: &DocContext<'_>,
1021     item: &Item,
1022     path_str: &str,
1023     dox: &str,
1024     link_range: Option<Range<usize>>,
1025 ) {
1026     report_diagnostic(
1027         cx,
1028         &format!("unresolved link to `{}`", path_str),
1029         item,
1030         dox,
1031         link_range,
1032         |diag, sp| {
1033             if let Some(sp) = sp {
1034                 diag.span_label(sp, "unresolved link");
1035             }
1036
1037             diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1038         },
1039     );
1040 }
1041
1042 fn anchor_failure(
1043     cx: &DocContext<'_>,
1044     item: &Item,
1045     path_str: &str,
1046     dox: &str,
1047     link_range: Option<Range<usize>>,
1048     failure: AnchorFailure,
1049 ) {
1050     let msg = match failure {
1051         AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1052         AnchorFailure::Primitive
1053         | AnchorFailure::Variant
1054         | AnchorFailure::AssocConstant
1055         | AnchorFailure::AssocType
1056         | AnchorFailure::Field
1057         | AnchorFailure::Method => {
1058             let kind = match failure {
1059                 AnchorFailure::Primitive => "primitive type",
1060                 AnchorFailure::Variant => "enum variant",
1061                 AnchorFailure::AssocConstant => "associated constant",
1062                 AnchorFailure::AssocType => "associated type",
1063                 AnchorFailure::Field => "struct field",
1064                 AnchorFailure::Method => "method",
1065                 AnchorFailure::MultipleAnchors => unreachable!("should be handled already"),
1066             };
1067
1068             format!(
1069                 "`{}` contains an anchor, but links to {kind}s are already anchored",
1070                 path_str,
1071                 kind = kind
1072             )
1073         }
1074     };
1075
1076     report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1077         if let Some(sp) = sp {
1078             diag.span_label(sp, "contains invalid anchor");
1079         }
1080     });
1081 }
1082
1083 fn ambiguity_error(
1084     cx: &DocContext<'_>,
1085     item: &Item,
1086     path_str: &str,
1087     dox: &str,
1088     link_range: Option<Range<usize>>,
1089     candidates: PerNS<Option<Res>>,
1090 ) {
1091     let mut msg = format!("`{}` is ", path_str);
1092
1093     let candidates = [TypeNS, ValueNS, MacroNS]
1094         .iter()
1095         .filter_map(|&ns| candidates[ns].map(|res| (res, ns)))
1096         .collect::<Vec<_>>();
1097     match candidates.as_slice() {
1098         [(first_def, _), (second_def, _)] => {
1099             msg += &format!(
1100                 "both {} {} and {} {}",
1101                 first_def.article(),
1102                 first_def.descr(),
1103                 second_def.article(),
1104                 second_def.descr(),
1105             );
1106         }
1107         _ => {
1108             let mut candidates = candidates.iter().peekable();
1109             while let Some((res, _)) = candidates.next() {
1110                 if candidates.peek().is_some() {
1111                     msg += &format!("{} {}, ", res.article(), res.descr());
1112                 } else {
1113                     msg += &format!("and {} {}", res.article(), res.descr());
1114                 }
1115             }
1116         }
1117     }
1118
1119     report_diagnostic(cx, &msg, item, dox, link_range.clone(), |diag, sp| {
1120         if let Some(sp) = sp {
1121             diag.span_label(sp, "ambiguous link");
1122
1123             let link_range = link_range.expect("must have a link range if we have a span");
1124
1125             for (res, ns) in candidates {
1126                 let (action, mut suggestion) = match res {
1127                     Res::Def(DefKind::AssocFn | DefKind::Fn, _) => {
1128                         ("add parentheses", format!("{}()", path_str))
1129                     }
1130                     Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1131                         ("add an exclamation mark", format!("{}!", path_str))
1132                     }
1133                     _ => {
1134                         let type_ = match (res, ns) {
1135                             (Res::Def(DefKind::Const, _), _) => "const",
1136                             (Res::Def(DefKind::Static, _), _) => "static",
1137                             (Res::Def(DefKind::Struct, _), _) => "struct",
1138                             (Res::Def(DefKind::Enum, _), _) => "enum",
1139                             (Res::Def(DefKind::Union, _), _) => "union",
1140                             (Res::Def(DefKind::Trait, _), _) => "trait",
1141                             (Res::Def(DefKind::Mod, _), _) => "module",
1142                             (_, TypeNS) => "type",
1143                             (_, ValueNS) => "value",
1144                             (Res::Def(DefKind::Macro(MacroKind::Derive), _), MacroNS) => "derive",
1145                             (_, MacroNS) => "macro",
1146                         };
1147
1148                         // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1149                         ("prefix with the item type", format!("{}@{}", type_, path_str))
1150                     }
1151                 };
1152
1153                 if dox.bytes().nth(link_range.start) == Some(b'`') {
1154                     suggestion = format!("`{}`", suggestion);
1155                 }
1156
1157                 // FIXME: Create a version of this suggestion for when we don't have the span.
1158                 diag.span_suggestion(
1159                     sp,
1160                     &format!("to link to the {}, {}", res.descr(), action),
1161                     suggestion,
1162                     Applicability::MaybeIncorrect,
1163                 );
1164             }
1165         }
1166     });
1167 }
1168
1169 fn privacy_error(
1170     cx: &DocContext<'_>,
1171     item: &Item,
1172     path_str: &str,
1173     dox: &str,
1174     link_range: Option<Range<usize>>,
1175 ) {
1176     let item_name = item.name.as_deref().unwrap_or("<unknown>");
1177     let msg =
1178         format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1179
1180     report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1181         if let Some(sp) = sp {
1182             diag.span_label(sp, "this item is private");
1183         }
1184
1185         let note_msg = if cx.render_options.document_private {
1186             "this link resolves only because you passed `--document-private-items`, but will break without"
1187         } else {
1188             "this link will resolve properly if you pass `--document-private-items`"
1189         };
1190         diag.note(note_msg);
1191     });
1192 }
1193
1194 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1195 fn handle_variant(
1196     cx: &DocContext<'_>,
1197     res: Res,
1198     extra_fragment: &Option<String>,
1199 ) -> Result<(Res, Option<String>), ErrorKind> {
1200     use rustc_middle::ty::DefIdTree;
1201
1202     if extra_fragment.is_some() {
1203         return Err(ErrorKind::AnchorFailure(AnchorFailure::Variant));
1204     }
1205     let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
1206         parent
1207     } else {
1208         return Err(ErrorKind::ResolutionFailure);
1209     };
1210     let parent_def = Res::Def(DefKind::Enum, parent);
1211     let variant = cx.tcx.expect_variant_res(res);
1212     Ok((parent_def, Some(format!("variant.{}", variant.ident.name))))
1213 }
1214
1215 const PRIMITIVES: &[(&str, Res)] = &[
1216     ("u8", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
1217     ("u16", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
1218     ("u32", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
1219     ("u64", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
1220     ("u128", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
1221     ("usize", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
1222     ("i8", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
1223     ("i16", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
1224     ("i32", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
1225     ("i64", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
1226     ("i128", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
1227     ("isize", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
1228     ("f32", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
1229     ("f64", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
1230     ("str", Res::PrimTy(hir::PrimTy::Str)),
1231     ("bool", Res::PrimTy(hir::PrimTy::Bool)),
1232     ("true", Res::PrimTy(hir::PrimTy::Bool)),
1233     ("false", Res::PrimTy(hir::PrimTy::Bool)),
1234     ("char", Res::PrimTy(hir::PrimTy::Char)),
1235 ];
1236
1237 fn is_primitive(path_str: &str, ns: Namespace) -> Option<(&'static str, Res)> {
1238     if ns == TypeNS {
1239         PRIMITIVES
1240             .iter()
1241             .filter(|x| x.0 == path_str)
1242             .copied()
1243             .map(|x| if x.0 == "true" || x.0 == "false" { ("bool", x.1) } else { x })
1244             .next()
1245     } else {
1246         None
1247     }
1248 }
1249
1250 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<&'static SmallVec<[DefId; 4]>> {
1251     Some(PrimitiveType::from_symbol(Symbol::intern(path_str))?.impls(cx.tcx))
1252 }