2 use rustc_data_structures::stable_set::FxHashSet;
3 use rustc_errors::{Applicability, DiagnosticBuilder};
4 use rustc_expand::base::SyntaxExtensionKind;
5 use rustc_feature::UnstableFeatures;
12 use rustc_hir::def_id::DefId;
14 use rustc_resolve::ParentScope;
15 use rustc_session::lint;
16 use rustc_span::hygiene::MacroKind;
17 use rustc_span::symbol::Ident;
18 use rustc_span::symbol::Symbol;
19 use rustc_span::DUMMY_SP;
20 use smallvec::SmallVec;
26 use crate::core::DocContext;
27 use crate::fold::DocFolder;
28 use crate::html::markdown::markdown_links;
29 use crate::passes::Pass;
31 use super::span_of_attrs;
33 pub const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
34 name: "collect-intra-doc-links",
35 run: collect_intra_doc_links,
36 description: "reads a crate's documentation to resolve intra-doc-links",
39 pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
40 if !UnstableFeatures::from_environment().is_nightly_build() {
43 let mut coll = LinkCollector::new(cx);
45 coll.fold_crate(krate)
51 AnchorFailure(AnchorFailure),
64 struct LinkCollector<'a, 'tcx> {
65 cx: &'a DocContext<'tcx>,
66 // NOTE: this may not necessarily be a module in the current crate
68 /// This is used to store the kind of associated items,
69 /// because `clean` and the disambiguator code expect them to be different.
70 /// See the code for associated items on inherent impls for details.
71 kind_side_channel: Cell<Option<DefKind>>,
74 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
75 fn new(cx: &'a DocContext<'tcx>) -> Self {
76 LinkCollector { cx, mod_ids: Vec::new(), kind_side_channel: Cell::new(None) }
82 current_item: &Option<String>,
84 ) -> Result<(Res, Option<String>), ErrorKind> {
87 let mut split = path_str.rsplitn(3, "::");
88 let variant_field_name =
89 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
91 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
95 if f == "self" || f == "Self" {
96 if let Some(name) = current_item.as_ref() {
102 .ok_or(ErrorKind::ResolutionFailure)?;
104 .enter_resolver(|resolver| {
105 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
107 .map_err(|_| ErrorKind::ResolutionFailure)?;
108 if let Res::Err = ty_res {
109 return Err(ErrorKind::ResolutionFailure);
111 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
113 Res::Def(DefKind::Enum, did) => {
118 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
119 .any(|item| item.ident.name == variant_name)
121 return Err(ErrorKind::ResolutionFailure);
123 match cx.tcx.type_of(did).kind {
124 ty::Adt(def, _) if def.is_enum() => {
125 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
129 "variant.{}.field.{}",
130 variant_name, variant_field_name
134 Err(ErrorKind::ResolutionFailure)
137 _ => Err(ErrorKind::ResolutionFailure),
140 _ => Err(ErrorKind::ResolutionFailure),
144 /// Resolves a string as a macro.
145 fn macro_resolve(&self, path_str: &str, parent_id: Option<DefId>) -> Option<Res> {
147 let path = ast::Path::from_ident(Ident::from_str(path_str));
148 cx.enter_resolver(|resolver| {
149 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
152 &ParentScope::module(resolver.graph_root()),
156 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
157 return Some(res.map_id(|_| panic!("unexpected id")));
160 if let Some(res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
161 return Some(res.map_id(|_| panic!("unexpected id")));
163 if let Some(module_id) = parent_id {
164 if let Ok((_, res)) =
165 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
167 // don't resolve builtins like `#[derive]`
168 if let Res::Def(..) = res {
169 let res = res.map_id(|_| panic!("unexpected node_id"));
174 debug!("attempting to resolve item without parent module: {}", path_str);
179 /// Resolves a string as a path within a particular namespace. Also returns an optional
180 /// URL fragment in the case of variants and methods.
185 current_item: &Option<String>,
186 parent_id: Option<DefId>,
187 extra_fragment: &Option<String>,
188 ) -> Result<(Res, Option<String>), ErrorKind> {
191 // In case we're in a module, try to resolve the relative path.
192 if let Some(module_id) = parent_id {
193 let result = cx.enter_resolver(|resolver| {
194 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
196 debug!("{} resolved to {:?} in namespace {:?}", path_str, result, ns);
197 let result = match result {
198 Ok((_, Res::Err)) => Err(ErrorKind::ResolutionFailure),
199 _ => result.map_err(|_| ErrorKind::ResolutionFailure),
202 if let Ok((_, res)) = result {
203 let res = res.map_id(|_| panic!("unexpected node_id"));
204 // In case this is a trait item, skip the
205 // early return and try looking for the trait.
206 let value = match res {
207 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => true,
208 Res::Def(DefKind::AssocTy, _) => false,
209 Res::Def(DefKind::Variant, _) => {
210 return handle_variant(cx, res, extra_fragment);
212 // Not a trait item; just return what we found.
214 if extra_fragment.is_some() {
215 return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
217 return Ok((res, Some(path_str.to_owned())));
219 Res::Def(DefKind::Mod, _) => {
220 return Ok((res, extra_fragment.clone()));
223 return Ok((res, extra_fragment.clone()));
227 if value != (ns == ValueNS) {
228 return Err(ErrorKind::ResolutionFailure);
230 } else if let Some((path, prim)) = is_primitive(path_str, ns) {
231 if extra_fragment.is_some() {
232 return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
234 return Ok((prim, Some(path.to_owned())));
237 // Try looking for methods and associated items.
238 let mut split = path_str.rsplitn(2, "::");
240 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
244 if f == "self" || f == "Self" {
245 if let Some(name) = current_item.as_ref() {
251 .ok_or(ErrorKind::ResolutionFailure)?;
253 if let Some((path, prim)) = is_primitive(&path, TypeNS) {
254 for &impl_ in primitive_impl(cx, &path).ok_or(ErrorKind::ResolutionFailure)? {
257 .associated_items(impl_)
258 .find_by_name_and_namespace(
260 Ident::with_dummy_span(item_name),
264 .map(|item| match item.kind {
265 ty::AssocKind::Fn => "method",
266 ty::AssocKind::Const => "associatedconstant",
267 ty::AssocKind::Type => "associatedtype",
269 .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name))));
270 if let Some(link) = link {
274 return Err(ErrorKind::ResolutionFailure);
278 .enter_resolver(|resolver| {
279 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
281 .map_err(|_| ErrorKind::ResolutionFailure)?;
282 if let Res::Err = ty_res {
283 return if ns == Namespace::ValueNS {
284 self.variant_field(path_str, current_item, module_id)
286 Err(ErrorKind::ResolutionFailure)
289 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
290 let res = match ty_res {
292 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::TyAlias,
295 debug!("looking for associated item named {} for item {:?}", item_name, did);
296 // Checks if item_name belongs to `impl SomeItem`
302 cx.tcx.associated_items(imp).find_by_name_and_namespace(
304 Ident::with_dummy_span(item_name),
309 .map(|item| item.kind)
310 // There should only ever be one associated item that matches from any inherent impl
312 // Check if item_name belongs to `impl SomeTrait for SomeItem`
313 // This gives precedence to `impl SomeItem`:
314 // Although having both would be ambiguous, use impl version for compat. sake.
315 // To handle that properly resolve() would have to support
316 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
318 let kind = resolve_associated_trait_item(
319 did, module_id, item_name, ns, &self.cx,
321 debug!("got associated item kind {:?}", kind);
325 if let Some(kind) = kind {
326 let out = match kind {
327 ty::AssocKind::Fn => "method",
328 ty::AssocKind::Const => "associatedconstant",
329 ty::AssocKind::Type => "associatedtype",
331 Some(if extra_fragment.is_some() {
332 Err(ErrorKind::AnchorFailure(if kind == ty::AssocKind::Fn {
333 AnchorFailure::Method
335 AnchorFailure::AssocConstant
338 // HACK(jynelson): `clean` expects the type, not the associated item.
339 // but the disambiguator logic expects the associated item.
340 // Store the kind in a side channel so that only the disambiguator logic looks at it.
341 self.kind_side_channel.set(Some(kind.as_def_kind()));
342 Ok((ty_res, Some(format!("{}.{}", out, item_name))))
344 } else if ns == Namespace::ValueNS {
345 match cx.tcx.type_of(did).kind {
347 let field = if def.is_enum() {
348 def.all_fields().find(|item| item.ident.name == item_name)
350 def.non_enum_variant()
353 .find(|item| item.ident.name == item_name)
356 if extra_fragment.is_some() {
357 Err(ErrorKind::AnchorFailure(if def.is_enum() {
358 AnchorFailure::Variant
381 // We already know this isn't in ValueNS, so no need to check variant_field
382 return Err(ErrorKind::ResolutionFailure);
385 Res::Def(DefKind::Trait, did) => cx
387 .associated_items(did)
388 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, did)
390 let kind = match item.kind {
391 ty::AssocKind::Const => "associatedconstant",
392 ty::AssocKind::Type => "associatedtype",
393 ty::AssocKind::Fn => {
394 if item.defaultness.has_value() {
402 if extra_fragment.is_some() {
403 Err(ErrorKind::AnchorFailure(if item.kind == ty::AssocKind::Const {
404 AnchorFailure::AssocConstant
405 } else if item.kind == ty::AssocKind::Type {
406 AnchorFailure::AssocType
408 AnchorFailure::Method
411 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
412 Ok((res, Some(format!("{}.{}", kind, item_name))))
417 res.unwrap_or_else(|| {
418 if ns == Namespace::ValueNS {
419 self.variant_field(path_str, current_item, module_id)
421 Err(ErrorKind::ResolutionFailure)
425 debug!("attempting to resolve item without parent module: {}", path_str);
426 Err(ErrorKind::ResolutionFailure)
431 fn resolve_associated_trait_item(
437 ) -> Option<ty::AssocKind> {
438 let ty = cx.tcx.type_of(did);
439 // First consider automatic impls: `impl From<T> for T`
440 let implicit_impls = crate::clean::get_auto_trait_and_blanket_impls(cx, ty, did);
441 let mut candidates: Vec<_> = implicit_impls
442 .flat_map(|impl_outer| {
443 match impl_outer.inner {
445 debug!("considering auto or blanket impl for trait {:?}", impl_.trait_);
446 // Give precedence to methods that were overridden
447 if !impl_.provided_trait_methods.contains(&*item_name.as_str()) {
448 let mut items = impl_.items.into_iter().filter_map(|assoc| {
449 if assoc.name.as_deref() != Some(&*item_name.as_str()) {
455 .expect("inner items for a trait should be associated items");
456 if kind.namespace() != ns {
460 trace!("considering associated item {:?}", assoc.inner);
461 // We have a slight issue: normal methods come from `clean` types,
462 // but provided methods come directly from `tcx`.
463 // Fortunately, we don't need the whole method, we just need to know
464 // what kind of associated item it is.
465 Some((assoc.def_id, kind))
467 let assoc = items.next();
468 debug_assert_eq!(items.count(), 0);
471 // These are provided methods or default types:
475 // fn has_default() -> A { 0 }
478 let trait_ = impl_.trait_.unwrap().def_id().unwrap();
480 .associated_items(trait_)
481 .find_by_name_and_namespace(
483 Ident::with_dummy_span(item_name),
487 .map(|assoc| (assoc.def_id, assoc.kind))
490 _ => panic!("get_impls returned something that wasn't an impl"),
495 // Next consider explicit impls: `impl MyTrait for MyType`
496 // Give precedence to inherent impls.
497 if candidates.is_empty() {
498 let traits = traits_implemented_by(cx, did, module);
499 debug!("considering traits {:?}", traits);
500 candidates.extend(traits.iter().filter_map(|&trait_| {
502 .associated_items(trait_)
503 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
504 .map(|assoc| (assoc.def_id, assoc.kind))
507 // FIXME: warn about ambiguity
508 debug!("the candidates were {:?}", candidates);
509 candidates.pop().map(|(_, kind)| kind)
512 /// Given a type, return all traits in scope in `module` implemented by that type.
514 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
515 /// So it is not stable to serialize cross-crate.
516 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
517 let mut cache = cx.module_trait_cache.borrow_mut();
518 let in_scope_traits = cache.entry(module).or_insert_with(|| {
519 cx.enter_resolver(|resolver| {
520 resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
524 let ty = cx.tcx.type_of(type_);
525 let iter = in_scope_traits.iter().flat_map(|&trait_| {
526 trace!("considering explicit impl for trait {:?}", trait_);
527 let mut saw_impl = false;
528 // Look at each trait implementation to see if it's an impl for `did`
529 cx.tcx.for_each_relevant_impl(trait_, ty, |impl_| {
530 // FIXME: this is inefficient, find a way to short-circuit for_each_* so this doesn't take as long
535 let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
536 // Check if these are the same type.
537 let impl_type = trait_ref.self_ty();
539 "comparing type {} with kind {:?} against type {:?}",
540 impl_type, impl_type.kind, type_
542 // Fast path: if this is a primitive simple `==` will work
543 saw_impl = impl_type == ty
544 || match impl_type.kind {
545 // Check if these are the same def_id
547 debug!("adt def_id: {:?}", def.did);
550 ty::Foreign(def_id) => def_id == type_,
554 if saw_impl { Some(trait_) } else { None }
559 /// Check for resolve collisions between a trait and its derive
561 /// These are common and we should just resolve to the trait in that case
562 fn is_derive_trait_collision<T>(ns: &PerNS<Option<(Res, T)>>) -> bool {
564 type_ns: Some((Res::Def(DefKind::Trait, _), _)),
565 macro_ns: Some((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
575 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
576 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
577 use rustc_middle::ty::DefIdTree;
579 let parent_node = if item.is_fake() {
580 // FIXME: is this correct?
583 let mut current = item.def_id;
584 // The immediate parent might not always be a module.
585 // Find the first parent which is.
587 if let Some(parent) = self.cx.tcx.parent(current) {
588 if self.cx.tcx.def_kind(parent) == DefKind::Mod {
598 if parent_node.is_some() {
599 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
602 let current_item = match item.inner {
604 if item.attrs.inner_docs {
605 if item.def_id.is_top_level_module() { item.name.clone() } else { None }
607 match parent_node.or(self.mod_ids.last().copied()) {
608 Some(parent) if !parent.is_top_level_module() => {
609 // FIXME: can we pull the parent module's name from elsewhere?
610 Some(self.cx.tcx.item_name(parent).to_string())
616 ImplItem(Impl { ref for_, .. }) => {
617 for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
619 // we don't display docs on `extern crate` items anyway, so don't process them.
620 ExternCrateItem(..) => {
621 debug!("ignoring extern crate item {:?}", item.def_id);
622 return self.fold_item_recur(item);
624 ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
625 MacroItem(..) => None,
626 _ => item.name.clone(),
629 if item.is_mod() && item.attrs.inner_docs {
630 self.mod_ids.push(item.def_id);
634 let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
635 trace!("got documentation '{}'", dox);
637 // find item's parent to resolve `Self` in item's docs below
638 let parent_name = self.cx.as_local_hir_id(item.def_id).and_then(|item_hir| {
639 let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
640 let item_parent = self.cx.tcx.hir().find(parent_hir);
642 Some(hir::Node::Item(hir::Item {
644 hir::ItemKind::Impl {
648 hir::TyKind::Path(hir::QPath::Resolved(
650 hir::Path { segments, .. },
657 })) => segments.first().map(|seg| seg.ident.to_string()),
658 Some(hir::Node::Item(hir::Item {
659 ident, kind: hir::ItemKind::Enum(..), ..
661 | Some(hir::Node::Item(hir::Item {
662 ident, kind: hir::ItemKind::Struct(..), ..
664 | Some(hir::Node::Item(hir::Item {
665 ident, kind: hir::ItemKind::Union(..), ..
667 | Some(hir::Node::Item(hir::Item {
668 ident, kind: hir::ItemKind::Trait(..), ..
669 })) => Some(ident.to_string()),
674 for (ori_link, link_range) in markdown_links(&dox) {
675 trace!("considering link '{}'", ori_link);
677 // Bail early for real links.
678 if ori_link.contains('/') {
682 // [] is mostly likely not supposed to be a link
683 if ori_link.is_empty() {
687 let link = ori_link.replace("`", "");
688 let parts = link.split('#').collect::<Vec<_>>();
689 let (link, extra_fragment) = if parts.len() > 2 {
690 anchor_failure(cx, &item, &link, &dox, link_range, AnchorFailure::MultipleAnchors);
692 } else if parts.len() == 2 {
693 if parts[0].trim().is_empty() {
694 // This is an anchor to an element of the current page, nothing to do in here!
697 (parts[0].to_owned(), Some(parts[1].to_owned()))
699 (parts[0].to_owned(), None)
704 let (mut res, mut fragment) = {
705 path_str = if let Ok((d, path)) = Disambiguator::from_str(&link) {
706 disambiguator = Some(d);
709 disambiguator = None;
714 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ch == ':' || ch == '_')) {
718 // In order to correctly resolve intra-doc-links we need to
719 // pick a base AST node to work from. If the documentation for
720 // this module came from an inner comment (//!) then we anchor
721 // our name resolution *inside* the module. If, on the other
722 // hand it was an outer comment (///) then we anchor the name
723 // resolution in the parent module on the basis that the names
724 // used are more likely to be intended to be parent names. For
725 // this, we set base_node to None for inner comments since
726 // we've already pushed this node onto the resolution stack but
727 // for outer comments we explicitly try and resolve against the
728 // parent_node first.
729 let base_node = if item.is_mod() && item.attrs.inner_docs {
730 self.mod_ids.last().copied()
735 // replace `Self` with suitable item's parent name
736 if path_str.starts_with("Self::") {
737 if let Some(ref name) = parent_name {
738 resolved_self = format!("{}::{}", name, &path_str[6..]);
739 path_str = &resolved_self;
743 match disambiguator.map(Disambiguator::ns) {
744 Some(ns @ (ValueNS | TypeNS)) => {
745 match self.resolve(path_str, ns, ¤t_item, base_node, &extra_fragment)
748 Err(ErrorKind::ResolutionFailure) => {
749 resolution_failure(cx, &item, path_str, &dox, link_range);
750 // This could just be a normal link or a broken link
751 // we could potentially check if something is
752 // "intra-doc-link-like" and warn in that case.
755 Err(ErrorKind::AnchorFailure(msg)) => {
756 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
763 let mut candidates = PerNS {
765 .macro_resolve(path_str, base_node)
766 .map(|res| (res, extra_fragment.clone())),
767 type_ns: match self.resolve(
775 debug!("got res in TypeNS: {:?}", res);
778 Err(ErrorKind::AnchorFailure(msg)) => {
779 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
782 Err(ErrorKind::ResolutionFailure) => None,
784 value_ns: match self.resolve(
791 Ok(res) => Some(res),
792 Err(ErrorKind::AnchorFailure(msg)) => {
793 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
796 Err(ErrorKind::ResolutionFailure) => None,
798 .and_then(|(res, fragment)| {
799 // Constructors are picked up in the type namespace.
801 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
802 _ => match (fragment, extra_fragment) {
803 (Some(fragment), Some(_)) => {
804 // Shouldn't happen but who knows?
805 Some((res, Some(fragment)))
807 (fragment, None) | (None, fragment) => {
808 Some((res, fragment))
815 if candidates.is_empty() {
816 resolution_failure(cx, &item, path_str, &dox, link_range);
817 // this could just be a normal link
821 let len = candidates.clone().present_items().count();
824 candidates.present_items().next().unwrap()
825 } else if len == 2 && is_derive_trait_collision(&candidates) {
826 candidates.type_ns.unwrap()
828 if is_derive_trait_collision(&candidates) {
829 candidates.macro_ns = None;
832 candidates.map(|candidate| candidate.map(|(res, _)| res));
839 candidates.present_items().collect(),
845 if let Some(res) = self.macro_resolve(path_str, base_node) {
846 (res, extra_fragment)
848 resolution_failure(cx, &item, path_str, &dox, link_range);
855 // Check for a primitive which might conflict with a module
856 // Report the ambiguity and require that the user specify which one they meant.
857 // FIXME: could there ever be a primitive not in the type namespace?
860 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
861 ) && !matches!(res, Res::PrimTy(_))
863 if let Some((path, prim)) = is_primitive(path_str, TypeNS) {
865 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
866 if fragment.is_some() {
873 AnchorFailure::Primitive,
878 fragment = Some(path.to_owned());
880 // `[char]` when a `char` module is in scope
881 let candidates = vec![res, prim];
882 ambiguity_error(cx, &item, path_str, &dox, link_range, candidates);
888 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
889 // The resolved item did not match the disambiguator; give a better error than 'not found'
890 let msg = format!("incompatible link kind for `{}`", path_str);
891 report_diagnostic(cx, &msg, &item, &dox, link_range.clone(), |diag, sp| {
893 "this link resolved to {} {}, which is not {} {}",
900 suggest_disambiguator(resolved, diag, path_str, &dox, sp, &link_range);
903 if let Res::PrimTy(_) = res {
904 match disambiguator {
905 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
906 item.attrs.links.push((ori_link, None, fragment))
909 report_mismatch(other, Disambiguator::Primitive);
914 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
916 // Disallow e.g. linking to enums with `struct@`
917 if let Res::Def(kind, _) = res {
918 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
919 match (self.kind_side_channel.take().unwrap_or(kind), disambiguator) {
920 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
921 // NOTE: this allows 'method' to mean both normal functions and associated functions
922 // This can't cause ambiguity because both are in the same namespace.
923 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
924 // These are namespaces; allow anything in the namespace to match
925 | (_, Some(Disambiguator::Namespace(_)))
926 // If no disambiguator given, allow anything
928 // All of these are valid, so do nothing
930 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
931 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
932 report_mismatch(specified, Disambiguator::Kind(kind));
938 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
939 if let Some((src_id, dst_id)) = res
941 .and_then(|def_id| def_id.as_local())
942 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
944 use rustc_hir::def_id::LOCAL_CRATE;
946 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
947 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
949 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
950 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
952 privacy_error(cx, &item, &path_str, &dox, link_range);
956 let id = register_res(cx, res);
957 item.attrs.links.push((ori_link, Some(id), fragment));
961 if item.is_mod() && !item.attrs.inner_docs {
962 self.mod_ids.push(item.def_id);
966 let ret = self.fold_item_recur(item);
972 self.fold_item_recur(item)
976 // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
977 // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
978 // will never resolve properly
979 fn fold_crate(&mut self, mut c: Crate) -> Crate {
980 c.module = c.module.take().and_then(|module| self.fold_item(module));
986 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
990 Namespace(Namespace),
994 /// (disambiguator, path_str)
995 fn from_str(link: &str) -> Result<(Self, &str), ()> {
996 use Disambiguator::{Kind, Namespace as NS, Primitive};
998 let find_suffix = || {
1000 ("!()", DefKind::Macro(MacroKind::Bang)),
1001 ("()", DefKind::Fn),
1002 ("!", DefKind::Macro(MacroKind::Bang)),
1004 for &(suffix, kind) in &suffixes {
1005 if link.ends_with(suffix) {
1006 return Ok((Kind(kind), link.trim_end_matches(suffix)));
1012 if let Some(idx) = link.find('@') {
1013 let (prefix, rest) = link.split_at(idx);
1014 let d = match prefix {
1015 "struct" => Kind(DefKind::Struct),
1016 "enum" => Kind(DefKind::Enum),
1017 "trait" => Kind(DefKind::Trait),
1018 "union" => Kind(DefKind::Union),
1019 "module" | "mod" => Kind(DefKind::Mod),
1020 "const" | "constant" => Kind(DefKind::Const),
1021 "static" => Kind(DefKind::Static),
1022 "function" | "fn" | "method" => Kind(DefKind::Fn),
1023 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1024 "type" => NS(Namespace::TypeNS),
1025 "value" => NS(Namespace::ValueNS),
1026 "macro" => NS(Namespace::MacroNS),
1027 "prim" | "primitive" => Primitive,
1028 _ => return find_suffix(),
1036 /// WARNING: panics on `Res::Err`
1037 fn from_res(res: Res) -> Self {
1039 Res::Def(kind, _) => Disambiguator::Kind(kind),
1040 Res::PrimTy(_) => Disambiguator::Primitive,
1041 _ => Disambiguator::Namespace(res.ns().expect("can't call `from_res` on Res::err")),
1045 /// Return (description of the change, suggestion)
1046 fn display_for(self, path_str: &str) -> (&'static str, String) {
1047 const PREFIX: &str = "prefix with the item kind";
1048 const FUNCTION: &str = "add parentheses";
1049 const MACRO: &str = "add an exclamation mark";
1051 let kind = match self {
1052 Disambiguator::Primitive => return (PREFIX, format!("prim@{}", path_str)),
1053 Disambiguator::Kind(kind) => kind,
1054 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1056 if kind == DefKind::Macro(MacroKind::Bang) {
1057 return (MACRO, format!("{}!", path_str));
1058 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1059 return (FUNCTION, format!("{}()", path_str));
1062 let prefix = match kind {
1063 DefKind::Struct => "struct",
1064 DefKind::Enum => "enum",
1065 DefKind::Trait => "trait",
1066 DefKind::Union => "union",
1067 DefKind::Mod => "mod",
1068 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1071 DefKind::Static => "static",
1072 DefKind::Macro(MacroKind::Derive) => "derive",
1073 // Now handle things that don't have a specific disambiguator
1076 .expect("tried to calculate a disambiguator for a def without a namespace?")
1078 Namespace::TypeNS => "type",
1079 Namespace::ValueNS => "value",
1080 Namespace::MacroNS => "macro",
1084 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1085 (PREFIX, format!("{}@{}", prefix, path_str))
1088 fn ns(self) -> Namespace {
1090 Self::Namespace(n) => n,
1092 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1094 Self::Primitive => TypeNS,
1098 fn article(self) -> &'static str {
1100 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1101 Self::Kind(k) => k.article(),
1102 Self::Primitive => "a",
1106 fn descr(self) -> &'static str {
1108 Self::Namespace(n) => n.descr(),
1109 // HACK(jynelson): by looking at the source I saw the DefId we pass
1110 // for `expected.descr()` doesn't matter, since it's not a crate
1111 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1112 Self::Primitive => "builtin type",
1117 /// Reports a diagnostic for an intra-doc link.
1119 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1120 /// the entire documentation block is used for the lint. If a range is provided but the span
1121 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1123 /// The `decorate` callback is invoked in all cases to allow further customization of the
1124 /// diagnostic before emission. If the span of the link was able to be determined, the second
1125 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1127 fn report_diagnostic(
1128 cx: &DocContext<'_>,
1132 link_range: Option<Range<usize>>,
1133 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1135 let hir_id = match cx.as_local_hir_id(item.def_id) {
1136 Some(hir_id) => hir_id,
1138 // If non-local, no need to check anything.
1139 info!("ignoring warning from parent crate: {}", msg);
1144 let attrs = &item.attrs;
1145 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1147 cx.tcx.struct_span_lint_hir(lint::builtin::BROKEN_INTRA_DOC_LINKS, hir_id, sp, |lint| {
1148 let mut diag = lint.build(msg);
1150 let span = link_range
1152 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
1154 if let Some(link_range) = link_range {
1155 if let Some(sp) = span {
1158 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1161 // last_new_line_offset
1162 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1163 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1165 // Print the line containing the `link_range` and manually mark it with '^'s.
1167 "the link appears in this line:\n\n{line}\n\
1168 {indicator: <before$}{indicator:^<found$}",
1171 before = link_range.start - last_new_line_offset,
1172 found = link_range.len(),
1177 decorate(&mut diag, span);
1183 fn resolution_failure(
1184 cx: &DocContext<'_>,
1188 link_range: Option<Range<usize>>,
1192 &format!("unresolved link to `{}`", path_str),
1197 if let Some(sp) = sp {
1198 diag.span_label(sp, "unresolved link");
1201 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1207 cx: &DocContext<'_>,
1211 link_range: Option<Range<usize>>,
1212 failure: AnchorFailure,
1214 let msg = match failure {
1215 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1216 AnchorFailure::Primitive
1217 | AnchorFailure::Variant
1218 | AnchorFailure::AssocConstant
1219 | AnchorFailure::AssocType
1220 | AnchorFailure::Field
1221 | AnchorFailure::Method => {
1222 let kind = match failure {
1223 AnchorFailure::Primitive => "primitive type",
1224 AnchorFailure::Variant => "enum variant",
1225 AnchorFailure::AssocConstant => "associated constant",
1226 AnchorFailure::AssocType => "associated type",
1227 AnchorFailure::Field => "struct field",
1228 AnchorFailure::Method => "method",
1229 AnchorFailure::MultipleAnchors => unreachable!("should be handled already"),
1233 "`{}` contains an anchor, but links to {kind}s are already anchored",
1240 report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1241 if let Some(sp) = sp {
1242 diag.span_label(sp, "contains invalid anchor");
1248 cx: &DocContext<'_>,
1252 link_range: Option<Range<usize>>,
1253 candidates: Vec<Res>,
1255 let mut msg = format!("`{}` is ", path_str);
1257 match candidates.as_slice() {
1258 [first_def, second_def] => {
1260 "both {} {} and {} {}",
1261 first_def.article(),
1263 second_def.article(),
1268 let mut candidates = candidates.iter().peekable();
1269 while let Some(res) = candidates.next() {
1270 if candidates.peek().is_some() {
1271 msg += &format!("{} {}, ", res.article(), res.descr());
1273 msg += &format!("and {} {}", res.article(), res.descr());
1279 report_diagnostic(cx, &msg, item, dox, link_range.clone(), |diag, sp| {
1280 if let Some(sp) = sp {
1281 diag.span_label(sp, "ambiguous link");
1283 diag.note("ambiguous link");
1286 for res in candidates {
1287 let disambiguator = Disambiguator::from_res(res);
1288 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1293 fn suggest_disambiguator(
1294 disambiguator: Disambiguator,
1295 diag: &mut DiagnosticBuilder<'_>,
1298 sp: Option<rustc_span::Span>,
1299 link_range: &Option<Range<usize>>,
1301 let (action, mut suggestion) = disambiguator.display_for(path_str);
1302 let help = format!("to link to the {}, {}", disambiguator.descr(), action);
1304 if let Some(sp) = sp {
1305 let link_range = link_range.as_ref().expect("must have a link range if we have a span");
1306 if dox.bytes().nth(link_range.start) == Some(b'`') {
1307 suggestion = format!("`{}`", suggestion);
1310 diag.span_suggestion(sp, &help, suggestion, Applicability::MaybeIncorrect);
1312 diag.help(&format!("{}: {}", help, suggestion));
1317 cx: &DocContext<'_>,
1321 link_range: Option<Range<usize>>,
1323 let item_name = item.name.as_deref().unwrap_or("<unknown>");
1325 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1327 report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1328 if let Some(sp) = sp {
1329 diag.span_label(sp, "this item is private");
1332 let note_msg = if cx.render_options.document_private {
1333 "this link resolves only because you passed `--document-private-items`, but will break without"
1335 "this link will resolve properly if you pass `--document-private-items`"
1337 diag.note(note_msg);
1341 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1343 cx: &DocContext<'_>,
1345 extra_fragment: &Option<String>,
1346 ) -> Result<(Res, Option<String>), ErrorKind> {
1347 use rustc_middle::ty::DefIdTree;
1349 if extra_fragment.is_some() {
1350 return Err(ErrorKind::AnchorFailure(AnchorFailure::Variant));
1352 let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
1355 return Err(ErrorKind::ResolutionFailure);
1357 let parent_def = Res::Def(DefKind::Enum, parent);
1358 let variant = cx.tcx.expect_variant_res(res);
1359 Ok((parent_def, Some(format!("variant.{}", variant.ident.name))))
1362 const PRIMITIVES: &[(&str, Res)] = &[
1363 ("u8", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
1364 ("u16", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
1365 ("u32", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
1366 ("u64", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
1367 ("u128", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
1368 ("usize", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
1369 ("i8", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
1370 ("i16", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
1371 ("i32", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
1372 ("i64", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
1373 ("i128", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
1374 ("isize", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
1375 ("f32", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
1376 ("f64", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
1377 ("str", Res::PrimTy(hir::PrimTy::Str)),
1378 ("bool", Res::PrimTy(hir::PrimTy::Bool)),
1379 ("true", Res::PrimTy(hir::PrimTy::Bool)),
1380 ("false", Res::PrimTy(hir::PrimTy::Bool)),
1381 ("char", Res::PrimTy(hir::PrimTy::Char)),
1384 fn is_primitive(path_str: &str, ns: Namespace) -> Option<(&'static str, Res)> {
1388 .filter(|x| x.0 == path_str)
1390 .map(|x| if x.0 == "true" || x.0 == "false" { ("bool", x.1) } else { x })
1397 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<&'static SmallVec<[DefId; 4]>> {
1398 Some(PrimitiveType::from_symbol(Symbol::intern(path_str))?.impls(cx.tcx))