2 use rustc_errors::{Applicability, DiagnosticBuilder};
3 use rustc_expand::base::SyntaxExtensionKind;
4 use rustc_feature::UnstableFeatures;
11 use rustc_hir::def_id::DefId;
13 use rustc_resolve::ParentScope;
14 use rustc_session::lint;
15 use rustc_span::hygiene::MacroKind;
16 use rustc_span::symbol::Ident;
17 use rustc_span::symbol::Symbol;
18 use rustc_span::DUMMY_SP;
19 use smallvec::SmallVec;
25 use crate::core::DocContext;
26 use crate::fold::DocFolder;
27 use crate::html::markdown::markdown_links;
28 use crate::passes::Pass;
30 use super::span_of_attrs;
32 pub const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
33 name: "collect-intra-doc-links",
34 run: collect_intra_doc_links,
35 description: "reads a crate's documentation to resolve intra-doc-links",
38 pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
39 if !UnstableFeatures::from_environment().is_nightly_build() {
42 let mut coll = LinkCollector::new(cx);
44 coll.fold_crate(krate)
50 AnchorFailure(AnchorFailure),
63 struct LinkCollector<'a, 'tcx> {
64 cx: &'a DocContext<'tcx>,
65 // NOTE: this may not necessarily be a module in the current crate
67 /// This is used to store the kind of associated items,
68 /// because `clean` and the disambiguator code expect them to be different.
69 /// See the code for associated items on inherent impls for details.
70 kind_side_channel: Cell<Option<DefKind>>,
73 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
74 fn new(cx: &'a DocContext<'tcx>) -> Self {
75 LinkCollector { cx, mod_ids: Vec::new(), kind_side_channel: Cell::new(None) }
81 current_item: &Option<String>,
83 ) -> Result<(Res, Option<String>), ErrorKind> {
86 let mut split = path_str.rsplitn(3, "::");
87 let variant_field_name =
88 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
90 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
94 if f == "self" || f == "Self" {
95 if let Some(name) = current_item.as_ref() {
101 .ok_or(ErrorKind::ResolutionFailure)?;
103 .enter_resolver(|resolver| {
104 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
106 .map_err(|_| ErrorKind::ResolutionFailure)?;
107 if let Res::Err = ty_res {
108 return Err(ErrorKind::ResolutionFailure);
110 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
112 Res::Def(DefKind::Enum, did) => {
117 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
118 .any(|item| item.ident.name == variant_name)
120 return Err(ErrorKind::ResolutionFailure);
122 match cx.tcx.type_of(did).kind {
123 ty::Adt(def, _) if def.is_enum() => {
124 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
128 "variant.{}.field.{}",
129 variant_name, variant_field_name
133 Err(ErrorKind::ResolutionFailure)
136 _ => Err(ErrorKind::ResolutionFailure),
139 _ => Err(ErrorKind::ResolutionFailure),
143 /// Resolves a string as a macro.
144 fn macro_resolve(&self, path_str: &str, parent_id: Option<DefId>) -> Option<Res> {
146 let path = ast::Path::from_ident(Ident::from_str(path_str));
147 cx.enter_resolver(|resolver| {
148 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
151 &ParentScope::module(resolver.graph_root()),
155 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
156 return Some(res.map_id(|_| panic!("unexpected id")));
159 if let Some(res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
160 return Some(res.map_id(|_| panic!("unexpected id")));
162 if let Some(module_id) = parent_id {
163 if let Ok((_, res)) =
164 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
166 // don't resolve builtins like `#[derive]`
167 if let Res::Def(..) = res {
168 let res = res.map_id(|_| panic!("unexpected node_id"));
173 debug!("attempting to resolve item without parent module: {}", path_str);
178 /// Resolves a string as a path within a particular namespace. Also returns an optional
179 /// URL fragment in the case of variants and methods.
183 disambiguator: Option<Disambiguator>,
185 current_item: &Option<String>,
186 parent_id: Option<DefId>,
187 extra_fragment: &Option<String>,
188 item_opt: Option<&Item>,
189 ) -> Result<(Res, Option<String>), ErrorKind> {
192 // In case we're in a module, try to resolve the relative path.
193 if let Some(module_id) = parent_id {
194 let result = cx.enter_resolver(|resolver| {
195 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
197 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
198 let result = match result {
199 Ok((_, Res::Err)) => Err(ErrorKind::ResolutionFailure),
200 _ => result.map_err(|_| ErrorKind::ResolutionFailure),
203 if let Ok((_, res)) = result {
204 let res = res.map_id(|_| panic!("unexpected node_id"));
205 // In case this is a trait item, skip the
206 // early return and try looking for the trait.
207 let value = match res {
208 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => true,
209 Res::Def(DefKind::AssocTy, _) => false,
210 Res::Def(DefKind::Variant, _) => {
211 return handle_variant(cx, res, extra_fragment);
213 // Not a trait item; just return what we found.
215 if extra_fragment.is_some() {
216 return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
218 return Ok((res, Some(path_str.to_owned())));
220 Res::Def(DefKind::Mod, _) => {
221 // This resolved to a module, but we want primitive types to take precedence instead.
224 None | Some(Disambiguator::Namespace(Namespace::TypeNS))
226 if let Some((path, prim)) = is_primitive(path_str, ns) {
227 if extra_fragment.is_some() {
228 return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
230 return Ok((prim, Some(path.to_owned())));
233 return Ok((res, extra_fragment.clone()));
236 return Ok((res, extra_fragment.clone()));
240 if value != (ns == ValueNS) {
241 return Err(ErrorKind::ResolutionFailure);
243 } else if let Some((path, prim)) = is_primitive(path_str, ns) {
244 if extra_fragment.is_some() {
245 return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
247 return Ok((prim, Some(path.to_owned())));
249 // If resolution failed, it may still be a method
250 // because methods are not handled by the resolver
251 // If so, bail when we're not looking for a value.
253 return Err(ErrorKind::ResolutionFailure);
257 // Try looking for methods and associated items.
258 let mut split = path_str.rsplitn(2, "::");
260 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
264 if f == "self" || f == "Self" {
265 if let Some(name) = current_item.as_ref() {
271 .ok_or(ErrorKind::ResolutionFailure)?;
273 if let Some((path, prim)) = is_primitive(&path, TypeNS) {
274 for &impl_ in primitive_impl(cx, &path).ok_or(ErrorKind::ResolutionFailure)? {
277 .associated_items(impl_)
278 .find_by_name_and_namespace(
280 Ident::with_dummy_span(item_name),
284 .and_then(|item| match item.kind {
285 ty::AssocKind::Fn => Some("method"),
288 .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name))));
289 if let Some(link) = link {
293 return Err(ErrorKind::ResolutionFailure);
297 .enter_resolver(|resolver| {
298 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
300 .map_err(|_| ErrorKind::ResolutionFailure)?;
301 if let Res::Err = ty_res {
302 return self.variant_field(path_str, current_item, module_id);
304 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
307 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::TyAlias,
310 // Checks if item_name belongs to `impl SomeItem`
315 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
316 .find(|item| item.ident.name == item_name);
317 let trait_item = item_opt
318 .and_then(|item| self.cx.as_local_hir_id(item.def_id))
319 .and_then(|item_hir| {
320 // Checks if item_name belongs to `impl SomeTrait for SomeItem`
321 let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
322 let item_parent = self.cx.tcx.hir().find(parent_hir);
324 Some(hir::Node::Item(hir::Item {
325 kind: hir::ItemKind::Impl { of_trait: Some(_), self_ty, .. },
329 .associated_item_def_ids(self_ty.hir_id.owner)
332 let associated_item = cx.tcx.associated_item(*child);
335 .find(|child| child.ident.name == item_name),
339 let item = match (impl_item, trait_item) {
340 (Some(from_impl), Some(_)) => {
341 // Although it's ambiguous, return impl version for compat. sake.
342 // To handle that properly resolve() would have to support
344 // [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
347 (None, Some(from_trait)) => Some(from_trait),
348 (Some(from_impl), None) => Some(from_impl),
352 if let Some(item) = item {
353 let out = match item.kind {
354 ty::AssocKind::Fn if ns == ValueNS => "method",
355 ty::AssocKind::Const if ns == ValueNS => "associatedconstant",
356 ty::AssocKind::Type if ns == ValueNS => "associatedtype",
357 _ => return self.variant_field(path_str, current_item, module_id),
359 if extra_fragment.is_some() {
360 Err(ErrorKind::AnchorFailure(if item.kind == ty::AssocKind::Fn {
361 AnchorFailure::Method
363 AnchorFailure::AssocConstant
366 // HACK(jynelson): `clean` expects the type, not the associated item.
367 // but the disambiguator logic expects the associated item.
368 // Store the kind in a side channel so that only the disambiguator logic looks at it.
369 self.kind_side_channel.replace(Some(item.kind.as_def_kind()));
370 Ok((ty_res, Some(format!("{}.{}", out, item_name))))
373 match cx.tcx.type_of(did).kind {
375 if let Some(item) = if def.is_enum() {
376 def.all_fields().find(|item| item.ident.name == item_name)
378 def.non_enum_variant()
381 .find(|item| item.ident.name == item_name)
383 if extra_fragment.is_some() {
384 Err(ErrorKind::AnchorFailure(if def.is_enum() {
385 AnchorFailure::Variant
404 self.variant_field(path_str, current_item, module_id)
407 _ => self.variant_field(path_str, current_item, module_id),
411 Res::Def(DefKind::Trait, did) => {
414 .associated_item_def_ids(did)
416 .map(|item| cx.tcx.associated_item(*item))
417 .find(|item| item.ident.name == item_name);
418 if let Some(item) = item {
421 ty::AssocKind::Const if ns == ValueNS => "associatedconstant",
422 ty::AssocKind::Type if ns == TypeNS => "associatedtype",
423 ty::AssocKind::Fn if ns == ValueNS => {
424 if item.defaultness.has_value() { "method" } else { "tymethod" }
426 _ => return self.variant_field(path_str, current_item, module_id),
429 if extra_fragment.is_some() {
430 Err(ErrorKind::AnchorFailure(if item.kind == ty::AssocKind::Const {
431 AnchorFailure::AssocConstant
432 } else if item.kind == ty::AssocKind::Type {
433 AnchorFailure::AssocType
435 AnchorFailure::Method
438 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
439 Ok((res, Some(format!("{}.{}", kind, item_name))))
442 self.variant_field(path_str, current_item, module_id)
445 _ => self.variant_field(path_str, current_item, module_id),
448 debug!("attempting to resolve item without parent module: {}", path_str);
449 Err(ErrorKind::ResolutionFailure)
454 /// Check for resolve collisions between a trait and its derive
456 /// These are common and we should just resolve to the trait in that case
457 fn is_derive_trait_collision<T>(ns: &PerNS<Option<(Res, T)>>) -> bool {
459 type_ns: Some((Res::Def(DefKind::Trait, _), _)),
460 macro_ns: Some((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
470 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
471 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
472 use rustc_middle::ty::DefIdTree;
474 let parent_node = if item.is_fake() {
475 // FIXME: is this correct?
478 let mut current = item.def_id;
479 // The immediate parent might not always be a module.
480 // Find the first parent which is.
482 if let Some(parent) = self.cx.tcx.parent(current) {
483 if self.cx.tcx.def_kind(parent) == DefKind::Mod {
493 if parent_node.is_some() {
494 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
497 let current_item = match item.inner {
499 if item.attrs.inner_docs {
500 if item.def_id.is_top_level_module() { item.name.clone() } else { None }
502 match parent_node.or(self.mod_ids.last().copied()) {
503 Some(parent) if !parent.is_top_level_module() => {
504 // FIXME: can we pull the parent module's name from elsewhere?
505 Some(self.cx.tcx.item_name(parent).to_string())
511 ImplItem(Impl { ref for_, .. }) => {
512 for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
514 // we don't display docs on `extern crate` items anyway, so don't process them.
515 ExternCrateItem(..) => {
516 debug!("ignoring extern crate item {:?}", item.def_id);
517 return self.fold_item_recur(item);
519 ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
520 MacroItem(..) => None,
521 _ => item.name.clone(),
524 if item.is_mod() && item.attrs.inner_docs {
525 self.mod_ids.push(item.def_id);
529 let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
530 trace!("got documentation '{}'", dox);
532 // find item's parent to resolve `Self` in item's docs below
533 let parent_name = self.cx.as_local_hir_id(item.def_id).and_then(|item_hir| {
534 let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
535 let item_parent = self.cx.tcx.hir().find(parent_hir);
537 Some(hir::Node::Item(hir::Item {
539 hir::ItemKind::Impl {
543 hir::TyKind::Path(hir::QPath::Resolved(
545 hir::Path { segments, .. },
552 })) => segments.first().map(|seg| seg.ident.to_string()),
553 Some(hir::Node::Item(hir::Item {
554 ident, kind: hir::ItemKind::Enum(..), ..
556 | Some(hir::Node::Item(hir::Item {
557 ident, kind: hir::ItemKind::Struct(..), ..
559 | Some(hir::Node::Item(hir::Item {
560 ident, kind: hir::ItemKind::Union(..), ..
562 | Some(hir::Node::Item(hir::Item {
563 ident, kind: hir::ItemKind::Trait(..), ..
564 })) => Some(ident.to_string()),
569 for (ori_link, link_range) in markdown_links(&dox) {
570 trace!("considering link '{}'", ori_link);
572 // Bail early for real links.
573 if ori_link.contains('/') {
577 // [] is mostly likely not supposed to be a link
578 if ori_link.is_empty() {
582 let link = ori_link.replace("`", "");
583 let parts = link.split('#').collect::<Vec<_>>();
584 let (link, extra_fragment) = if parts.len() > 2 {
585 anchor_failure(cx, &item, &link, &dox, link_range, AnchorFailure::MultipleAnchors);
587 } else if parts.len() == 2 {
588 if parts[0].trim().is_empty() {
589 // This is an anchor to an element of the current page, nothing to do in here!
592 (parts[0].to_owned(), Some(parts[1].to_owned()))
594 (parts[0].to_owned(), None)
599 let (res, fragment) = {
600 path_str = if let Ok((d, path)) = Disambiguator::from_str(&link) {
601 disambiguator = Some(d);
604 disambiguator = None;
609 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ch == ':' || ch == '_')) {
613 // In order to correctly resolve intra-doc-links we need to
614 // pick a base AST node to work from. If the documentation for
615 // this module came from an inner comment (//!) then we anchor
616 // our name resolution *inside* the module. If, on the other
617 // hand it was an outer comment (///) then we anchor the name
618 // resolution in the parent module on the basis that the names
619 // used are more likely to be intended to be parent names. For
620 // this, we set base_node to None for inner comments since
621 // we've already pushed this node onto the resolution stack but
622 // for outer comments we explicitly try and resolve against the
623 // parent_node first.
624 let base_node = if item.is_mod() && item.attrs.inner_docs {
625 self.mod_ids.last().copied()
630 // replace `Self` with suitable item's parent name
631 if path_str.starts_with("Self::") {
632 if let Some(ref name) = parent_name {
633 resolved_self = format!("{}::{}", name, &path_str[6..]);
634 path_str = &resolved_self;
638 match disambiguator.map(Disambiguator::ns) {
639 Some(ns @ ValueNS) => {
650 Err(ErrorKind::ResolutionFailure) => {
651 resolution_failure(cx, &item, path_str, &dox, link_range);
652 // This could just be a normal link or a broken link
653 // we could potentially check if something is
654 // "intra-doc-link-like" and warn in that case.
657 Err(ErrorKind::AnchorFailure(msg)) => {
658 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
663 Some(ns @ TypeNS) => {
674 Err(ErrorKind::ResolutionFailure) => {
675 resolution_failure(cx, &item, path_str, &dox, link_range);
676 // This could just be a normal link.
679 Err(ErrorKind::AnchorFailure(msg)) => {
680 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
687 let mut candidates = PerNS {
689 .macro_resolve(path_str, base_node)
690 .map(|res| (res, extra_fragment.clone())),
691 type_ns: match self.resolve(
700 Err(ErrorKind::AnchorFailure(msg)) => {
701 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
706 value_ns: match self.resolve(
715 Err(ErrorKind::AnchorFailure(msg)) => {
716 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
721 .and_then(|(res, fragment)| {
722 // Constructors are picked up in the type namespace.
724 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
725 _ => match (fragment, extra_fragment) {
726 (Some(fragment), Some(_)) => {
727 // Shouldn't happen but who knows?
728 Some((res, Some(fragment)))
730 (fragment, None) | (None, fragment) => {
731 Some((res, fragment))
738 if candidates.is_empty() {
739 resolution_failure(cx, &item, path_str, &dox, link_range);
740 // this could just be a normal link
744 let len = candidates.clone().present_items().count();
747 candidates.present_items().next().unwrap()
748 } else if len == 2 && is_derive_trait_collision(&candidates) {
749 candidates.type_ns.unwrap()
751 if is_derive_trait_collision(&candidates) {
752 candidates.macro_ns = None;
760 candidates.map(|candidate| candidate.map(|(res, _)| res)),
766 if let Some(res) = self.macro_resolve(path_str, base_node) {
767 (res, extra_fragment)
769 resolution_failure(cx, &item, path_str, &dox, link_range);
776 if let Res::PrimTy(_) = res {
777 item.attrs.links.push((ori_link, None, fragment));
779 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
781 // Disallow e.g. linking to enums with `struct@`
782 if let Res::Def(kind, id) = res {
783 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
784 match (self.kind_side_channel.take().unwrap_or(kind), disambiguator) {
785 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
786 // NOTE: this allows 'method' to mean both normal functions and associated functions
787 // This can't cause ambiguity because both are in the same namespace.
788 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
789 // These are namespaces; allow anything in the namespace to match
790 | (_, Some(Disambiguator::Namespace(_)))
791 // If no disambiguator given, allow anything
793 // All of these are valid, so do nothing
795 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
796 (_, Some(Disambiguator::Kind(expected))) => {
797 // The resolved item did not match the disambiguator; give a better error than 'not found'
798 let msg = format!("incompatible link kind for `{}`", path_str);
799 report_diagnostic(cx, &msg, &item, &dox, link_range, |diag, sp| {
800 // HACK(jynelson): by looking at the source I saw the DefId we pass
801 // for `expected.descr()` doesn't matter, since it's not a crate
802 let note = format!("this link resolved to {} {}, which is not {} {}", kind.article(), kind.descr(id), expected.article(), expected.descr(id));
803 let suggestion = Disambiguator::display_for(kind, path_str);
804 let help_msg = format!("to link to the {}, use its disambiguator", kind.descr(id));
806 if let Some(sp) = sp {
807 diag.span_suggestion(sp, &help_msg, suggestion, Applicability::MaybeIncorrect);
809 diag.help(&format!("{}: {}", help_msg, suggestion));
817 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
818 if let Some((src_id, dst_id)) = res
820 .and_then(|def_id| def_id.as_local())
821 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
823 use rustc_hir::def_id::LOCAL_CRATE;
825 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
826 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
828 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
829 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
831 privacy_error(cx, &item, &path_str, &dox, link_range);
835 let id = register_res(cx, res);
836 item.attrs.links.push((ori_link, Some(id), fragment));
840 if item.is_mod() && !item.attrs.inner_docs {
841 self.mod_ids.push(item.def_id);
845 let ret = self.fold_item_recur(item);
851 self.fold_item_recur(item)
855 // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
856 // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
857 // will never resolve properly
858 fn fold_crate(&mut self, mut c: Crate) -> Crate {
859 c.module = c.module.take().and_then(|module| self.fold_item(module));
865 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
868 Namespace(Namespace),
872 /// (disambiguator, path_str)
873 fn from_str(link: &str) -> Result<(Self, &str), ()> {
874 use Disambiguator::{Kind, Namespace as NS};
876 let find_suffix = || {
878 ("!()", DefKind::Macro(MacroKind::Bang)),
880 ("!", DefKind::Macro(MacroKind::Bang)),
882 for &(suffix, kind) in &suffixes {
883 if link.ends_with(suffix) {
884 return Ok((Kind(kind), link.trim_end_matches(suffix)));
890 if let Some(idx) = link.find('@') {
891 let (prefix, rest) = link.split_at(idx);
892 let d = match prefix {
893 "struct" => Kind(DefKind::Struct),
894 "enum" => Kind(DefKind::Enum),
895 "trait" => Kind(DefKind::Trait),
896 "union" => Kind(DefKind::Union),
897 "module" | "mod" => Kind(DefKind::Mod),
898 "const" | "constant" => Kind(DefKind::Const),
899 "static" => Kind(DefKind::Static),
900 "function" | "fn" | "method" => Kind(DefKind::Fn),
901 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
902 "type" => NS(Namespace::TypeNS),
903 "value" => NS(Namespace::ValueNS),
904 "macro" => NS(Namespace::MacroNS),
905 _ => return find_suffix(),
913 fn display_for(kind: DefKind, path_str: &str) -> String {
914 if kind == DefKind::Macro(MacroKind::Bang) {
915 return format!("{}!", path_str);
916 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
917 return format!("{}()", path_str);
919 let prefix = match kind {
920 DefKind::Struct => "struct",
921 DefKind::Enum => "enum",
922 DefKind::Trait => "trait",
923 DefKind::Union => "union",
924 DefKind::Mod => "mod",
925 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
928 DefKind::Static => "static",
929 DefKind::Macro(MacroKind::Derive) => "derive",
930 // Now handle things that don't have a specific disambiguator
933 .expect("tried to calculate a disambiguator for a def without a namespace?")
935 Namespace::TypeNS => "type",
936 Namespace::ValueNS => "value",
937 Namespace::MacroNS => "macro",
940 format!("{}@{}", prefix, path_str)
943 fn ns(self) -> Namespace {
945 Self::Namespace(n) => n,
947 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
953 /// Reports a diagnostic for an intra-doc link.
955 /// If no link range is provided, or the source span of the link cannot be determined, the span of
956 /// the entire documentation block is used for the lint. If a range is provided but the span
957 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
959 /// The `decorate` callback is invoked in all cases to allow further customization of the
960 /// diagnostic before emission. If the span of the link was able to be determined, the second
961 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
963 fn report_diagnostic(
968 link_range: Option<Range<usize>>,
969 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
971 let hir_id = match cx.as_local_hir_id(item.def_id) {
972 Some(hir_id) => hir_id,
974 // If non-local, no need to check anything.
975 info!("ignoring warning from parent crate: {}", msg);
980 let attrs = &item.attrs;
981 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
983 cx.tcx.struct_span_lint_hir(lint::builtin::BROKEN_INTRA_DOC_LINKS, hir_id, sp, |lint| {
984 let mut diag = lint.build(msg);
986 let span = link_range
988 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
990 if let Some(link_range) = link_range {
991 if let Some(sp) = span {
994 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
997 // last_new_line_offset
998 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
999 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1001 // Print the line containing the `link_range` and manually mark it with '^'s.
1003 "the link appears in this line:\n\n{line}\n\
1004 {indicator: <before$}{indicator:^<found$}",
1007 before = link_range.start - last_new_line_offset,
1008 found = link_range.len(),
1013 decorate(&mut diag, span);
1019 fn resolution_failure(
1020 cx: &DocContext<'_>,
1024 link_range: Option<Range<usize>>,
1028 &format!("unresolved link to `{}`", path_str),
1033 if let Some(sp) = sp {
1034 diag.span_label(sp, "unresolved link");
1037 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1043 cx: &DocContext<'_>,
1047 link_range: Option<Range<usize>>,
1048 failure: AnchorFailure,
1050 let msg = match failure {
1051 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1052 AnchorFailure::Primitive
1053 | AnchorFailure::Variant
1054 | AnchorFailure::AssocConstant
1055 | AnchorFailure::AssocType
1056 | AnchorFailure::Field
1057 | AnchorFailure::Method => {
1058 let kind = match failure {
1059 AnchorFailure::Primitive => "primitive type",
1060 AnchorFailure::Variant => "enum variant",
1061 AnchorFailure::AssocConstant => "associated constant",
1062 AnchorFailure::AssocType => "associated type",
1063 AnchorFailure::Field => "struct field",
1064 AnchorFailure::Method => "method",
1065 AnchorFailure::MultipleAnchors => unreachable!("should be handled already"),
1069 "`{}` contains an anchor, but links to {kind}s are already anchored",
1076 report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1077 if let Some(sp) = sp {
1078 diag.span_label(sp, "contains invalid anchor");
1084 cx: &DocContext<'_>,
1088 link_range: Option<Range<usize>>,
1089 candidates: PerNS<Option<Res>>,
1091 let mut msg = format!("`{}` is ", path_str);
1093 let candidates = [TypeNS, ValueNS, MacroNS]
1095 .filter_map(|&ns| candidates[ns].map(|res| (res, ns)))
1096 .collect::<Vec<_>>();
1097 match candidates.as_slice() {
1098 [(first_def, _), (second_def, _)] => {
1100 "both {} {} and {} {}",
1101 first_def.article(),
1103 second_def.article(),
1108 let mut candidates = candidates.iter().peekable();
1109 while let Some((res, _)) = candidates.next() {
1110 if candidates.peek().is_some() {
1111 msg += &format!("{} {}, ", res.article(), res.descr());
1113 msg += &format!("and {} {}", res.article(), res.descr());
1119 report_diagnostic(cx, &msg, item, dox, link_range.clone(), |diag, sp| {
1120 if let Some(sp) = sp {
1121 diag.span_label(sp, "ambiguous link");
1123 let link_range = link_range.expect("must have a link range if we have a span");
1125 for (res, ns) in candidates {
1126 let (action, mut suggestion) = match res {
1127 Res::Def(DefKind::AssocFn | DefKind::Fn, _) => {
1128 ("add parentheses", format!("{}()", path_str))
1130 Res::Def(DefKind::Macro(MacroKind::Bang), _) => {
1131 ("add an exclamation mark", format!("{}!", path_str))
1134 let type_ = match (res, ns) {
1135 (Res::Def(DefKind::Const, _), _) => "const",
1136 (Res::Def(DefKind::Static, _), _) => "static",
1137 (Res::Def(DefKind::Struct, _), _) => "struct",
1138 (Res::Def(DefKind::Enum, _), _) => "enum",
1139 (Res::Def(DefKind::Union, _), _) => "union",
1140 (Res::Def(DefKind::Trait, _), _) => "trait",
1141 (Res::Def(DefKind::Mod, _), _) => "module",
1142 (_, TypeNS) => "type",
1143 (_, ValueNS) => "value",
1144 (Res::Def(DefKind::Macro(MacroKind::Derive), _), MacroNS) => "derive",
1145 (_, MacroNS) => "macro",
1148 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1149 ("prefix with the item type", format!("{}@{}", type_, path_str))
1153 if dox.bytes().nth(link_range.start) == Some(b'`') {
1154 suggestion = format!("`{}`", suggestion);
1157 // FIXME: Create a version of this suggestion for when we don't have the span.
1158 diag.span_suggestion(
1160 &format!("to link to the {}, {}", res.descr(), action),
1162 Applicability::MaybeIncorrect,
1170 cx: &DocContext<'_>,
1174 link_range: Option<Range<usize>>,
1176 let item_name = item.name.as_deref().unwrap_or("<unknown>");
1178 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1180 report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1181 if let Some(sp) = sp {
1182 diag.span_label(sp, "this item is private");
1185 let note_msg = if cx.render_options.document_private {
1186 "this link resolves only because you passed `--document-private-items`, but will break without"
1188 "this link will resolve properly if you pass `--document-private-items`"
1190 diag.note(note_msg);
1194 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1196 cx: &DocContext<'_>,
1198 extra_fragment: &Option<String>,
1199 ) -> Result<(Res, Option<String>), ErrorKind> {
1200 use rustc_middle::ty::DefIdTree;
1202 if extra_fragment.is_some() {
1203 return Err(ErrorKind::AnchorFailure(AnchorFailure::Variant));
1205 let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
1208 return Err(ErrorKind::ResolutionFailure);
1210 let parent_def = Res::Def(DefKind::Enum, parent);
1211 let variant = cx.tcx.expect_variant_res(res);
1212 Ok((parent_def, Some(format!("variant.{}", variant.ident.name))))
1215 const PRIMITIVES: &[(&str, Res)] = &[
1216 ("u8", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
1217 ("u16", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
1218 ("u32", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
1219 ("u64", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
1220 ("u128", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
1221 ("usize", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
1222 ("i8", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
1223 ("i16", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
1224 ("i32", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
1225 ("i64", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
1226 ("i128", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
1227 ("isize", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
1228 ("f32", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
1229 ("f64", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
1230 ("str", Res::PrimTy(hir::PrimTy::Str)),
1231 ("bool", Res::PrimTy(hir::PrimTy::Bool)),
1232 ("true", Res::PrimTy(hir::PrimTy::Bool)),
1233 ("false", Res::PrimTy(hir::PrimTy::Bool)),
1234 ("char", Res::PrimTy(hir::PrimTy::Char)),
1237 fn is_primitive(path_str: &str, ns: Namespace) -> Option<(&'static str, Res)> {
1241 .filter(|x| x.0 == path_str)
1243 .map(|x| if x.0 == "true" || x.0 == "false" { ("bool", x.1) } else { x })
1250 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<&'static SmallVec<[DefId; 4]>> {
1251 Some(PrimitiveType::from_symbol(Symbol::intern(path_str))?.impls(cx.tcx))