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;
8 use syntax::ast::{self, Ident};
9 use syntax::feature_gate::UnstableFeatures;
10 use syntax::symbol::Symbol;
11 use syntax_pos::DUMMY_SP;
15 use crate::core::DocContext;
16 use crate::fold::DocFolder;
17 use crate::html::markdown::markdown_links;
19 use crate::passes::{look_for_tests, Pass};
21 use super::span_of_attrs;
23 pub const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
24 name: "collect-intra-doc-links",
25 pass: collect_intra_doc_links,
26 description: "reads a crate's documentation to resolve intra-doc-links",
29 pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
30 if !UnstableFeatures::from_environment().is_nightly_build() {
33 let mut coll = LinkCollector::new(cx);
35 coll.fold_crate(krate)
39 struct LinkCollector<'a, 'tcx> {
40 cx: &'a DocContext<'tcx>,
41 mod_ids: Vec<hir::HirId>,
44 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
45 fn new(cx: &'a DocContext<'tcx>) -> Self {
52 /// Resolves a string as a path within a particular namespace. Also returns an optional
53 /// URL fragment in the case of variants and methods.
57 current_item: &Option<String>,
58 parent_id: Option<hir::HirId>)
59 -> Result<(Res, Option<String>), ()>
63 // In case we're in a module, try to resolve the relative
65 if let Some(id) = parent_id.or(self.mod_ids.last().cloned()) {
66 // FIXME: `with_scope` requires the `NodeId` of a module.
67 let node_id = cx.tcx.hir().hir_to_node_id(id);
68 let result = cx.enter_resolver(|resolver| {
69 resolver.with_scope(node_id, |resolver| {
70 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns == ValueNS)
74 if let Ok(result) = result {
75 // In case this is a trait item, skip the
76 // early return and try looking for the trait.
77 let value = match result.res {
78 Res::Def(DefKind::Method, _) | Res::Def(DefKind::AssociatedConst, _) => true,
79 Res::Def(DefKind::AssociatedTy, _) => false,
80 Res::Def(DefKind::Variant, _) => return handle_variant(cx, result.res),
81 // Not a trait item; just return what we found.
82 _ => return Ok((result.res, None))
85 if value != (ns == ValueNS) {
88 } else if let Some(prim) = is_primitive(path_str, ns) {
89 return Ok((prim, Some(path_str.to_owned())))
91 // If resolution failed, it may still be a method
92 // because methods are not handled by the resolver
93 // If so, bail when we're not looking for a value.
99 // Try looking for methods and associated items.
100 let mut split = path_str.rsplitn(2, "::");
101 let item_name = if let Some(first) = split.next() {
102 Symbol::intern(first)
107 let mut path = if let Some(second) = split.next() {
113 if path == "self" || path == "Self" {
114 if let Some(name) = current_item.as_ref() {
118 if let Some(prim) = is_primitive(&path, TypeNS) {
119 let did = primitive_impl(cx, &path).ok_or(())?;
120 return cx.tcx.associated_items(did)
121 .find(|item| item.ident.name == item_name)
122 .and_then(|item| match item.kind {
123 ty::AssociatedKind::Method => Some("method"),
126 .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name))))
130 // FIXME: `with_scope` requires the `NodeId` of a module.
131 let node_id = cx.tcx.hir().hir_to_node_id(id);
132 let ty = cx.enter_resolver(|resolver| resolver.with_scope(node_id, |resolver| {
133 resolver.resolve_str_path_error(DUMMY_SP, &path, false)
136 Res::Def(DefKind::Struct, did)
137 | Res::Def(DefKind::Union, did)
138 | Res::Def(DefKind::Enum, did)
139 | Res::Def(DefKind::TyAlias, did) => {
140 let item = cx.tcx.inherent_impls(did)
142 .flat_map(|imp| cx.tcx.associated_items(*imp))
143 .find(|item| item.ident.name == item_name);
144 if let Some(item) = item {
145 let out = match item.kind {
146 ty::AssociatedKind::Method if ns == ValueNS => "method",
147 ty::AssociatedKind::Const if ns == ValueNS => "associatedconstant",
150 Ok((ty.res, Some(format!("{}.{}", out, item_name))))
152 match cx.tcx.type_of(did).sty {
154 if let Some(item) = if def.is_enum() {
155 def.all_fields().find(|item| item.ident.name == item_name)
157 def.non_enum_variant()
160 .find(|item| item.ident.name == item_name)
163 Some(format!("{}.{}",
178 Res::Def(DefKind::Trait, did) => {
179 let item = cx.tcx.associated_item_def_ids(did).iter()
180 .map(|item| cx.tcx.associated_item(*item))
181 .find(|item| item.ident.name == item_name);
182 if let Some(item) = item {
183 let kind = match item.kind {
184 ty::AssociatedKind::Const if ns == ValueNS => "associatedconstant",
185 ty::AssociatedKind::Type if ns == TypeNS => "associatedtype",
186 ty::AssociatedKind::Method if ns == ValueNS => {
187 if item.defaultness.has_value() {
196 Ok((ty.res, Some(format!("{}.{}", kind, item_name))))
204 debug!("attempting to resolve item without parent module: {}", path_str);
210 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
211 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
212 let item_hir_id = if item.is_mod() {
213 if let Some(id) = self.cx.tcx.hir().as_local_hir_id(item.def_id) {
216 debug!("attempting to fold on a non-local item: {:?}", item);
217 return self.fold_item_recur(item);
223 // FIXME: get the resolver to work with non-local resolve scopes.
224 let parent_node = self.cx.as_local_hir_id(item.def_id).and_then(|hir_id| {
225 // FIXME: this fails hard for impls in non-module scope, but is necessary for the
226 // current `resolve()` implementation.
227 match self.cx.tcx.hir().get_module_parent_node(hir_id) {
228 id if id != hir_id => Some(id),
233 if parent_node.is_some() {
234 debug!("got parent node for {} {:?}, id {:?}", item.type_(), item.name, item.def_id);
237 let current_item = match item.inner {
239 if item.attrs.inner_docs {
240 if item_hir_id.unwrap() != hir::CRATE_HIR_ID {
246 match parent_node.or(self.mod_ids.last().cloned()) {
247 Some(parent) if parent != hir::CRATE_HIR_ID => {
248 // FIXME: can we pull the parent module's name from elsewhere?
249 Some(self.cx.tcx.hir().name_by_hir_id(parent).to_string())
255 ImplItem(Impl { ref for_, .. }) => {
256 for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
258 // we don't display docs on `extern crate` items anyway, so don't process them.
259 ExternCrateItem(..) => return self.fold_item_recur(item),
260 ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
261 MacroItem(..) => None,
262 _ => item.name.clone(),
265 if item.is_mod() && item.attrs.inner_docs {
266 self.mod_ids.push(item_hir_id.unwrap());
270 let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
272 look_for_tests(&cx, &dox, &item, true);
274 for (ori_link, link_range) in markdown_links(&dox) {
275 // Bail early for real links.
276 if ori_link.contains('/') {
280 // [] is mostly likely not supposed to be a link
281 if ori_link.is_empty() {
285 let link = ori_link.replace("`", "");
286 let (res, fragment) = {
288 let path_str = if let Some(prefix) =
289 ["struct@", "enum@", "type@",
290 "trait@", "union@"].iter()
291 .find(|p| link.starts_with(**p)) {
293 link.trim_start_matches(prefix)
294 } else if let Some(prefix) =
295 ["const@", "static@",
296 "value@", "function@", "mod@",
297 "fn@", "module@", "method@"]
298 .iter().find(|p| link.starts_with(**p)) {
299 kind = Some(ValueNS);
300 link.trim_start_matches(prefix)
301 } else if link.ends_with("()") {
302 kind = Some(ValueNS);
303 link.trim_end_matches("()")
304 } else if link.starts_with("macro@") {
305 kind = Some(MacroNS);
306 link.trim_start_matches("macro@")
307 } else if link.ends_with('!') {
308 kind = Some(MacroNS);
309 link.trim_end_matches('!')
314 if path_str.contains(|ch: char| !(ch.is_alphanumeric() ||
315 ch == ':' || ch == '_')) {
320 Some(ns @ ValueNS) => {
321 if let Ok(res) = self.resolve(path_str, ns, ¤t_item, parent_node) {
324 resolution_failure(cx, &item.attrs, path_str, &dox, link_range);
325 // This could just be a normal link or a broken link
326 // we could potentially check if something is
327 // "intra-doc-link-like" and warn in that case.
331 Some(ns @ TypeNS) => {
332 if let Ok(res) = self.resolve(path_str, ns, ¤t_item, parent_node) {
335 resolution_failure(cx, &item.attrs, path_str, &dox, link_range);
336 // This could just be a normal link.
342 let candidates = PerNS {
343 macro_ns: macro_resolve(cx, path_str).map(|res| (res, None)),
345 .resolve(path_str, TypeNS, ¤t_item, parent_node)
348 .resolve(path_str, ValueNS, ¤t_item, parent_node)
350 .and_then(|(res, fragment)| {
351 // Constructors are picked up in the type namespace.
353 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
354 _ => Some((res, fragment))
359 if candidates.is_empty() {
360 resolution_failure(cx, &item.attrs, path_str, &dox, link_range);
361 // this could just be a normal link
365 let is_unambiguous = candidates.clone().present_items().count() == 1;
367 candidates.present_items().next().unwrap()
375 candidates.map(|candidate| candidate.map(|(res, _)| res)),
381 if let Some(res) = macro_resolve(cx, path_str) {
384 resolution_failure(cx, &item.attrs, path_str, &dox, link_range);
391 if let Res::PrimTy(_) = res {
392 item.attrs.links.push((ori_link, None, fragment));
394 let id = register_res(cx, res);
395 item.attrs.links.push((ori_link, Some(id), fragment));
399 if item.is_mod() && !item.attrs.inner_docs {
400 self.mod_ids.push(item_hir_id.unwrap());
404 let ret = self.fold_item_recur(item);
410 self.fold_item_recur(item)
414 // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
415 // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
416 // will never resolve properly
417 fn fold_crate(&mut self, mut c: Crate) -> Crate {
418 c.module = c.module.take().and_then(|module| self.fold_item(module));
424 /// Resolves a string as a macro.
425 fn macro_resolve(cx: &DocContext<'_>, path_str: &str) -> Option<Res> {
426 use syntax::ext::base::{MacroKind, SyntaxExtension};
427 let segment = ast::PathSegment::from_ident(Ident::from_str(path_str));
428 let path = ast::Path { segments: vec![segment], span: DUMMY_SP };
429 cx.enter_resolver(|resolver| {
430 let parent_scope = resolver.dummy_parent_scope();
431 if let Ok(res) = resolver.resolve_macro_to_res_inner(&path, MacroKind::Bang,
432 &parent_scope, false, false) {
433 if let Res::Def(DefKind::Macro(MacroKind::ProcMacroStub), _) = res {
434 // skip proc-macro stubs, they'll cause `get_macro` to crash
436 if let SyntaxExtension::DeclMacro { .. } = *resolver.get_macro(res) {
437 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 sp = span_of_attrs(attrs);
462 let mut diag = cx.tcx.struct_span_lint_hir(
463 lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,
466 &format!("`[{}]` cannot be resolved, ignoring it...", path_str),
468 if let Some(link_range) = link_range {
469 if let Some(sp) = super::source_span_for_markdown_range(cx, dox, &link_range, attrs) {
471 diag.span_label(sp, "cannot be resolved, ignoring");
473 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
476 // last_new_line_offset
477 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
478 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
480 // Print the line containing the `link_range` and manually mark it with '^'s.
482 "the link appears in this line:\n\n{line}\n\
483 {indicator: <before$}{indicator:^<found$}",
486 before=link_range.start - last_new_line_offset,
487 found=link_range.len(),
491 diag.help("to escape `[` and `]` characters, just add '\\' before them like \
501 link_range: Option<Range<usize>>,
502 candidates: PerNS<Option<Res>>,
504 let sp = span_of_attrs(attrs);
506 let mut msg = format!("`{}` is ", path_str);
508 let candidates = [TypeNS, ValueNS, MacroNS].iter().filter_map(|&ns| {
509 candidates[ns].map(|res| (res, ns))
510 }).collect::<Vec<_>>();
511 match candidates.as_slice() {
512 [(first_def, _), (second_def, _)] => {
514 "both {} {} and {} {}",
517 second_def.article(),
522 let mut candidates = candidates.iter().peekable();
523 while let Some((res, _)) = candidates.next() {
524 if candidates.peek().is_some() {
525 msg += &format!("{} {}, ", res.article(), res.descr());
527 msg += &format!("and {} {}", res.article(), res.descr());
533 let mut diag = cx.tcx.struct_span_lint_hir(
534 lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,
540 if let Some(link_range) = link_range {
541 if let Some(sp) = super::source_span_for_markdown_range(cx, dox, &link_range, attrs) {
543 diag.span_label(sp, "ambiguous link");
545 for (res, ns) in candidates {
546 let (action, mut suggestion) = match res {
547 Res::Def(DefKind::Method, _) | Res::Def(DefKind::Fn, _) => {
548 ("add parentheses", format!("{}()", path_str))
550 Res::Def(DefKind::Macro(..), _) => {
551 ("add an exclamation mark", format!("{}!", path_str))
554 let type_ = match (res, ns) {
555 (Res::Def(DefKind::Const, _), _) => "const",
556 (Res::Def(DefKind::Static, _), _) => "static",
557 (Res::Def(DefKind::Struct, _), _) => "struct",
558 (Res::Def(DefKind::Enum, _), _) => "enum",
559 (Res::Def(DefKind::Union, _), _) => "union",
560 (Res::Def(DefKind::Trait, _), _) => "trait",
561 (Res::Def(DefKind::Mod, _), _) => "module",
562 (_, TypeNS) => "type",
563 (_, ValueNS) => "value",
564 (_, MacroNS) => "macro",
567 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
568 ("prefix with the item type", format!("{}@{}", type_, path_str))
572 if dox.bytes().nth(link_range.start) == Some(b'`') {
573 suggestion = format!("`{}`", suggestion);
576 diag.span_suggestion(
578 &format!("to link to the {}, {}", res.descr(), action),
580 Applicability::MaybeIncorrect,
584 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
587 // last_new_line_offset
588 let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
589 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
591 // Print the line containing the `link_range` and manually mark it with '^'s.
593 "the link appears in this line:\n\n{line}\n\
594 {indicator: <before$}{indicator:^<found$}",
597 before=link_range.start - last_new_line_offset,
598 found=link_range.len(),
606 /// Given an enum variant's res, return the res of its enum and the associated fragment.
607 fn handle_variant(cx: &DocContext<'_>, res: Res) -> Result<(Res, Option<String>), ()> {
608 use rustc::ty::DefIdTree;
610 let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
615 let parent_def = Res::Def(DefKind::Enum, parent);
616 let variant = cx.tcx.expect_variant_res(res);
617 Ok((parent_def, Some(format!("{}.v", variant.ident.name))))
620 const PRIMITIVES: &[(&str, Res)] = &[
621 ("u8", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U8))),
622 ("u16", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U16))),
623 ("u32", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U32))),
624 ("u64", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U64))),
625 ("u128", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::U128))),
626 ("usize", Res::PrimTy(hir::PrimTy::Uint(syntax::ast::UintTy::Usize))),
627 ("i8", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I8))),
628 ("i16", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I16))),
629 ("i32", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I32))),
630 ("i64", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I64))),
631 ("i128", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::I128))),
632 ("isize", Res::PrimTy(hir::PrimTy::Int(syntax::ast::IntTy::Isize))),
633 ("f32", Res::PrimTy(hir::PrimTy::Float(syntax::ast::FloatTy::F32))),
634 ("f64", Res::PrimTy(hir::PrimTy::Float(syntax::ast::FloatTy::F64))),
635 ("str", Res::PrimTy(hir::PrimTy::Str)),
636 ("bool", Res::PrimTy(hir::PrimTy::Bool)),
637 ("char", Res::PrimTy(hir::PrimTy::Char)),
640 fn is_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
642 PRIMITIVES.iter().find(|x| x.0 == path_str).map(|x| x.1)
648 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<DefId> {
651 "u8" => tcx.lang_items().u8_impl(),
652 "u16" => tcx.lang_items().u16_impl(),
653 "u32" => tcx.lang_items().u32_impl(),
654 "u64" => tcx.lang_items().u64_impl(),
655 "u128" => tcx.lang_items().u128_impl(),
656 "usize" => tcx.lang_items().usize_impl(),
657 "i8" => tcx.lang_items().i8_impl(),
658 "i16" => tcx.lang_items().i16_impl(),
659 "i32" => tcx.lang_items().i32_impl(),
660 "i64" => tcx.lang_items().i64_impl(),
661 "i128" => tcx.lang_items().i128_impl(),
662 "isize" => tcx.lang_items().isize_impl(),
663 "f32" => tcx.lang_items().f32_impl(),
664 "f64" => tcx.lang_items().f64_impl(),
665 "str" => tcx.lang_items().str_impl(),
666 "char" => tcx.lang_items().char_impl(),