2 use rustc_errors::Applicability;
3 use rustc_expand::base::SyntaxExtensionKind;
4 use rustc_feature::UnstableFeatures;
11 use rustc_hir::def_id::{DefId, LocalDefId};
13 use rustc_resolve::ParentScope;
14 use rustc_session::lint;
15 use rustc_span::symbol::Ident;
16 use rustc_span::symbol::Symbol;
17 use rustc_span::DUMMY_SP;
22 use crate::core::DocContext;
23 use crate::fold::DocFolder;
24 use crate::html::markdown::markdown_links;
25 use crate::passes::{look_for_tests, Pass};
27 use super::span_of_attrs;
29 pub const COLLECT_INTRA_DOC_LINKS: Pass = Pass {
30 name: "collect-intra-doc-links",
31 run: collect_intra_doc_links,
32 description: "reads a crate's documentation to resolve intra-doc-links",
35 pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext<'_>) -> Crate {
36 if !UnstableFeatures::from_environment().is_nightly_build() {
39 let mut coll = LinkCollector::new(cx);
41 coll.fold_crate(krate)
47 AnchorFailure(&'static str),
50 struct LinkCollector<'a, 'tcx> {
51 cx: &'a DocContext<'tcx>,
52 mod_ids: Vec<hir::HirId>,
55 impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
56 fn new(cx: &'a DocContext<'tcx>) -> Self {
57 LinkCollector { cx, mod_ids: Vec::new() }
63 current_item: &Option<String>,
64 module_id: LocalDefId,
65 ) -> Result<(Res, Option<String>), ErrorKind> {
68 let mut split = path_str.rsplitn(3, "::");
69 let variant_field_name =
70 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
72 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
76 if f == "self" || f == "Self" {
77 if let Some(name) = current_item.as_ref() {
83 .ok_or(ErrorKind::ResolutionFailure)?;
85 .enter_resolver(|resolver| {
86 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
88 .map_err(|_| ErrorKind::ResolutionFailure)?;
89 if let Res::Err = ty_res {
90 return Err(ErrorKind::ResolutionFailure);
92 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
94 Res::Def(DefKind::Enum, did) => {
99 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
100 .any(|item| item.ident.name == variant_name)
102 return Err(ErrorKind::ResolutionFailure);
104 match cx.tcx.type_of(did).kind {
105 ty::Adt(def, _) if def.is_enum() => {
106 if def.all_fields().any(|item| item.ident.name == variant_field_name) {
110 "variant.{}.field.{}",
111 variant_name, variant_field_name
115 Err(ErrorKind::ResolutionFailure)
118 _ => Err(ErrorKind::ResolutionFailure),
121 _ => Err(ErrorKind::ResolutionFailure),
125 /// Resolves a string as a macro.
126 fn macro_resolve(&self, path_str: &str, parent_id: Option<hir::HirId>) -> Option<Res> {
128 let path = ast::Path::from_ident(Ident::from_str(path_str));
129 cx.enter_resolver(|resolver| {
130 if let Ok((Some(ext), res)) = resolver.resolve_macro_path(
133 &ParentScope::module(resolver.graph_root()),
137 if let SyntaxExtensionKind::LegacyBang { .. } = ext.kind {
138 return Some(res.map_id(|_| panic!("unexpected id")));
141 if let Some(res) = resolver.all_macros().get(&Symbol::intern(path_str)) {
142 return Some(res.map_id(|_| panic!("unexpected id")));
144 if let Some(module_id) = parent_id.or(self.mod_ids.last().cloned()) {
145 let module_id = cx.tcx.hir().local_def_id(module_id);
146 if let Ok((_, res)) =
147 resolver.resolve_str_path_error(DUMMY_SP, path_str, MacroNS, module_id)
149 // don't resolve builtins like `#[derive]`
150 if let Res::Def(..) = res {
151 let res = res.map_id(|_| panic!("unexpected node_id"));
156 debug!("attempting to resolve item without parent module: {}", path_str);
161 /// Resolves a string as a path within a particular namespace. Also returns an optional
162 /// URL fragment in the case of variants and methods.
167 current_item: &Option<String>,
168 parent_id: Option<hir::HirId>,
169 extra_fragment: &Option<String>,
170 item_opt: Option<&Item>,
171 ) -> Result<(Res, Option<String>), ErrorKind> {
174 // In case we're in a module, try to resolve the relative path.
175 if let Some(module_id) = parent_id.or(self.mod_ids.last().cloned()) {
176 let module_id = cx.tcx.hir().local_def_id(module_id);
177 let result = cx.enter_resolver(|resolver| {
178 resolver.resolve_str_path_error(DUMMY_SP, &path_str, ns, module_id)
180 let result = match result {
181 Ok((_, Res::Err)) => Err(ErrorKind::ResolutionFailure),
182 _ => result.map_err(|_| ErrorKind::ResolutionFailure),
185 if let Ok((_, res)) = result {
186 let res = res.map_id(|_| panic!("unexpected node_id"));
187 // In case this is a trait item, skip the
188 // early return and try looking for the trait.
189 let value = match res {
190 Res::Def(DefKind::AssocFn | DefKind::AssocConst, _) => true,
191 Res::Def(DefKind::AssocTy, _) => false,
192 Res::Def(DefKind::Variant, _) => {
193 return handle_variant(cx, res, extra_fragment);
195 // Not a trait item; just return what we found.
197 if extra_fragment.is_some() {
198 return Err(ErrorKind::AnchorFailure(
199 "primitive types cannot be followed by anchors",
202 return Ok((res, Some(path_str.to_owned())));
204 _ => return Ok((res, extra_fragment.clone())),
207 if value != (ns == ValueNS) {
208 return Err(ErrorKind::ResolutionFailure);
210 } else if let Some(prim) = is_primitive(path_str, ns) {
211 if extra_fragment.is_some() {
212 return Err(ErrorKind::AnchorFailure(
213 "primitive types cannot be followed by anchors",
216 return Ok((prim, Some(path_str.to_owned())));
218 // If resolution failed, it may still be a method
219 // because methods are not handled by the resolver
220 // If so, bail when we're not looking for a value.
222 return Err(ErrorKind::ResolutionFailure);
226 // Try looking for methods and associated items.
227 let mut split = path_str.rsplitn(2, "::");
229 split.next().map(|f| Symbol::intern(f)).ok_or(ErrorKind::ResolutionFailure)?;
233 if f == "self" || f == "Self" {
234 if let Some(name) = current_item.as_ref() {
240 .ok_or(ErrorKind::ResolutionFailure)?;
242 if let Some(prim) = is_primitive(&path, TypeNS) {
243 let did = primitive_impl(cx, &path).ok_or(ErrorKind::ResolutionFailure)?;
246 .associated_items(did)
247 .filter_by_name_unhygienic(item_name)
249 .and_then(|item| match item.kind {
250 ty::AssocKind::Fn => Some("method"),
253 .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name))))
254 .ok_or(ErrorKind::ResolutionFailure);
258 .enter_resolver(|resolver| {
259 resolver.resolve_str_path_error(DUMMY_SP, &path, TypeNS, module_id)
261 .map_err(|_| ErrorKind::ResolutionFailure)?;
262 if let Res::Err = ty_res {
263 return self.variant_field(path_str, current_item, module_id);
265 let ty_res = ty_res.map_id(|_| panic!("unexpected node_id"));
268 DefKind::Struct | DefKind::Union | DefKind::Enum | DefKind::TyAlias,
271 // Checks if item_name belongs to `impl SomeItem`
276 .flat_map(|imp| cx.tcx.associated_items(*imp).in_definition_order())
277 .find(|item| item.ident.name == item_name);
278 let trait_item = item_opt
279 .and_then(|item| self.cx.as_local_hir_id(item.def_id))
280 .and_then(|item_hir| {
281 // Checks if item_name belongs to `impl SomeTrait for SomeItem`
282 let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
283 let item_parent = self.cx.tcx.hir().find(parent_hir);
285 Some(hir::Node::Item(hir::Item {
286 kind: hir::ItemKind::Impl { of_trait: Some(_), self_ty, .. },
290 .associated_item_def_ids(self_ty.hir_id.owner)
293 let associated_item = cx.tcx.associated_item(*child);
296 .find(|child| child.ident.name == item_name),
300 let item = match (impl_item, trait_item) {
301 (Some(from_impl), Some(_)) => {
302 // Although it's ambiguous, return impl version for compat. sake.
303 // To handle that properly resolve() would have to support
305 // [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn)
308 (None, Some(from_trait)) => Some(from_trait),
309 (Some(from_impl), None) => Some(from_impl),
313 if let Some(item) = item {
314 let out = match item.kind {
315 ty::AssocKind::Fn if ns == ValueNS => "method",
316 ty::AssocKind::Const if ns == ValueNS => "associatedconstant",
317 ty::AssocKind::Type if ns == ValueNS => "associatedtype",
318 _ => return self.variant_field(path_str, current_item, module_id),
320 if extra_fragment.is_some() {
321 Err(ErrorKind::AnchorFailure(if item.kind == ty::AssocKind::Fn {
322 "methods cannot be followed by anchors"
324 "associated constants cannot be followed by anchors"
327 Ok((ty_res, Some(format!("{}.{}", out, item_name))))
330 match cx.tcx.type_of(did).kind {
332 if let Some(item) = if def.is_enum() {
333 def.all_fields().find(|item| item.ident.name == item_name)
335 def.non_enum_variant()
338 .find(|item| item.ident.name == item_name)
340 if extra_fragment.is_some() {
341 Err(ErrorKind::AnchorFailure(if def.is_enum() {
342 "enum variants cannot be followed by anchors"
344 "struct fields cannot be followed by anchors"
361 self.variant_field(path_str, current_item, module_id)
364 _ => self.variant_field(path_str, current_item, module_id),
368 Res::Def(DefKind::Trait, did) => {
371 .associated_item_def_ids(did)
373 .map(|item| cx.tcx.associated_item(*item))
374 .find(|item| item.ident.name == item_name);
375 if let Some(item) = item {
378 ty::AssocKind::Const if ns == ValueNS => "associatedconstant",
379 ty::AssocKind::Type if ns == TypeNS => "associatedtype",
380 ty::AssocKind::Fn if ns == ValueNS => {
381 if item.defaultness.has_value() { "method" } else { "tymethod" }
383 _ => return self.variant_field(path_str, current_item, module_id),
386 if extra_fragment.is_some() {
387 Err(ErrorKind::AnchorFailure(if item.kind == ty::AssocKind::Const {
388 "associated constants cannot be followed by anchors"
389 } else if item.kind == ty::AssocKind::Type {
390 "associated types cannot be followed by anchors"
392 "methods cannot be followed by anchors"
395 Ok((ty_res, Some(format!("{}.{}", kind, item_name))))
398 self.variant_field(path_str, current_item, module_id)
401 _ => self.variant_field(path_str, current_item, module_id),
404 debug!("attempting to resolve item without parent module: {}", path_str);
405 Err(ErrorKind::ResolutionFailure)
410 impl<'a, 'tcx> DocFolder for LinkCollector<'a, 'tcx> {
411 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
412 let item_hir_id = if item.is_mod() {
413 if let Some(def_id) = item.def_id.as_local() {
414 Some(self.cx.tcx.hir().as_local_hir_id(def_id))
416 debug!("attempting to fold on a non-local item: {:?}", item);
417 return self.fold_item_recur(item);
423 // FIXME: get the resolver to work with non-local resolve scopes.
424 let parent_node = self.cx.as_local_hir_id(item.def_id).and_then(|hir_id| {
425 // FIXME: this fails hard for impls in non-module scope, but is necessary for the
426 // current `resolve()` implementation.
427 match self.cx.as_local_hir_id(self.cx.tcx.parent_module(hir_id).to_def_id()).unwrap() {
428 id if id != hir_id => Some(id),
433 if parent_node.is_some() {
434 debug!("got parent node for {:?} {:?}, id {:?}", item.type_(), item.name, item.def_id);
437 let current_item = match item.inner {
439 if item.attrs.inner_docs {
440 if item_hir_id.unwrap() != hir::CRATE_HIR_ID { item.name.clone() } else { None }
442 match parent_node.or(self.mod_ids.last().cloned()) {
443 Some(parent) if parent != hir::CRATE_HIR_ID => {
444 // FIXME: can we pull the parent module's name from elsewhere?
445 Some(self.cx.tcx.hir().name(parent).to_string())
451 ImplItem(Impl { ref for_, .. }) => {
452 for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string())
454 // we don't display docs on `extern crate` items anyway, so don't process them.
455 ExternCrateItem(..) => return self.fold_item_recur(item),
456 ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()),
457 MacroItem(..) => None,
458 _ => item.name.clone(),
461 if item.is_mod() && item.attrs.inner_docs {
462 self.mod_ids.push(item_hir_id.unwrap());
466 let dox = item.attrs.collapsed_doc_value().unwrap_or_else(String::new);
468 look_for_tests(&cx, &dox, &item, true);
470 // find item's parent to resolve `Self` in item's docs below
471 let parent_name = self.cx.as_local_hir_id(item.def_id).and_then(|item_hir| {
472 let parent_hir = self.cx.tcx.hir().get_parent_item(item_hir);
473 let item_parent = self.cx.tcx.hir().find(parent_hir);
475 Some(hir::Node::Item(hir::Item {
477 hir::ItemKind::Impl {
481 hir::TyKind::Path(hir::QPath::Resolved(
483 hir::Path { segments, .. },
490 })) => segments.first().and_then(|seg| Some(seg.ident.to_string())),
491 Some(hir::Node::Item(hir::Item {
492 ident, kind: hir::ItemKind::Enum(..), ..
494 | Some(hir::Node::Item(hir::Item {
495 ident, kind: hir::ItemKind::Struct(..), ..
497 | Some(hir::Node::Item(hir::Item {
498 ident, kind: hir::ItemKind::Union(..), ..
500 | Some(hir::Node::Item(hir::Item {
501 ident, kind: hir::ItemKind::Trait(..), ..
502 })) => Some(ident.to_string()),
507 for (ori_link, link_range) in markdown_links(&dox) {
508 // Bail early for real links.
509 if ori_link.contains('/') {
513 // [] is mostly likely not supposed to be a link
514 if ori_link.is_empty() {
518 let link = ori_link.replace("`", "");
519 let parts = link.split('#').collect::<Vec<_>>();
520 let (link, extra_fragment) = if parts.len() > 2 {
527 "has an issue with the link anchor.",
528 "only one `#` is allowed in a link",
532 } else if parts.len() == 2 {
533 if parts[0].trim().is_empty() {
534 // This is an anchor to an element of the current page, nothing to do in here!
537 (parts[0].to_owned(), Some(parts[1].to_owned()))
539 (parts[0].to_owned(), None)
541 let (res, fragment) = {
543 let mut path_str = if let Some(prefix) =
544 ["struct@", "enum@", "type@", "trait@", "union@"]
546 .find(|p| link.starts_with(**p))
549 link.trim_start_matches(prefix)
550 } else if let Some(prefix) = [
561 .find(|p| link.starts_with(**p))
563 kind = Some(ValueNS);
564 link.trim_start_matches(prefix)
565 } else if link.ends_with("()") {
566 kind = Some(ValueNS);
567 link.trim_end_matches("()")
568 } else if link.starts_with("macro@") {
569 kind = Some(MacroNS);
570 link.trim_start_matches("macro@")
571 } else if link.ends_with('!') {
572 kind = Some(MacroNS);
573 link.trim_end_matches('!')
579 if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ch == ':' || ch == '_')) {
583 // In order to correctly resolve intra-doc-links we need to
584 // pick a base AST node to work from. If the documentation for
585 // this module came from an inner comment (//!) then we anchor
586 // our name resolution *inside* the module. If, on the other
587 // hand it was an outer comment (///) then we anchor the name
588 // resolution in the parent module on the basis that the names
589 // used are more likely to be intended to be parent names. For
590 // this, we set base_node to None for inner comments since
591 // we've already pushed this node onto the resolution stack but
592 // for outer comments we explicitly try and resolve against the
593 // parent_node first.
595 if item.is_mod() && item.attrs.inner_docs { None } else { parent_node };
598 // replace `Self` with suitable item's parent name
599 if path_str.starts_with("Self::") {
600 if let Some(ref name) = parent_name {
601 resolved_self = format!("{}::{}", name, &path_str[6..]);
602 path_str = &resolved_self;
607 Some(ns @ ValueNS) => {
617 Err(ErrorKind::ResolutionFailure) => {
618 resolution_failure(cx, &item, path_str, &dox, link_range);
619 // This could just be a normal link or a broken link
620 // we could potentially check if something is
621 // "intra-doc-link-like" and warn in that case.
624 Err(ErrorKind::AnchorFailure(msg)) => {
625 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
630 Some(ns @ TypeNS) => {
640 Err(ErrorKind::ResolutionFailure) => {
641 resolution_failure(cx, &item, path_str, &dox, link_range);
642 // This could just be a normal link.
645 Err(ErrorKind::AnchorFailure(msg)) => {
646 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
653 let candidates = PerNS {
655 .macro_resolve(path_str, base_node)
656 .map(|res| (res, extra_fragment.clone())),
657 type_ns: match self.resolve(
665 Err(ErrorKind::AnchorFailure(msg)) => {
666 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
671 value_ns: match self.resolve(
679 Err(ErrorKind::AnchorFailure(msg)) => {
680 anchor_failure(cx, &item, &ori_link, &dox, link_range, msg);
685 .and_then(|(res, fragment)| {
686 // Constructors are picked up in the type namespace.
688 Res::Def(DefKind::Ctor(..), _) | Res::SelfCtor(..) => None,
689 _ => match (fragment, extra_fragment) {
690 (Some(fragment), Some(_)) => {
691 // Shouldn't happen but who knows?
692 Some((res, Some(fragment)))
694 (fragment, None) | (None, fragment) => {
695 Some((res, fragment))
702 if candidates.is_empty() {
703 resolution_failure(cx, &item, path_str, &dox, link_range);
704 // this could just be a normal link
708 let is_unambiguous = candidates.clone().present_items().count() == 1;
710 candidates.present_items().next().unwrap()
718 candidates.map(|candidate| candidate.map(|(res, _)| res)),
724 if let Some(res) = self.macro_resolve(path_str, base_node) {
725 (res, extra_fragment)
727 resolution_failure(cx, &item, path_str, &dox, link_range);
734 if let Res::PrimTy(_) = res {
735 item.attrs.links.push((ori_link, None, fragment));
737 let id = register_res(cx, res);
738 item.attrs.links.push((ori_link, Some(id), fragment));
742 if item.is_mod() && !item.attrs.inner_docs {
743 self.mod_ids.push(item_hir_id.unwrap());
747 let ret = self.fold_item_recur(item);
753 self.fold_item_recur(item)
757 // FIXME: if we can resolve intra-doc links from other crates, we can use the stock
758 // `fold_crate`, but until then we should avoid scanning `krate.external_traits` since those
759 // will never resolve properly
760 fn fold_crate(&mut self, mut c: Crate) -> Crate {
761 c.module = c.module.take().and_then(|module| self.fold_item(module));
772 link_range: Option<Range<usize>>,
775 help_msg: Option<&str>,
777 let hir_id = match cx.as_local_hir_id(item.def_id) {
778 Some(hir_id) => hir_id,
780 // If non-local, no need to check anything.
784 let attrs = &item.attrs;
785 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
787 cx.tcx.struct_span_lint_hir(
788 lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,
792 let mut diag = lint.build(&format!("`[{}]` {}", path_str, err_msg));
793 if let Some(link_range) = link_range {
794 if let Some(sp) = super::source_span_for_markdown_range(cx, dox, &link_range, attrs)
797 diag.span_label(sp, short_err_msg);
799 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
802 // last_new_line_offset
803 let last_new_line_offset =
804 dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
805 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
807 // Print the line containing the `link_range` and manually mark it with '^'s.
809 "the link appears in this line:\n\n{line}\n\
810 {indicator: <before$}{indicator:^<found$}",
813 before = link_range.start - last_new_line_offset,
814 found = link_range.len(),
818 if let Some(help_msg) = help_msg {
826 /// Reports a resolution failure diagnostic.
828 /// If we cannot find the exact source span of the resolution failure, we use the span of the
829 /// documentation attributes themselves. This is a little heavy-handed, so we display the markdown
830 /// line containing the failure as a note as well.
831 fn resolution_failure(
836 link_range: Option<Range<usize>>,
844 "cannot be resolved, ignoring it.",
845 "cannot be resolved, ignoring",
846 Some("to escape `[` and `]` characters, just add '\\' before them like `\\[` or `\\]`"),
855 link_range: Option<Range<usize>>,
864 "has an issue with the link anchor.",
875 link_range: Option<Range<usize>>,
876 candidates: PerNS<Option<Res>>,
878 let hir_id = match cx.as_local_hir_id(item.def_id) {
879 Some(hir_id) => hir_id,
881 // If non-local, no need to check anything.
885 let attrs = &item.attrs;
886 let sp = span_of_attrs(attrs).unwrap_or(item.source.span());
888 cx.tcx.struct_span_lint_hir(
889 lint::builtin::INTRA_DOC_LINK_RESOLUTION_FAILURE,
893 let mut msg = format!("`{}` is ", path_str);
895 let candidates = [TypeNS, ValueNS, MacroNS]
897 .filter_map(|&ns| candidates[ns].map(|res| (res, ns)))
898 .collect::<Vec<_>>();
899 match candidates.as_slice() {
900 [(first_def, _), (second_def, _)] => {
902 "both {} {} and {} {}",
905 second_def.article(),
910 let mut candidates = candidates.iter().peekable();
911 while let Some((res, _)) = candidates.next() {
912 if candidates.peek().is_some() {
913 msg += &format!("{} {}, ", res.article(), res.descr());
915 msg += &format!("and {} {}", res.article(), res.descr());
921 let mut diag = lint.build(&msg);
923 if let Some(link_range) = link_range {
924 if let Some(sp) = super::source_span_for_markdown_range(cx, dox, &link_range, attrs)
927 diag.span_label(sp, "ambiguous link");
929 for (res, ns) in candidates {
930 let (action, mut suggestion) = match res {
931 Res::Def(DefKind::AssocFn | DefKind::Fn, _) => {
932 ("add parentheses", format!("{}()", path_str))
934 Res::Def(DefKind::Macro(..), _) => {
935 ("add an exclamation mark", format!("{}!", path_str))
938 let type_ = match (res, ns) {
939 (Res::Def(DefKind::Const, _), _) => "const",
940 (Res::Def(DefKind::Static, _), _) => "static",
941 (Res::Def(DefKind::Struct, _), _) => "struct",
942 (Res::Def(DefKind::Enum, _), _) => "enum",
943 (Res::Def(DefKind::Union, _), _) => "union",
944 (Res::Def(DefKind::Trait, _), _) => "trait",
945 (Res::Def(DefKind::Mod, _), _) => "module",
946 (_, TypeNS) => "type",
947 (_, ValueNS) => "value",
948 (_, MacroNS) => "macro",
951 // FIXME: if this is an implied shortcut link, it's bad style to suggest `@`
952 ("prefix with the item type", format!("{}@{}", type_, path_str))
956 if dox.bytes().nth(link_range.start) == Some(b'`') {
957 suggestion = format!("`{}`", suggestion);
960 diag.span_suggestion(
962 &format!("to link to the {}, {}", res.descr(), action),
964 Applicability::MaybeIncorrect,
968 // blah blah blah\nblah\nblah [blah] blah blah\nblah blah
971 // last_new_line_offset
972 let last_new_line_offset =
973 dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1);
974 let line = dox[last_new_line_offset..].lines().next().unwrap_or("");
976 // Print the line containing the `link_range` and manually mark it with '^'s.
978 "the link appears in this line:\n\n{line}\n\
979 {indicator: <before$}{indicator:^<found$}",
982 before = link_range.start - last_new_line_offset,
983 found = link_range.len(),
992 /// Given an enum variant's res, return the res of its enum and the associated fragment.
996 extra_fragment: &Option<String>,
997 ) -> Result<(Res, Option<String>), ErrorKind> {
998 use rustc_middle::ty::DefIdTree;
1000 if extra_fragment.is_some() {
1001 return Err(ErrorKind::AnchorFailure("variants cannot be followed by anchors"));
1003 let parent = if let Some(parent) = cx.tcx.parent(res.def_id()) {
1006 return Err(ErrorKind::ResolutionFailure);
1008 let parent_def = Res::Def(DefKind::Enum, parent);
1009 let variant = cx.tcx.expect_variant_res(res);
1010 Ok((parent_def, Some(format!("{}.v", variant.ident.name))))
1013 const PRIMITIVES: &[(&str, Res)] = &[
1014 ("u8", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U8))),
1015 ("u16", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U16))),
1016 ("u32", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U32))),
1017 ("u64", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U64))),
1018 ("u128", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::U128))),
1019 ("usize", Res::PrimTy(hir::PrimTy::Uint(rustc_ast::ast::UintTy::Usize))),
1020 ("i8", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I8))),
1021 ("i16", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I16))),
1022 ("i32", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I32))),
1023 ("i64", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I64))),
1024 ("i128", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::I128))),
1025 ("isize", Res::PrimTy(hir::PrimTy::Int(rustc_ast::ast::IntTy::Isize))),
1026 ("f32", Res::PrimTy(hir::PrimTy::Float(rustc_ast::ast::FloatTy::F32))),
1027 ("f64", Res::PrimTy(hir::PrimTy::Float(rustc_ast::ast::FloatTy::F64))),
1028 ("str", Res::PrimTy(hir::PrimTy::Str)),
1029 ("bool", Res::PrimTy(hir::PrimTy::Bool)),
1030 ("char", Res::PrimTy(hir::PrimTy::Char)),
1033 fn is_primitive(path_str: &str, ns: Namespace) -> Option<Res> {
1034 if ns == TypeNS { PRIMITIVES.iter().find(|x| x.0 == path_str).map(|x| x.1) } else { None }
1037 fn primitive_impl(cx: &DocContext<'_>, path_str: &str) -> Option<DefId> {
1040 "u8" => tcx.lang_items().u8_impl(),
1041 "u16" => tcx.lang_items().u16_impl(),
1042 "u32" => tcx.lang_items().u32_impl(),
1043 "u64" => tcx.lang_items().u64_impl(),
1044 "u128" => tcx.lang_items().u128_impl(),
1045 "usize" => tcx.lang_items().usize_impl(),
1046 "i8" => tcx.lang_items().i8_impl(),
1047 "i16" => tcx.lang_items().i16_impl(),
1048 "i32" => tcx.lang_items().i32_impl(),
1049 "i64" => tcx.lang_items().i64_impl(),
1050 "i128" => tcx.lang_items().i128_impl(),
1051 "isize" => tcx.lang_items().isize_impl(),
1052 "f32" => tcx.lang_items().f32_impl(),
1053 "f64" => tcx.lang_items().f64_impl(),
1054 "str" => tcx.lang_items().str_impl(),
1055 "bool" => tcx.lang_items().bool_impl(),
1056 "char" => tcx.lang_items().char_impl(),