]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/collect_intra_doc_links.rs
refactor and reword intra-doc link errors
[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::{look_for_tests, 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         look_for_tests(&cx, &dox, &item, true);
512
513         // find item's parent to resolve `Self` in item's docs below
514         let parent_name = self.cx.as_local_hir_id(item.def_id).and_then(|item_hir| {
515             let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
516             let item_parent = self.cx.tcx.hir().find(parent_hir);
517             match item_parent {
518                 Some(hir::Node::Item(hir::Item {
519                     kind:
520                         hir::ItemKind::Impl {
521                             self_ty:
522                                 hir::Ty {
523                                     kind:
524                                         hir::TyKind::Path(hir::QPath::Resolved(
525                                             _,
526                                             hir::Path { segments, .. },
527                                         )),
528                                     ..
529                                 },
530                             ..
531                         },
532                     ..
533                 })) => segments.first().map(|seg| seg.ident.to_string()),
534                 Some(hir::Node::Item(hir::Item {
535                     ident, kind: hir::ItemKind::Enum(..), ..
536                 }))
537                 | Some(hir::Node::Item(hir::Item {
538                     ident, kind: hir::ItemKind::Struct(..), ..
539                 }))
540                 | Some(hir::Node::Item(hir::Item {
541                     ident, kind: hir::ItemKind::Union(..), ..
542                 }))
543                 | Some(hir::Node::Item(hir::Item {
544                     ident, kind: hir::ItemKind::Trait(..), ..
545                 })) => Some(ident.to_string()),
546                 _ => None,
547             }
548         });
549
550         for (ori_link, link_range) in markdown_links(&dox) {
551             trace!("considering link '{}'", ori_link);
552
553             // Bail early for real links.
554             if ori_link.contains('/') {
555                 continue;
556             }
557
558             // [] is mostly likely not supposed to be a link
559             if ori_link.is_empty() {
560                 continue;
561             }
562
563             let link = ori_link.replace("`", "");
564             let parts = link.split('#').collect::<Vec<_>>();
565             let (link, extra_fragment) = if parts.len() > 2 {
566                 anchor_failure(cx, &item, &link, &dox, link_range, AnchorFailure::MultipleAnchors);
567                 continue;
568             } else if parts.len() == 2 {
569                 if parts[0].trim().is_empty() {
570                     // This is an anchor to an element of the current page, nothing to do in here!
571                     continue;
572                 }
573                 (parts[0].to_owned(), Some(parts[1].to_owned()))
574             } else {
575                 (parts[0].to_owned(), None)
576             };
577             let resolved_self;
578             let mut path_str;
579             let (res, fragment) = {
580                 let mut kind = None;
581                 let mut disambiguator = None;
582                 path_str = if let Some(prefix) =
583                     ["struct@", "enum@", "type@", "trait@", "union@", "module@", "mod@"]
584                         .iter()
585                         .find(|p| link.starts_with(**p))
586                 {
587                     kind = Some(TypeNS);
588                     disambiguator = Some(&prefix[..prefix.len() - 1]);
589                     link.trim_start_matches(prefix)
590                 } else if let Some(prefix) =
591                     ["const@", "static@", "value@", "function@", "fn@", "method@"]
592                         .iter()
593                         .find(|p| link.starts_with(**p))
594                 {
595                     kind = Some(ValueNS);
596                     disambiguator = Some(&prefix[..prefix.len() - 1]);
597                     link.trim_start_matches(prefix)
598                 } else if link.ends_with("!()") {
599                     kind = Some(MacroNS);
600                     link.trim_end_matches("!()")
601                 } else if link.ends_with("()") {
602                     kind = Some(ValueNS);
603                     disambiguator = Some("fn");
604                     link.trim_end_matches("()")
605                 } else if link.starts_with("macro@") {
606                     kind = Some(MacroNS);
607                     disambiguator = Some("macro");
608                     link.trim_start_matches("macro@")
609                 } else if link.starts_with("derive@") {
610                     kind = Some(MacroNS);
611                     disambiguator = Some("derive");
612                     link.trim_start_matches("derive@")
613                 } else if link.ends_with('!') {
614                     kind = Some(MacroNS);
615                     disambiguator = Some("macro");
616                     link.trim_end_matches('!')
617                 } else {
618                     &link[..]
619                 }
620                 .trim();
621
622                 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ch == ':' || ch == '_')) {
623                     continue;
624                 }
625
626                 // In order to correctly resolve intra-doc-links we need to
627                 // pick a base AST node to work from.  If the documentation for
628                 // this module came from an inner comment (//!) then we anchor
629                 // our name resolution *inside* the module.  If, on the other
630                 // hand it was an outer comment (///) then we anchor the name
631                 // resolution in the parent module on the basis that the names
632                 // used are more likely to be intended to be parent names.  For
633                 // this, we set base_node to None for inner comments since
634                 // we've already pushed this node onto the resolution stack but
635                 // for outer comments we explicitly try and resolve against the
636                 // parent_node first.
637                 let base_node = if item.is_mod() && item.attrs.inner_docs {
638                     self.mod_ids.last().copied()
639                 } else {
640                     parent_node
641                 };
642
643                 // replace `Self` with suitable item's parent name
644                 if path_str.starts_with("Self::") {
645                     if let Some(ref name) = parent_name {
646                         resolved_self = format!("{}::{}", name, &path_str[6..]);
647                         path_str = &resolved_self;
648                     }
649                 }
650
651                 match kind {
652                     Some(ns @ ValueNS) => {
653                         match self.resolve(
654                             path_str,
655                             disambiguator,
656                             ns,
657                             &current_item,
658                             base_node,
659                             &extra_fragment,
660                             Some(&item),
661                         ) {
662                             Ok(res) => res,
663                             Err(ErrorKind::ResolutionFailure) => {
664                                 resolution_failure(cx, &item, path_str, &dox, link_range);
665                                 // This could just be a normal link or a broken link
666                                 // we could potentially check if something is
667                                 // "intra-doc-link-like" and warn in that case.
668                                 continue;
669                             }
670                             Err(ErrorKind::AnchorFailure(msg)) => {
671                                 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
672                                 continue;
673                             }
674                         }
675                     }
676                     Some(ns @ TypeNS) => {
677                         match self.resolve(
678                             path_str,
679                             disambiguator,
680                             ns,
681                             &current_item,
682                             base_node,
683                             &extra_fragment,
684                             Some(&item),
685                         ) {
686                             Ok(res) => res,
687                             Err(ErrorKind::ResolutionFailure) => {
688                                 resolution_failure(cx, &item, path_str, &dox, link_range);
689                                 // This could just be a normal link.
690                                 continue;
691                             }
692                             Err(ErrorKind::AnchorFailure(msg)) => {
693                                 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
694                                 continue;
695                             }
696                         }
697                     }
698                     None => {
699                         // Try everything!
700                         let mut candidates = PerNS {
701                             macro_ns: self
702                                 .macro_resolve(path_str, base_node)
703                                 .map(|res| (res, extra_fragment.clone())),
704                             type_ns: match self.resolve(
705                                 path_str,
706                                 disambiguator,
707                                 TypeNS,
708                                 &current_item,
709                                 base_node,
710                                 &extra_fragment,
711                                 Some(&item),
712                             ) {
713                                 Err(ErrorKind::AnchorFailure(msg)) => {
714                                     anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
715                                     continue;
716                                 }
717                                 x => x.ok(),
718                             },
719                             value_ns: match self.resolve(
720                                 path_str,
721                                 disambiguator,
722                                 ValueNS,
723                                 &current_item,
724                                 base_node,
725                                 &extra_fragment,
726                                 Some(&item),
727                             ) {
728                                 Err(ErrorKind::AnchorFailure(msg)) => {
729                                     anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
730                                     continue;
731                                 }
732                                 x => x.ok(),
733                             }
734                             .and_then(|(res, fragment)| {
735                                 // Constructors are picked up in the type namespace.
736                                 match res {
737                                     Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
738                                     _ => match (fragment, extra_fragment) {
739                                         (Some(fragment), Some(_)) => {
740                                             // Shouldn't happen but who knows?
741                                             Some((res, Some(fragment)))
742                                         }
743                                         (fragment, None) | (None, fragment) => {
744                                             Some((res, fragment))
745                                         }
746                                     },
747                                 }
748                             }),
749                         };
750
751                         if candidates.is_empty() {
752                             resolution_failure(cx, &item, path_str, &dox, link_range);
753                             // this could just be a normal link
754                             continue;
755                         }
756
757                         let len = candidates.clone().present_items().count();
758
759                         if len == 1 {
760                             candidates.present_items().next().unwrap()
761                         } else if len == 2 && is_derive_trait_collision(&candidates) {
762                             candidates.type_ns.unwrap()
763                         } else {
764                             if is_derive_trait_collision(&candidates) {
765                                 candidates.macro_ns = None;
766                             }
767                             ambiguity_error(
768                                 cx,
769                                 &item,
770                                 path_str,
771                                 &dox,
772                                 link_range,
773                                 candidates.map(|candidate| candidate.map(|(res, _)| res)),
774                             );
775                             continue;
776                         }
777                     }
778                     Some(MacroNS) => {
779                         if let Some(res) = self.macro_resolve(path_str, base_node) {
780                             (res, extra_fragment)
781                         } else {
782                             resolution_failure(cx, &item, path_str, &dox, link_range);
783                             continue;
784                         }
785                     }
786                 }
787             };
788
789             if let Res::PrimTy(_) = res {
790                 item.attrs.links.push((ori_link, None, fragment));
791             } else {
792                 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
793                 if let Some(local) = res.opt_def_id().and_then(|def_id| def_id.as_local()) {
794                     use rustc_hir::def_id::LOCAL_CRATE;
795
796                     let hir_id = self.cx.tcx.hir().as_local_hir_id(local);
797                     if !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_id)
798                         && (item.visibility == Visibility::Public)
799                         && !self.cx.render_options.document_private
800                     {
801                         privacy_error(cx, &item, &path_str, &dox, link_range);
802                         continue;
803                     }
804                 }
805                 let id = register_res(cx, res);
806                 item.attrs.links.push((ori_link, Some(id), fragment));
807             }
808         }
809
810         if item.is_mod() && !item.attrs.inner_docs {
811             self.mod_ids.push(item.def_id);
812         }
813
814         if item.is_mod() {
815             let ret = self.fold_item_recur(item);
816
817             self.mod_ids.pop();
818
819             ret
820         } else {
821             self.fold_item_recur(item)
822         }
823     }
824
825     // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
826     // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
827     // will never resolve properly
828     fn fold_crate(&mut self, mut c: Crate) -> Crate {
829         c.module = c.module.take().and_then(|module| self.fold_item(module));
830
831         c
832     }
833 }
834
835 /// Reports a diagnostic for an intra-doc link.
836 ///
837 /// If no link range is provided, or the source span of the link cannot be determined, the span of
838 /// the entire documentation block is used for the lint. If a range is provided but the span
839 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
840 ///
841 /// The `decorate` callback is invoked in all cases to allow further customization of the
842 /// diagnostic before emission. If the span of the link was able to be determined, the second
843 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
844 /// to it.
845 fn report_diagnostic(
846     cx: &DocContext<'_>,
847     msg: &str,
848     item: &Item,
849     dox: &str,
850     link_range: Option<Range<usize>>,
851     decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
852 ) {
853     let hir_id = match cx.as_local_hir_id(item.def_id) {
854         Some(hir_id) => hir_id,
855         None => {
856             // If non-local, no need to check anything.
857             info!("ignoring warning from parent crate: {}", msg);
858             return;
859         }
860     };
861
862     let attrs = &item.attrs;
863     let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
864
865     cx.tcx.struct_span_lint_hir(
866         lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,
867         hir_id,
868         sp,
869         |lint| {
870             let mut diag = lint.build(msg);
871
872             let span = link_range
873                 .as_ref()
874                 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
875
876             if let Some(link_range) = link_range {
877                 if let Some(sp) = span {
878                     diag.set_span(sp);
879                 } else {
880                     // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
881                     //                       ^     ~~~~
882                     //                       |     link_range
883                     //                       last_new_line_offset
884                     let last_new_line_offset =
885                         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
907 fn resolution_failure(
908     cx: &DocContext<'_>,
909     item: &Item,
910     path_str: &str,
911     dox: &str,
912     link_range: Option<Range<usize>>,
913 ) {
914     report_diagnostic(
915         cx,
916         &format!("unresolved link to `{}`", path_str),
917         item,
918         dox,
919         link_range,
920         |diag, sp| {
921             if let Some(sp) = sp {
922                 diag.span_label(sp, "unresolved link");
923             }
924
925             diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
926         },
927     );
928 }
929
930 fn anchor_failure(
931     cx: &DocContext<'_>,
932     item: &Item,
933     path_str: &str,
934     dox: &str,
935     link_range: Option<Range<usize>>,
936     failure: AnchorFailure,
937 ) {
938     let msg = match failure {
939         AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
940         AnchorFailure::Primitive
941         | AnchorFailure::Variant
942         | AnchorFailure::AssocConstant
943         | AnchorFailure::AssocType
944         | AnchorFailure::Field
945         | AnchorFailure::Method => {
946             let kind = match failure {
947                 AnchorFailure::Primitive => "primitive type",
948                 AnchorFailure::Variant => "enum variant",
949                 AnchorFailure::AssocConstant => "associated constant",
950                 AnchorFailure::AssocType => "associated type",
951                 AnchorFailure::Field => "struct field",
952                 AnchorFailure::Method => "method",
953                 AnchorFailure::MultipleAnchors => unreachable!("should be handled already"),
954             };
955
956             format!(
957                 "`{}` contains an anchor, but links to {kind}s are already anchored",
958                 path_str,
959                 kind = kind
960             )
961         }
962     };
963
964     report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
965         if let Some(sp) = sp {
966             diag.span_label(sp, "contains invalid anchor");
967         }
968     });
969 }
970
971 fn ambiguity_error(
972     cx: &DocContext<'_>,
973     item: &Item,
974     path_str: &str,
975     dox: &str,
976     link_range: Option<Range<usize>>,
977     candidates: PerNS<Option<Res>>,
978 ) {
979     let mut msg = format!("`{}` is ", path_str);
980
981     let candidates = [TypeNS, ValueNS, MacroNS]
982         .iter()
983         .filter_map(|&ns| candidates[ns].map(|res| (res, ns)))
984         .collect::<Vec<_>>();
985     match candidates.as_slice() {
986         [(first_def, _), (second_def, _)] => {
987             msg += &format!(
988                 "both {} {} and {} {}",
989                 first_def.article(),
990                 first_def.descr(),
991                 second_def.article(),
992                 second_def.descr(),
993             );
994         }
995         _ => {
996             let mut candidates = candidates.iter().peekable();
997             while let Some((res, _)) = candidates.next() {
998                 if candidates.peek().is_some() {
999                     msg += &format!("{} {}, ", res.article(), res.descr());
1000                 } else {
1001                     msg += &format!("and {} {}", res.article(), res.descr());
1002                 }
1003             }
1004         }
1005     }
1006
1007     report_diagnostic(cx, &msg, item, dox, link_range.clone(), |diag, sp| {
1008         if let Some(sp) = sp {
1009             diag.span_label(sp, "ambiguous link");
1010
1011             let link_range = link_range.expect("must have a link range if we have a span");
1012
1013             for (res, ns) in candidates {
1014                 let (action, mut suggestion) = match res {
1015                     Res::Def(DefKind::AssocFn | DefKind::Fn, _) => {
1016                         ("add parentheses", format!("{}()", path_str))
1017                     }
1018                     Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1019                         ("add an exclamation mark", format!("{}!", path_str))
1020                     }
1021                     _ => {
1022                         let type_ = match (res, ns) {
1023                             (Res::Def(DefKind::Const, _), _) => "const",
1024                             (Res::Def(DefKind::Static, _), _) => "static",
1025                             (Res::Def(DefKind::Struct, _), _) => "struct",
1026                             (Res::Def(DefKind::Enum, _), _) => "enum",
1027                             (Res::Def(DefKind::Union, _), _) => "union",
1028                             (Res::Def(DefKind::Trait, _), _) => "trait",
1029                             (Res::Def(DefKind::Mod, _), _) => "module",
1030                             (_, TypeNS) => "type",
1031                             (_, ValueNS) => "value",
1032                             (Res::Def(DefKind::Macro(MacroKind::Derive), _), MacroNS) => "derive",
1033                             (_, MacroNS) => "macro",
1034                         };
1035
1036                         // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1037                         ("prefix with the item type", format!("{}@{}", type_, path_str))
1038                     }
1039                 };
1040
1041                 if dox.bytes().nth(link_range.start) == Some(b'`') {
1042                     suggestion = format!("`{}`", suggestion);
1043                 }
1044
1045                 // FIXME: Create a version of this suggestion for when we don't have the span.
1046                 diag.span_suggestion(
1047                     sp,
1048                     &format!("to link to the {}, {}", res.descr(), action),
1049                     suggestion,
1050                     Applicability::MaybeIncorrect,
1051                 );
1052             }
1053         }
1054     });
1055 }
1056
1057 fn privacy_error(
1058     cx: &DocContext<'_>,
1059     item: &Item,
1060     path_str: &str,
1061     dox: &str,
1062     link_range: Option<Range<usize>>,
1063 ) {
1064     let item_name = item.name.as_deref().unwrap_or("<unknown>");
1065     let msg =
1066         format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1067
1068     report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1069         if let Some(sp) = sp {
1070             diag.span_label(sp, "this item is private");
1071         }
1072     });
1073 }
1074
1075 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1076 fn handle_variant(
1077     cx: &DocContext<'_>,
1078     res: Res,
1079     extra_fragment: &Option<String>,
1080 ) -> Result<(Res, Option<String>), ErrorKind> {
1081     use rustc_middle::ty::DefIdTree;
1082
1083     if extra_fragment.is_some() {
1084         return Err(ErrorKind::AnchorFailure(AnchorFailure::Variant));
1085     }
1086     let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
1087         parent
1088     } else {
1089         return Err(ErrorKind::ResolutionFailure);
1090     };
1091     let parent_def = Res::Def(DefKind::Enum, parent);
1092     let variant = cx.tcx.expect_variant_res(res);
1093     Ok((parent_def, Some(format!("variant.{}", variant.ident.name))))
1094 }
1095
1096 const PRIMITIVES: &[(&str, Res)] = &[
1097     ("u8", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U8))),
1098     ("u16", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U16))),
1099     ("u32", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U32))),
1100     ("u64", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U64))),
1101     ("u128", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U128))),
1102     ("usize", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::Usize))),
1103     ("i8", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I8))),
1104     ("i16", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I16))),
1105     ("i32", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I32))),
1106     ("i64", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I64))),
1107     ("i128", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I128))),
1108     ("isize", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::Isize))),
1109     ("f32", Res::PrimTy(hir::PrimTy::Float(rustc_ast::ast::FloatTy::F32))),
1110     ("f64", Res::PrimTy(hir::PrimTy::Float(rustc_ast::ast::FloatTy::F64))),
1111     ("str", Res::PrimTy(hir::PrimTy::Str)),
1112     ("bool", Res::PrimTy(hir::PrimTy::Bool)),
1113     ("char", Res::PrimTy(hir::PrimTy::Char)),
1114 ];
1115
1116 fn is_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
1117     if ns == TypeNS { PRIMITIVES.iter().find(|x| x.0 == path_str).map(|x| x.1) } else { None }
1118 }
1119
1120 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<DefId> {
1121     let tcx = cx.tcx;
1122     match path_str {
1123         "u8" => tcx.lang_items().u8_impl(),
1124         "u16" => tcx.lang_items().u16_impl(),
1125         "u32" => tcx.lang_items().u32_impl(),
1126         "u64" => tcx.lang_items().u64_impl(),
1127         "u128" => tcx.lang_items().u128_impl(),
1128         "usize" => tcx.lang_items().usize_impl(),
1129         "i8" => tcx.lang_items().i8_impl(),
1130         "i16" => tcx.lang_items().i16_impl(),
1131         "i32" => tcx.lang_items().i32_impl(),
1132         "i64" => tcx.lang_items().i64_impl(),
1133         "i128" => tcx.lang_items().i128_impl(),
1134         "isize" => tcx.lang_items().isize_impl(),
1135         "f32" => tcx.lang_items().f32_impl(),
1136         "f64" => tcx.lang_items().f64_impl(),
1137         "str" => tcx.lang_items().str_impl(),
1138         "bool" => tcx.lang_items().bool_impl(),
1139         "char" => tcx.lang_items().char_impl(),
1140         _ => None,
1141     }
1142 }