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 debug!("resolving {} as a macro in the module {:?}", path_str, module_id);
165 if let Ok((_, res)) =
166 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
168 // don't resolve builtins like `#[derive]`
169 if let Res::Def(..) = res {
170 let res = res.map_id(|_| panic!("unexpected node_id"));
175 debug!("attempting to resolve item without parent module: {}", path_str);
180 /// Resolves a string as a path within a particular namespace. Also returns an optional
181 /// URL fragment in the case of variants and methods.
186 current_item: &Option<String>,
187 parent_id: Option<DefId>,
188 extra_fragment: &Option<String>,
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 return Ok((res, extra_fragment.clone()));
224 return Ok((res, extra_fragment.clone()));
228 if value != (ns == ValueNS) {
229 return Err(ErrorKind::ResolutionFailure);
231 } else if let Some((path, prim)) = is_primitive(path_str, ns) {
232 if extra_fragment.is_some() {
233 return Err(ErrorKind::AnchorFailure(AnchorFailure::Primitive));
235 return Ok((prim, Some(path.to_owned())));
238 // Try looking for methods and associated items.
239 let mut split = path_str.rsplitn(2, "::");
241 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
245 if f == "self" || f == "Self" {
246 if let Some(name) = current_item.as_ref() {
252 .ok_or(ErrorKind::ResolutionFailure)?;
254 if let Some((path, prim)) = is_primitive(&path, TypeNS) {
255 for &impl_ in primitive_impl(cx, &path).ok_or(ErrorKind::ResolutionFailure)? {
258 .associated_items(impl_)
259 .find_by_name_and_namespace(
261 Ident::with_dummy_span(item_name),
265 .map(|item| match item.kind {
266 ty::AssocKind::Fn => "method",
267 ty::AssocKind::Const => "associatedconstant",
268 ty::AssocKind::Type => "associatedtype",
270 .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name))));
271 if let Some(link) = link {
275 return Err(ErrorKind::ResolutionFailure);
279 .enter_resolver(|resolver| {
280 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
282 .map_err(|_| ErrorKind::ResolutionFailure)?;
283 if let Res::Err = ty_res {
284 return if ns == Namespace::ValueNS {
285 self.variant_field(path_str, current_item, module_id)
287 Err(ErrorKind::ResolutionFailure)
290 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
291 let res = match ty_res {
293 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::TyAlias,
296 debug!("looking for associated item named {} for item {:?}", item_name, did);
297 // Checks if item_name belongs to `impl SomeItem`
303 cx.tcx.associated_items(imp).find_by_name_and_namespace(
305 Ident::with_dummy_span(item_name),
310 .map(|item| item.kind)
311 // There should only ever be one associated item that matches from any inherent impl
313 // Check if item_name belongs to `impl SomeTrait for SomeItem`
314 // This gives precedence to `impl SomeItem`:
315 // Although having both would be ambiguous, use impl version for compat. sake.
316 // To handle that properly resolve() would have to support
317 // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
319 let kind = resolve_associated_trait_item(
320 did, module_id, item_name, ns, &self.cx,
322 debug!("got associated item kind {:?}", kind);
326 if let Some(kind) = kind {
327 let out = match kind {
328 ty::AssocKind::Fn => "method",
329 ty::AssocKind::Const => "associatedconstant",
330 ty::AssocKind::Type => "associatedtype",
332 Some(if extra_fragment.is_some() {
333 Err(ErrorKind::AnchorFailure(if kind == ty::AssocKind::Fn {
334 AnchorFailure::Method
336 AnchorFailure::AssocConstant
339 // HACK(jynelson): `clean` expects the type, not the associated item.
340 // but the disambiguator logic expects the associated item.
341 // Store the kind in a side channel so that only the disambiguator logic looks at it.
342 self.kind_side_channel.set(Some(kind.as_def_kind()));
343 Ok((ty_res, Some(format!("{}.{}", out, item_name))))
345 } else if ns == Namespace::ValueNS {
346 match cx.tcx.type_of(did).kind() {
348 let field = if def.is_enum() {
349 def.all_fields().find(|item| item.ident.name == item_name)
351 def.non_enum_variant()
354 .find(|item| item.ident.name == item_name)
357 if extra_fragment.is_some() {
358 Err(ErrorKind::AnchorFailure(if def.is_enum() {
359 AnchorFailure::Variant
382 // We already know this isn't in ValueNS, so no need to check variant_field
383 return Err(ErrorKind::ResolutionFailure);
386 Res::Def(DefKind::Trait, did) => cx
388 .associated_items(did)
389 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, did)
391 let kind = match item.kind {
392 ty::AssocKind::Const => "associatedconstant",
393 ty::AssocKind::Type => "associatedtype",
394 ty::AssocKind::Fn => {
395 if item.defaultness.has_value() {
403 if extra_fragment.is_some() {
404 Err(ErrorKind::AnchorFailure(if item.kind == ty::AssocKind::Const {
405 AnchorFailure::AssocConstant
406 } else if item.kind == ty::AssocKind::Type {
407 AnchorFailure::AssocType
409 AnchorFailure::Method
412 let res = Res::Def(item.kind.as_def_kind(), item.def_id);
413 Ok((res, Some(format!("{}.{}", kind, item_name))))
418 res.unwrap_or_else(|| {
419 if ns == Namespace::ValueNS {
420 self.variant_field(path_str, current_item, module_id)
422 Err(ErrorKind::ResolutionFailure)
426 debug!("attempting to resolve item without parent module: {}", path_str);
427 Err(ErrorKind::ResolutionFailure)
432 fn resolve_associated_trait_item(
438 ) -> Option<ty::AssocKind> {
439 let ty = cx.tcx.type_of(did);
440 // First consider automatic impls: `impl From<T> for T`
441 let implicit_impls = crate::clean::get_auto_trait_and_blanket_impls(cx, ty, did);
442 let mut candidates: Vec<_> = implicit_impls
443 .flat_map(|impl_outer| {
444 match impl_outer.inner {
446 debug!("considering auto or blanket impl for trait {:?}", impl_.trait_);
447 // Give precedence to methods that were overridden
448 if !impl_.provided_trait_methods.contains(&*item_name.as_str()) {
449 let mut items = impl_.items.into_iter().filter_map(|assoc| {
450 if assoc.name.as_deref() != Some(&*item_name.as_str()) {
456 .expect("inner items for a trait should be associated items");
457 if kind.namespace() != ns {
461 trace!("considering associated item {:?}", assoc.inner);
462 // We have a slight issue: normal methods come from `clean` types,
463 // but provided methods come directly from `tcx`.
464 // Fortunately, we don't need the whole method, we just need to know
465 // what kind of associated item it is.
466 Some((assoc.def_id, kind))
468 let assoc = items.next();
469 debug_assert_eq!(items.count(), 0);
472 // These are provided methods or default types:
476 // fn has_default() -> A { 0 }
479 let trait_ = impl_.trait_.unwrap().def_id().unwrap();
481 .associated_items(trait_)
482 .find_by_name_and_namespace(
484 Ident::with_dummy_span(item_name),
488 .map(|assoc| (assoc.def_id, assoc.kind))
491 _ => panic!("get_impls returned something that wasn't an impl"),
496 // Next consider explicit impls: `impl MyTrait for MyType`
497 // Give precedence to inherent impls.
498 if candidates.is_empty() {
499 let traits = traits_implemented_by(cx, did, module);
500 debug!("considering traits {:?}", traits);
501 candidates.extend(traits.iter().filter_map(|&trait_| {
503 .associated_items(trait_)
504 .find_by_name_and_namespace(cx.tcx, Ident::with_dummy_span(item_name), ns, trait_)
505 .map(|assoc| (assoc.def_id, assoc.kind))
508 // FIXME: warn about ambiguity
509 debug!("the candidates were {:?}", candidates);
510 candidates.pop().map(|(_, kind)| kind)
513 /// Given a type, return all traits in scope in `module` implemented by that type.
515 /// NOTE: this cannot be a query because more traits could be available when more crates are compiled!
516 /// So it is not stable to serialize cross-crate.
517 fn traits_implemented_by(cx: &DocContext<'_>, type_: DefId, module: DefId) -> FxHashSet<DefId> {
518 let mut cache = cx.module_trait_cache.borrow_mut();
519 let in_scope_traits = cache.entry(module).or_insert_with(|| {
520 cx.enter_resolver(|resolver| {
521 resolver.traits_in_scope(module).into_iter().map(|candidate| candidate.def_id).collect()
525 let ty = cx.tcx.type_of(type_);
526 let iter = in_scope_traits.iter().flat_map(|&trait_| {
527 trace!("considering explicit impl for trait {:?}", trait_);
528 let mut saw_impl = false;
529 // Look at each trait implementation to see if it's an impl for `did`
530 cx.tcx.for_each_relevant_impl(trait_, ty, |impl_| {
531 // FIXME: this is inefficient, find a way to short-circuit for_each_* so this doesn't take as long
536 let trait_ref = cx.tcx.impl_trait_ref(impl_).expect("this is not an inherent impl");
537 // Check if these are the same type.
538 let impl_type = trait_ref.self_ty();
540 "comparing type {} with kind {:?} against type {:?}",
545 // Fast path: if this is a primitive simple `==` will work
546 saw_impl = impl_type == ty
547 || match impl_type.kind() {
548 // Check if these are the same def_id
550 debug!("adt def_id: {:?}", def.did);
553 ty::Foreign(def_id) => *def_id == type_,
557 if saw_impl { Some(trait_) } else { None }
562 /// Check for resolve collisions between a trait and its derive
564 /// These are common and we should just resolve to the trait in that case
565 fn is_derive_trait_collision<T>(ns: &PerNS<Option<(Res, T)>>) -> bool {
567 type_ns: Some((Res::Def(DefKind::Trait, _), _)),
568 macro_ns: Some((Res::Def(DefKind::Macro(MacroKind::Derive), _), _)),
578 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
579 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
580 use rustc_middle::ty::DefIdTree;
582 let parent_node = if item.is_fake() {
583 // FIXME: is this correct?
586 let mut current = item.def_id;
587 // The immediate parent might not always be a module.
588 // Find the first parent which is.
590 if let Some(parent) = self.cx.tcx.parent(current) {
591 if self.cx.tcx.def_kind(parent) == DefKind::Mod {
601 if parent_node.is_some() {
602 trace!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
605 let current_item = match item.inner {
607 if item.attrs.inner_docs {
608 if item.def_id.is_top_level_module() { item.name.clone() } else { None }
610 match parent_node.or(self.mod_ids.last().copied()) {
611 Some(parent) if !parent.is_top_level_module() => {
612 // FIXME: can we pull the parent module's name from elsewhere?
613 Some(self.cx.tcx.item_name(parent).to_string())
619 ImplItem(Impl { ref for_, .. }) => {
620 for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
622 // we don't display docs on `extern crate` items anyway, so don't process them.
623 ExternCrateItem(..) => {
624 debug!("ignoring extern crate item {:?}", item.def_id);
625 return self.fold_item_recur(item);
627 ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
628 MacroItem(..) => None,
629 _ => item.name.clone(),
632 if item.is_mod() && item.attrs.inner_docs {
633 self.mod_ids.push(item.def_id);
637 let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
638 trace!("got documentation '{}'", dox);
640 // find item's parent to resolve `Self` in item's docs below
641 let parent_name = self.cx.as_local_hir_id(item.def_id).and_then(|item_hir| {
642 let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
643 let item_parent = self.cx.tcx.hir().find(parent_hir);
645 Some(hir::Node::Item(hir::Item {
647 hir::ItemKind::Impl {
651 hir::TyKind::Path(hir::QPath::Resolved(
653 hir::Path { segments, .. },
660 })) => segments.first().map(|seg| seg.ident.to_string()),
661 Some(hir::Node::Item(hir::Item {
662 ident, kind: hir::ItemKind::Enum(..), ..
664 | Some(hir::Node::Item(hir::Item {
665 ident, kind: hir::ItemKind::Struct(..), ..
667 | Some(hir::Node::Item(hir::Item {
668 ident, kind: hir::ItemKind::Union(..), ..
670 | Some(hir::Node::Item(hir::Item {
671 ident, kind: hir::ItemKind::Trait(..), ..
672 })) => Some(ident.to_string()),
677 for (ori_link, link_range) in markdown_links(&dox) {
678 trace!("considering link '{}'", ori_link);
680 // Bail early for real links.
681 if ori_link.contains('/') {
685 // [] is mostly likely not supposed to be a link
686 if ori_link.is_empty() {
690 let link = ori_link.replace("`", "");
691 let parts = link.split('#').collect::<Vec<_>>();
692 let (link, extra_fragment) = if parts.len() > 2 {
693 anchor_failure(cx, &item, &link, &dox, link_range, AnchorFailure::MultipleAnchors);
695 } else if parts.len() == 2 {
696 if parts[0].trim().is_empty() {
697 // This is an anchor to an element of the current page, nothing to do in here!
700 (parts[0], Some(parts[1].to_owned()))
708 let (mut res, mut fragment) = {
709 path_str = if let Ok((d, path)) = Disambiguator::from_str(&link) {
710 disambiguator = Some(d);
713 disambiguator = None;
718 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ch == ':' || ch == '_')) {
722 // We stripped `()` and `!` when parsing the disambiguator.
723 // Add them back to be displayed, but not prefix disambiguators.
724 link_text = disambiguator
725 .map(|d| d.display_for(path_str))
726 .unwrap_or_else(|| path_str.to_owned());
728 // In order to correctly resolve intra-doc-links we need to
729 // pick a base AST node to work from. If the documentation for
730 // this module came from an inner comment (//!) then we anchor
731 // our name resolution *inside* the module. If, on the other
732 // hand it was an outer comment (///) then we anchor the name
733 // resolution in the parent module on the basis that the names
734 // used are more likely to be intended to be parent names. For
735 // this, we set base_node to None for inner comments since
736 // we've already pushed this node onto the resolution stack but
737 // for outer comments we explicitly try and resolve against the
738 // parent_node first.
739 let base_node = if item.is_mod() && item.attrs.inner_docs {
740 self.mod_ids.last().copied()
745 // replace `Self` with suitable item's parent name
746 if path_str.starts_with("Self::") {
747 if let Some(ref name) = parent_name {
748 resolved_self = format!("{}::{}", name, &path_str[6..]);
749 path_str = &resolved_self;
753 match disambiguator.map(Disambiguator::ns) {
754 Some(ns @ (ValueNS | TypeNS)) => {
755 match self.resolve(path_str, ns, ¤t_item, base_node, &extra_fragment)
758 Err(ErrorKind::ResolutionFailure) => {
759 resolution_failure(cx, &item, path_str, &dox, link_range);
760 // This could just be a normal link or a broken link
761 // we could potentially check if something is
762 // "intra-doc-link-like" and warn in that case.
765 Err(ErrorKind::AnchorFailure(msg)) => {
766 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
773 let mut candidates = PerNS {
775 .macro_resolve(path_str, base_node)
776 .map(|res| (res, extra_fragment.clone())),
777 type_ns: match self.resolve(
785 debug!("got res in TypeNS: {:?}", res);
788 Err(ErrorKind::AnchorFailure(msg)) => {
789 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
792 Err(ErrorKind::ResolutionFailure) => None,
794 value_ns: match self.resolve(
801 Ok(res) => Some(res),
802 Err(ErrorKind::AnchorFailure(msg)) => {
803 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
806 Err(ErrorKind::ResolutionFailure) => None,
808 .and_then(|(res, fragment)| {
809 // Constructors are picked up in the type namespace.
811 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
812 _ => match (fragment, extra_fragment) {
813 (Some(fragment), Some(_)) => {
814 // Shouldn't happen but who knows?
815 Some((res, Some(fragment)))
817 (fragment, None) | (None, fragment) => {
818 Some((res, fragment))
825 if candidates.is_empty() {
826 resolution_failure(cx, &item, path_str, &dox, link_range);
827 // this could just be a normal link
831 let len = candidates.clone().present_items().count();
834 candidates.present_items().next().unwrap()
835 } else if len == 2 && is_derive_trait_collision(&candidates) {
836 candidates.type_ns.unwrap()
838 if is_derive_trait_collision(&candidates) {
839 candidates.macro_ns = None;
842 candidates.map(|candidate| candidate.map(|(res, _)| res));
849 candidates.present_items().collect(),
855 if let Some(res) = self.macro_resolve(path_str, base_node) {
856 (res, extra_fragment)
858 resolution_failure(cx, &item, path_str, &dox, link_range);
865 // Check for a primitive which might conflict with a module
866 // Report the ambiguity and require that the user specify which one they meant.
867 // FIXME: could there ever be a primitive not in the type namespace?
870 None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive)
871 ) && !matches!(res, Res::PrimTy(_))
873 if let Some((path, prim)) = is_primitive(path_str, TypeNS) {
875 if matches!(disambiguator, Some(Disambiguator::Primitive)) {
876 if fragment.is_some() {
883 AnchorFailure::Primitive,
888 fragment = Some(path.to_owned());
890 // `[char]` when a `char` module is in scope
891 let candidates = vec![res, prim];
892 ambiguity_error(cx, &item, path_str, &dox, link_range, candidates);
898 let report_mismatch = |specified: Disambiguator, resolved: Disambiguator| {
899 // The resolved item did not match the disambiguator; give a better error than 'not found'
900 let msg = format!("incompatible link kind for `{}`", path_str);
901 report_diagnostic(cx, &msg, &item, &dox, link_range.clone(), |diag, sp| {
903 "this link resolved to {} {}, which is not {} {}",
910 suggest_disambiguator(resolved, diag, path_str, &dox, sp, &link_range);
913 if let Res::PrimTy(_) = res {
914 match disambiguator {
915 Some(Disambiguator::Primitive | Disambiguator::Namespace(_)) | None => {
916 item.attrs.links.push(ItemLink {
918 link_text: path_str.to_owned(),
924 report_mismatch(other, Disambiguator::Primitive);
929 debug!("intra-doc link to {} resolved to {:?}", path_str, res);
931 // Disallow e.g. linking to enums with `struct@`
932 if let Res::Def(kind, _) = res {
933 debug!("saw kind {:?} with disambiguator {:?}", kind, disambiguator);
934 match (self.kind_side_channel.take().unwrap_or(kind), disambiguator) {
935 | (DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst, Some(Disambiguator::Kind(DefKind::Const)))
936 // NOTE: this allows 'method' to mean both normal functions and associated functions
937 // This can't cause ambiguity because both are in the same namespace.
938 | (DefKind::Fn | DefKind::AssocFn, Some(Disambiguator::Kind(DefKind::Fn)))
939 // These are namespaces; allow anything in the namespace to match
940 | (_, Some(Disambiguator::Namespace(_)))
941 // If no disambiguator given, allow anything
943 // All of these are valid, so do nothing
945 (actual, Some(Disambiguator::Kind(expected))) if actual == expected => {}
946 (_, Some(specified @ Disambiguator::Kind(_) | specified @ Disambiguator::Primitive)) => {
947 report_mismatch(specified, Disambiguator::Kind(kind));
953 // item can be non-local e.g. when using #[doc(primitive = "pointer")]
954 if let Some((src_id, dst_id)) = res
956 .and_then(|def_id| def_id.as_local())
957 .and_then(|dst_id| item.def_id.as_local().map(|src_id| (src_id, dst_id)))
959 use rustc_hir::def_id::LOCAL_CRATE;
961 let hir_src = self.cx.tcx.hir().local_def_id_to_hir_id(src_id);
962 let hir_dst = self.cx.tcx.hir().local_def_id_to_hir_id(dst_id);
964 if self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_src)
965 && !self.cx.tcx.privacy_access_levels(LOCAL_CRATE).is_exported(hir_dst)
967 privacy_error(cx, &item, &path_str, &dox, link_range);
971 let id = register_res(cx, res);
972 item.attrs.links.push(ItemLink {
981 if item.is_mod() && !item.attrs.inner_docs {
982 self.mod_ids.push(item.def_id);
986 let ret = self.fold_item_recur(item);
992 self.fold_item_recur(item)
997 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1001 Namespace(Namespace),
1004 impl Disambiguator {
1005 /// The text that should be displayed when the path is rendered as HTML.
1007 /// NOTE: `path` is not the original link given by the user, but a name suitable for passing to `resolve`.
1008 fn display_for(&self, path: &str) -> String {
1010 // FIXME: this will have different output if the user had `m!()` originally.
1011 Self::Kind(DefKind::Macro(MacroKind::Bang)) => format!("{}!", path),
1012 Self::Kind(DefKind::Fn) => format!("{}()", path),
1013 _ => path.to_owned(),
1017 /// (disambiguator, path_str)
1018 fn from_str(link: &str) -> Result<(Self, &str), ()> {
1019 use Disambiguator::{Kind, Namespace as NS, Primitive};
1021 let find_suffix = || {
1023 ("!()", DefKind::Macro(MacroKind::Bang)),
1024 ("()", DefKind::Fn),
1025 ("!", DefKind::Macro(MacroKind::Bang)),
1027 for &(suffix, kind) in &suffixes {
1028 if link.ends_with(suffix) {
1029 return Ok((Kind(kind), link.trim_end_matches(suffix)));
1035 if let Some(idx) = link.find('@') {
1036 let (prefix, rest) = link.split_at(idx);
1037 let d = match prefix {
1038 "struct" => Kind(DefKind::Struct),
1039 "enum" => Kind(DefKind::Enum),
1040 "trait" => Kind(DefKind::Trait),
1041 "union" => Kind(DefKind::Union),
1042 "module" | "mod" => Kind(DefKind::Mod),
1043 "const" | "constant" => Kind(DefKind::Const),
1044 "static" => Kind(DefKind::Static),
1045 "function" | "fn" | "method" => Kind(DefKind::Fn),
1046 "derive" => Kind(DefKind::Macro(MacroKind::Derive)),
1047 "type" => NS(Namespace::TypeNS),
1048 "value" => NS(Namespace::ValueNS),
1049 "macro" => NS(Namespace::MacroNS),
1050 "prim" | "primitive" => Primitive,
1051 _ => return find_suffix(),
1059 /// WARNING: panics on `Res::Err`
1060 fn from_res(res: Res) -> Self {
1062 Res::Def(kind, _) => Disambiguator::Kind(kind),
1063 Res::PrimTy(_) => Disambiguator::Primitive,
1064 _ => Disambiguator::Namespace(res.ns().expect("can't call `from_res` on Res::err")),
1068 /// Return (description of the change, suggestion)
1069 fn suggestion_for(self, path_str: &str) -> (&'static str, String) {
1070 const PREFIX: &str = "prefix with the item kind";
1071 const FUNCTION: &str = "add parentheses";
1072 const MACRO: &str = "add an exclamation mark";
1074 let kind = match self {
1075 Disambiguator::Primitive => return (PREFIX, format!("prim@{}", path_str)),
1076 Disambiguator::Kind(kind) => kind,
1077 Disambiguator::Namespace(_) => panic!("display_for cannot be used on namespaces"),
1079 if kind == DefKind::Macro(MacroKind::Bang) {
1080 return (MACRO, format!("{}!", path_str));
1081 } else if kind == DefKind::Fn || kind == DefKind::AssocFn {
1082 return (FUNCTION, format!("{}()", path_str));
1085 let prefix = match kind {
1086 DefKind::Struct => "struct",
1087 DefKind::Enum => "enum",
1088 DefKind::Trait => "trait",
1089 DefKind::Union => "union",
1090 DefKind::Mod => "mod",
1091 DefKind::Const | DefKind::ConstParam | DefKind::AssocConst | DefKind::AnonConst => {
1094 DefKind::Static => "static",
1095 DefKind::Macro(MacroKind::Derive) => "derive",
1096 // Now handle things that don't have a specific disambiguator
1099 .expect("tried to calculate a disambiguator for a def without a namespace?")
1101 Namespace::TypeNS => "type",
1102 Namespace::ValueNS => "value",
1103 Namespace::MacroNS => "macro",
1107 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
1108 (PREFIX, format!("{}@{}", prefix, path_str))
1111 fn ns(self) -> Namespace {
1113 Self::Namespace(n) => n,
1115 k.ns().expect("only DefKinds with a valid namespace can be disambiguators")
1117 Self::Primitive => TypeNS,
1121 fn article(self) -> &'static str {
1123 Self::Namespace(_) => panic!("article() doesn't make sense for namespaces"),
1124 Self::Kind(k) => k.article(),
1125 Self::Primitive => "a",
1129 fn descr(self) -> &'static str {
1131 Self::Namespace(n) => n.descr(),
1132 // HACK(jynelson): by looking at the source I saw the DefId we pass
1133 // for `expected.descr()` doesn't matter, since it's not a crate
1134 Self::Kind(k) => k.descr(DefId::local(hir::def_id::DefIndex::from_usize(0))),
1135 Self::Primitive => "builtin type",
1140 /// Reports a diagnostic for an intra-doc link.
1142 /// If no link range is provided, or the source span of the link cannot be determined, the span of
1143 /// the entire documentation block is used for the lint. If a range is provided but the span
1144 /// calculation fails, a note is added to the diagnostic pointing to the link in the markdown.
1146 /// The `decorate` callback is invoked in all cases to allow further customization of the
1147 /// diagnostic before emission. If the span of the link was able to be determined, the second
1148 /// parameter of the callback will contain it, and the primary span of the diagnostic will be set
1150 fn report_diagnostic(
1151 cx: &DocContext<'_>,
1155 link_range: Option<Range<usize>>,
1156 decorate: impl FnOnce(&mut DiagnosticBuilder<'_>, Option<rustc_span::Span>),
1158 let hir_id = match cx.as_local_hir_id(item.def_id) {
1159 Some(hir_id) => hir_id,
1161 // If non-local, no need to check anything.
1162 info!("ignoring warning from parent crate: {}", msg);
1167 let attrs = &item.attrs;
1168 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
1170 cx.tcx.struct_span_lint_hir(lint::builtin::BROKEN_INTRA_DOC_LINKS, hir_id, sp, |lint| {
1171 let mut diag = lint.build(msg);
1173 let span = link_range
1175 .and_then(|range| super::source_span_for_markdown_range(cx, dox, range, attrs));
1177 if let Some(link_range) = link_range {
1178 if let Some(sp) = span {
1181 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
1184 // last_new_line_offset
1185 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
1186 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
1188 // Print the line containing the `link_range` and manually mark it with '^'s.
1190 "the link appears in this line:\n\n{line}\n\
1191 {indicator: <before$}{indicator:^<found$}",
1194 before = link_range.start - last_new_line_offset,
1195 found = link_range.len(),
1200 decorate(&mut diag, span);
1206 fn resolution_failure(
1207 cx: &DocContext<'_>,
1211 link_range: Option<Range<usize>>,
1215 &format!("unresolved link to `{}`", path_str),
1220 if let Some(sp) = sp {
1221 diag.span_label(sp, "unresolved link");
1224 diag.help(r#"to escape `[` and `]` characters, add '\' before them like `\[` or `\]`"#);
1230 cx: &DocContext<'_>,
1234 link_range: Option<Range<usize>>,
1235 failure: AnchorFailure,
1237 let msg = match failure {
1238 AnchorFailure::MultipleAnchors => format!("`{}` contains multiple anchors", path_str),
1239 AnchorFailure::Primitive
1240 | AnchorFailure::Variant
1241 | AnchorFailure::AssocConstant
1242 | AnchorFailure::AssocType
1243 | AnchorFailure::Field
1244 | AnchorFailure::Method => {
1245 let kind = match failure {
1246 AnchorFailure::Primitive => "primitive type",
1247 AnchorFailure::Variant => "enum variant",
1248 AnchorFailure::AssocConstant => "associated constant",
1249 AnchorFailure::AssocType => "associated type",
1250 AnchorFailure::Field => "struct field",
1251 AnchorFailure::Method => "method",
1252 AnchorFailure::MultipleAnchors => unreachable!("should be handled already"),
1256 "`{}` contains an anchor, but links to {kind}s are already anchored",
1263 report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1264 if let Some(sp) = sp {
1265 diag.span_label(sp, "contains invalid anchor");
1271 cx: &DocContext<'_>,
1275 link_range: Option<Range<usize>>,
1276 candidates: Vec<Res>,
1278 let mut msg = format!("`{}` is ", path_str);
1280 match candidates.as_slice() {
1281 [first_def, second_def] => {
1283 "both {} {} and {} {}",
1284 first_def.article(),
1286 second_def.article(),
1291 let mut candidates = candidates.iter().peekable();
1292 while let Some(res) = candidates.next() {
1293 if candidates.peek().is_some() {
1294 msg += &format!("{} {}, ", res.article(), res.descr());
1296 msg += &format!("and {} {}", res.article(), res.descr());
1302 report_diagnostic(cx, &msg, item, dox, link_range.clone(), |diag, sp| {
1303 if let Some(sp) = sp {
1304 diag.span_label(sp, "ambiguous link");
1306 diag.note("ambiguous link");
1309 for res in candidates {
1310 let disambiguator = Disambiguator::from_res(res);
1311 suggest_disambiguator(disambiguator, diag, path_str, dox, sp, &link_range);
1316 fn suggest_disambiguator(
1317 disambiguator: Disambiguator,
1318 diag: &mut DiagnosticBuilder<'_>,
1321 sp: Option<rustc_span::Span>,
1322 link_range: &Option<Range<usize>>,
1324 let (action, mut suggestion) = disambiguator.suggestion_for(path_str);
1325 let help = format!("to link to the {}, {}", disambiguator.descr(), action);
1327 if let Some(sp) = sp {
1328 let link_range = link_range.as_ref().expect("must have a link range if we have a span");
1329 if dox.bytes().nth(link_range.start) == Some(b'`') {
1330 suggestion = format!("`{}`", suggestion);
1333 diag.span_suggestion(sp, &help, suggestion, Applicability::MaybeIncorrect);
1335 diag.help(&format!("{}: {}", help, suggestion));
1340 cx: &DocContext<'_>,
1344 link_range: Option<Range<usize>>,
1346 let item_name = item.name.as_deref().unwrap_or("<unknown>");
1348 format!("public documentation for `{}` links to private item `{}`", item_name, path_str);
1350 report_diagnostic(cx, &msg, item, dox, link_range, |diag, sp| {
1351 if let Some(sp) = sp {
1352 diag.span_label(sp, "this item is private");
1355 let note_msg = if cx.render_options.document_private {
1356 "this link resolves only because you passed `--document-private-items`, but will break without"
1358 "this link will resolve properly if you pass `--document-private-items`"
1360 diag.note(note_msg);
1364 /// Given an enum variant's res, return the res of its enum and the associated fragment.
1366 cx: &DocContext<'_>,
1368 extra_fragment: &Option<String>,
1369 ) -> Result<(Res, Option<String>), ErrorKind> {
1370 use rustc_middle::ty::DefIdTree;
1372 if extra_fragment.is_some() {
1373 return Err(ErrorKind::AnchorFailure(AnchorFailure::Variant));
1375 let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
1378 return Err(ErrorKind::ResolutionFailure);
1380 let parent_def = Res::Def(DefKind::Enum, parent);
1381 let variant = cx.tcx.expect_variant_res(res);
1382 Ok((parent_def, Some(format!("variant.{}", variant.ident.name))))
1385 const PRIMITIVES: &[(&str, Res)] = &[
1386 ("u8", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U8))),
1387 ("u16", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U16))),
1388 ("u32", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U32))),
1389 ("u64", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U64))),
1390 ("u128", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::U128))),
1391 ("usize", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::UintTy::Usize))),
1392 ("i8", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I8))),
1393 ("i16", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I16))),
1394 ("i32", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I32))),
1395 ("i64", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I64))),
1396 ("i128", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::I128))),
1397 ("isize", Res::PrimTy(hir::PrimTy::Int(rustc_ast::IntTy::Isize))),
1398 ("f32", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F32))),
1399 ("f64", Res::PrimTy(hir::PrimTy::Float(rustc_ast::FloatTy::F64))),
1400 ("str", Res::PrimTy(hir::PrimTy::Str)),
1401 ("bool", Res::PrimTy(hir::PrimTy::Bool)),
1402 ("true", Res::PrimTy(hir::PrimTy::Bool)),
1403 ("false", Res::PrimTy(hir::PrimTy::Bool)),
1404 ("char", Res::PrimTy(hir::PrimTy::Char)),
1407 fn is_primitive(path_str: &str, ns: Namespace) -> Option<(&'static str, Res)> {
1411 .filter(|x| x.0 == path_str)
1413 .map(|x| if x.0 == "true" || x.0 == "false" { ("bool", x.1) } else { x })
1420 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<&'static SmallVec<[DefId; 4]>> {
1421 Some(PrimitiveType::from_symbol(Symbol::intern(path_str))?.impls(cx.tcx))