1 use errors::Applicability;
2 use rustc::hir::def::{Res, DefKind, Namespace::{self, *}, PerNS};
3 use rustc::hir::def_id::DefId;
5 use rustc::lint as lint;
7 use rustc_resolve::ParentScope;
9 use syntax::ast::{self, Ident};
10 use syntax::ext::base::SyntaxExtensionKind;
11 use syntax::feature_gate::UnstableFeatures;
12 use syntax::symbol::Symbol;
13 use syntax_pos::DUMMY_SP;
17 use crate::core::DocContext;
18 use crate::fold::DocFolder;
19 use crate::html::markdown::markdown_links;
21 use crate::passes::{look_for_tests, Pass};
23 use super::span_of_attrs;
25 pub const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
26 name: "collect-intra-doc-links",
27 pass: collect_intra_doc_links,
28 description: "reads a crate's documentation to resolve intra-doc-links",
31 pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
32 if !UnstableFeatures::from_environment().is_nightly_build() {
35 let mut coll = LinkCollector::new(cx);
37 coll.fold_crate(krate)
41 struct LinkCollector<'a, 'tcx> {
42 cx: &'a DocContext<'tcx>,
43 mod_ids: Vec<hir::HirId>,
46 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
47 fn new(cx: &'a DocContext<'tcx>) -> Self {
54 /// Resolves a string as a path within a particular namespace. Also returns an optional
55 /// URL fragment in the case of variants and methods.
59 current_item: &Option<String>,
60 parent_id: Option<hir::HirId>)
61 -> Result<(Res, Option<String>), ()>
65 // In case we're in a module, try to resolve the relative path.
66 if let Some(module_id) = parent_id.or(self.mod_ids.last().cloned()) {
67 let module_id = cx.tcx.hir().hir_to_node_id(module_id);
68 let result = cx.enter_resolver(|resolver| {
69 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
71 let result = match result {
72 Ok((_, Res::Err)) => Err(()),
76 if let Ok((_, res)) = result {
77 let res = res.map_id(|_| panic!("unexpected node_id"));
78 // In case this is a trait item, skip the
79 // early return and try looking for the trait.
80 let value = match res {
81 Res::Def(DefKind::Method, _) | Res::Def(DefKind::AssocConst, _) => true,
82 Res::Def(DefKind::AssocTy, _) => false,
83 Res::Def(DefKind::Variant, _) => return handle_variant(cx, res),
84 // Not a trait item; just return what we found.
85 Res::PrimTy(..) => return Ok((res, Some(path_str.to_owned()))),
86 _ => return Ok((res, None))
89 if value != (ns == ValueNS) {
92 } else if let Some(prim) = is_primitive(path_str, ns) {
93 return Ok((prim, Some(path_str.to_owned())))
95 // If resolution failed, it may still be a method
96 // because methods are not handled by the resolver
97 // If so, bail when we're not looking for a value.
103 // Try looking for methods and associated items.
104 let mut split = path_str.rsplitn(2, "::");
105 let item_name = if let Some(first) = split.next() {
106 Symbol::intern(first)
111 let mut path = if let Some(second) = split.next() {
117 if path == "self" || path == "Self" {
118 if let Some(name) = current_item.as_ref() {
122 if let Some(prim) = is_primitive(&path, TypeNS) {
123 let did = primitive_impl(cx, &path).ok_or(())?;
124 return cx.tcx.associated_items(did)
125 .find(|item| item.ident.name == item_name)
126 .and_then(|item| match item.kind {
127 ty::AssocKind::Method => Some("method"),
130 .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name))))
134 let (_, ty_res) = cx.enter_resolver(|resolver| {
135 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
137 if let Res::Err = ty_res {
140 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
142 Res::Def(DefKind::Struct, did)
143 | Res::Def(DefKind::Union, did)
144 | Res::Def(DefKind::Enum, did)
145 | Res::Def(DefKind::TyAlias, did) => {
146 let item = cx.tcx.inherent_impls(did)
148 .flat_map(|imp| cx.tcx.associated_items(*imp))
149 .find(|item| item.ident.name == item_name);
150 if let Some(item) = item {
151 let out = match item.kind {
152 ty::AssocKind::Method if ns == ValueNS => "method",
153 ty::AssocKind::Const if ns == ValueNS => "associatedconstant",
156 Ok((ty_res, Some(format!("{}.{}", out, item_name))))
158 match cx.tcx.type_of(did).kind {
160 if let Some(item) = if def.is_enum() {
161 def.all_fields().find(|item| item.ident.name == item_name)
163 def.non_enum_variant()
166 .find(|item| item.ident.name == item_name)
169 Some(format!("{}.{}",
184 Res::Def(DefKind::Trait, did) => {
185 let item = cx.tcx.associated_item_def_ids(did).iter()
186 .map(|item| cx.tcx.associated_item(*item))
187 .find(|item| item.ident.name == item_name);
188 if let Some(item) = item {
189 let kind = match item.kind {
190 ty::AssocKind::Const if ns == ValueNS => "associatedconstant",
191 ty::AssocKind::Type if ns == TypeNS => "associatedtype",
192 ty::AssocKind::Method if ns == ValueNS => {
193 if item.defaultness.has_value() {
202 Ok((ty_res, Some(format!("{}.{}", kind, item_name))))
210 debug!("attempting to resolve item without parent module: {}", path_str);
216 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
217 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
218 let item_hir_id = if item.is_mod() {
219 if let Some(id) = self.cx.tcx.hir().as_local_hir_id(item.def_id) {
222 debug!("attempting to fold on a non-local item: {:?}", item);
223 return self.fold_item_recur(item);
229 // FIXME: get the resolver to work with non-local resolve scopes.
230 let parent_node = self.cx.as_local_hir_id(item.def_id).and_then(|hir_id| {
231 // FIXME: this fails hard for impls in non-module scope, but is necessary for the
232 // current `resolve()` implementation.
233 match self.cx.tcx.hir().get_module_parent_node(hir_id) {
234 id if id != hir_id => Some(id),
239 if parent_node.is_some() {
240 debug!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
243 let current_item = match item.inner {
245 if item.attrs.inner_docs {
246 if item_hir_id.unwrap() != hir::CRATE_HIR_ID {
252 match parent_node.or(self.mod_ids.last().cloned()) {
253 Some(parent) if parent != hir::CRATE_HIR_ID => {
254 // FIXME: can we pull the parent module's name from elsewhere?
255 Some(self.cx.tcx.hir().name(parent).to_string())
261 ImplItem(Impl { ref for_, .. }) => {
262 for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
264 // we don't display docs on `extern crate` items anyway, so don't process them.
265 ExternCrateItem(..) => return self.fold_item_recur(item),
266 ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
267 MacroItem(..) => None,
268 _ => item.name.clone(),
271 if item.is_mod() && item.attrs.inner_docs {
272 self.mod_ids.push(item_hir_id.unwrap());
276 let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
278 look_for_tests(&cx, &dox, &item, true);
280 for (ori_link, link_range) in markdown_links(&dox) {
281 // Bail early for real links.
282 if ori_link.contains('/') {
286 // [] is mostly likely not supposed to be a link
287 if ori_link.is_empty() {
291 let link = ori_link.replace("`", "");
292 let (res, fragment) = {
294 let path_str = if let Some(prefix) =
295 ["struct@", "enum@", "type@",
296 "trait@", "union@"].iter()
297 .find(|p| link.starts_with(**p)) {
299 link.trim_start_matches(prefix)
300 } else if let Some(prefix) =
301 ["const@", "static@",
302 "value@", "function@", "mod@",
303 "fn@", "module@", "method@"]
304 .iter().find(|p| link.starts_with(**p)) {
305 kind = Some(ValueNS);
306 link.trim_start_matches(prefix)
307 } else if link.ends_with("()") {
308 kind = Some(ValueNS);
309 link.trim_end_matches("()")
310 } else if link.starts_with("macro@") {
311 kind = Some(MacroNS);
312 link.trim_start_matches("macro@")
313 } else if link.ends_with('!') {
314 kind = Some(MacroNS);
315 link.trim_end_matches('!')
320 if path_str.contains(|ch: char| !(ch.is_alphanumeric() ||
321 ch == ':' || ch == '_')) {
326 Some(ns @ ValueNS) => {
327 if let Ok(res) = self.resolve(path_str, ns, ¤t_item, parent_node) {
330 resolution_failure(cx, &item, path_str, &dox, link_range);
331 // This could just be a normal link or a broken link
332 // we could potentially check if something is
333 // "intra-doc-link-like" and warn in that case.
337 Some(ns @ TypeNS) => {
338 if let Ok(res) = self.resolve(path_str, ns, ¤t_item, parent_node) {
341 resolution_failure(cx, &item, path_str, &dox, link_range);
342 // This could just be a normal link.
348 let candidates = PerNS {
349 macro_ns: macro_resolve(cx, path_str).map(|res| (res, None)),
351 .resolve(path_str, TypeNS, ¤t_item, parent_node)
354 .resolve(path_str, ValueNS, ¤t_item, parent_node)
356 .and_then(|(res, fragment)| {
357 // Constructors are picked up in the type namespace.
359 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
360 _ => Some((res, fragment))
365 if candidates.is_empty() {
366 resolution_failure(cx, &item, path_str, &dox, link_range);
367 // this could just be a normal link
371 let is_unambiguous = candidates.clone().present_items().count() == 1;
373 candidates.present_items().next().unwrap()
381 candidates.map(|candidate| candidate.map(|(res, _)| res)),
387 if let Some(res) = macro_resolve(cx, path_str) {
390 resolution_failure(cx, &item, path_str, &dox, link_range);
397 if let Res::PrimTy(_) = res {
398 item.attrs.links.push((ori_link, None, fragment));
400 let id = register_res(cx, res);
401 item.attrs.links.push((ori_link, Some(id), fragment));
405 if item.is_mod() && !item.attrs.inner_docs {
406 self.mod_ids.push(item_hir_id.unwrap());
410 let ret = self.fold_item_recur(item);
416 self.fold_item_recur(item)
420 // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
421 // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
422 // will never resolve properly
423 fn fold_crate(&mut self, mut c: Crate) -> Crate {
424 c.module = c.module.take().and_then(|module| self.fold_item(module));
430 /// Resolves a string as a macro.
431 fn macro_resolve(cx: &DocContext<'_>, path_str: &str) -> Option<Res> {
432 let path = ast::Path::from_ident(Ident::from_str(path_str));
433 cx.enter_resolver(|resolver| {
434 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
435 &path, None, &ParentScope::module(resolver.graph_root), false, false
437 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
438 return Some(res.map_id(|_| panic!("unexpected id")));
441 if let Some(res) = resolver.all_macros.get(&Symbol::intern(path_str)) {
442 return Some(res.map_id(|_| panic!("unexpected id")));
448 /// Reports a resolution failure diagnostic.
450 /// If we cannot find the exact source span of the resolution failure, we use the span of the
451 /// documentation attributes themselves. This is a little heavy-handed, so we display the markdown
452 /// line containing the failure as a note as well.
453 fn resolution_failure(
458 link_range: Option<Range<usize>>,
460 let hir_id = match cx.as_local_hir_id(item.def_id) {
461 Some(hir_id) => hir_id,
463 // If non-local, no need to check anything.
467 let attrs = &item.attrs;
468 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
470 let mut diag = cx.tcx.struct_span_lint_hir(
471 lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,
474 &format!("`[{}]` cannot be resolved, ignoring it...", path_str),
476 if let Some(link_range) = link_range {
477 if let Some(sp) = super::source_span_for_markdown_range(cx, dox, &link_range, attrs) {
479 diag.span_label(sp, "cannot be resolved, ignoring");
481 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
484 // last_new_line_offset
485 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
486 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
488 // Print the line containing the `link_range` and manually mark it with '^'s.
490 "the link appears in this line:\n\n{line}\n\
491 {indicator: <before$}{indicator:^<found$}",
494 before=link_range.start - last_new_line_offset,
495 found=link_range.len(),
499 diag.help("to escape `[` and `]` characters, just add '\\' before them like \
509 link_range: Option<Range<usize>>,
510 candidates: PerNS<Option<Res>>,
512 let hir_id = match cx.as_local_hir_id(item.def_id) {
513 Some(hir_id) => hir_id,
515 // If non-local, no need to check anything.
519 let attrs = &item.attrs;
520 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
522 let mut msg = format!("`{}` is ", path_str);
524 let candidates = [TypeNS, ValueNS, MacroNS].iter().filter_map(|&ns| {
525 candidates[ns].map(|res| (res, ns))
526 }).collect::<Vec<_>>();
527 match candidates.as_slice() {
528 [(first_def, _), (second_def, _)] => {
530 "both {} {} and {} {}",
533 second_def.article(),
538 let mut candidates = candidates.iter().peekable();
539 while let Some((res, _)) = candidates.next() {
540 if candidates.peek().is_some() {
541 msg += &format!("{} {}, ", res.article(), res.descr());
543 msg += &format!("and {} {}", res.article(), res.descr());
549 let mut diag = cx.tcx.struct_span_lint_hir(
550 lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,
556 if let Some(link_range) = link_range {
557 if let Some(sp) = super::source_span_for_markdown_range(cx, dox, &link_range, attrs) {
559 diag.span_label(sp, "ambiguous link");
561 for (res, ns) in candidates {
562 let (action, mut suggestion) = match res {
563 Res::Def(DefKind::Method, _) | Res::Def(DefKind::Fn, _) => {
564 ("add parentheses", format!("{}()", path_str))
566 Res::Def(DefKind::Macro(..), _) => {
567 ("add an exclamation mark", format!("{}!", path_str))
570 let type_ = match (res, ns) {
571 (Res::Def(DefKind::Const, _), _) => "const",
572 (Res::Def(DefKind::Static, _), _) => "static",
573 (Res::Def(DefKind::Struct, _), _) => "struct",
574 (Res::Def(DefKind::Enum, _), _) => "enum",
575 (Res::Def(DefKind::Union, _), _) => "union",
576 (Res::Def(DefKind::Trait, _), _) => "trait",
577 (Res::Def(DefKind::Mod, _), _) => "module",
578 (_, TypeNS) => "type",
579 (_, ValueNS) => "value",
580 (_, MacroNS) => "macro",
583 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
584 ("prefix with the item type", format!("{}@{}", type_, path_str))
588 if dox.bytes().nth(link_range.start) == Some(b'`') {
589 suggestion = format!("`{}`", suggestion);
592 diag.span_suggestion(
594 &format!("to link to the {}, {}", res.descr(), action),
596 Applicability::MaybeIncorrect,
600 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
603 // last_new_line_offset
604 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
605 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
607 // Print the line containing the `link_range` and manually mark it with '^'s.
609 "the link appears in this line:\n\n{line}\n\
610 {indicator: <before$}{indicator:^<found$}",
613 before=link_range.start - last_new_line_offset,
614 found=link_range.len(),
622 /// Given an enum variant's res, return the res of its enum and the associated fragment.
623 fn handle_variant(cx: &DocContext<'_>, res: Res) -> Result<(Res, Option<String>), ()> {
624 use rustc::ty::DefIdTree;
626 let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
631 let parent_def = Res::Def(DefKind::Enum, parent);
632 let variant = cx.tcx.expect_variant_res(res);
633 Ok((parent_def, Some(format!("{}.v", variant.ident.name))))
636 const PRIMITIVES: &[(&str, Res)] = &[
637 ("u8", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U8))),
638 ("u16", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U16))),
639 ("u32", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U32))),
640 ("u64", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U64))),
641 ("u128", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U128))),
642 ("usize", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::Usize))),
643 ("i8", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I8))),
644 ("i16", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I16))),
645 ("i32", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I32))),
646 ("i64", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I64))),
647 ("i128", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I128))),
648 ("isize", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::Isize))),
649 ("f32", Res::PrimTy(hir::PrimTy::Float(syntax::ast::FloatTy::F32))),
650 ("f64", Res::PrimTy(hir::PrimTy::Float(syntax::ast::FloatTy::F64))),
651 ("str", Res::PrimTy(hir::PrimTy::Str)),
652 ("bool", Res::PrimTy(hir::PrimTy::Bool)),
653 ("char", Res::PrimTy(hir::PrimTy::Char)),
656 fn is_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
658 PRIMITIVES.iter().find(|x| x.0 == path_str).map(|x| x.1)
664 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<DefId> {
667 "u8" => tcx.lang_items().u8_impl(),
668 "u16" => tcx.lang_items().u16_impl(),
669 "u32" => tcx.lang_items().u32_impl(),
670 "u64" => tcx.lang_items().u64_impl(),
671 "u128" => tcx.lang_items().u128_impl(),
672 "usize" => tcx.lang_items().usize_impl(),
673 "i8" => tcx.lang_items().i8_impl(),
674 "i16" => tcx.lang_items().i16_impl(),
675 "i32" => tcx.lang_items().i32_impl(),
676 "i64" => tcx.lang_items().i64_impl(),
677 "i128" => tcx.lang_items().i128_impl(),
678 "isize" => tcx.lang_items().isize_impl(),
679 "f32" => tcx.lang_items().f32_impl(),
680 "f64" => tcx.lang_items().f64_impl(),
681 "str" => tcx.lang_items().str_impl(),
682 "bool" => tcx.lang_items().bool_impl(),
683 "char" => tcx.lang_items().char_impl(),