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