rustdoc/passes/
propagate_doc_cfg.rs1use rustc_data_structures::fx::FxHashMap;
4use rustc_hir::Attribute;
5use rustc_hir::attrs::{AttributeKind, DocAttribute};
6
7use crate::clean::inline::{load_attrs, merge_attrs};
8use crate::clean::{CfgInfo, Crate, Item, ItemId, ItemKind};
9use crate::core::DocContext;
10use crate::fold::DocFolder;
11use crate::passes::Pass;
12
13pub(crate) const PROPAGATE_DOC_CFG: Pass = Pass {
14 name: "propagate-doc-cfg",
15 run: Some(propagate_doc_cfg),
16 description: "propagates `#[doc(cfg(...))]` to child items",
17};
18
19pub(crate) fn propagate_doc_cfg(cr: Crate, cx: &mut DocContext<'_>) -> Crate {
20 if cx.tcx.features().doc_cfg() {
21 CfgPropagator { cx, cfg_info: CfgInfo::default(), impl_cfg_info: FxHashMap::default() }
22 .fold_crate(cr)
23 } else {
24 cr
25 }
26}
27
28struct CfgPropagator<'a, 'tcx> {
29 cx: &'a mut DocContext<'tcx>,
30 cfg_info: CfgInfo,
31
32 impl_cfg_info: FxHashMap<ItemId, CfgInfo>,
35}
36
37fn add_only_cfg_attributes(attrs: &mut Vec<Attribute>, new_attrs: &[Attribute]) {
40 for attr in new_attrs {
41 if let Attribute::Parsed(AttributeKind::Doc(d)) = attr
42 && !d.cfg.is_empty()
43 {
44 let mut new_attr = DocAttribute::default();
45 new_attr.cfg = d.cfg.clone();
46 attrs.push(Attribute::Parsed(AttributeKind::Doc(Box::new(new_attr))));
47 } else if let Attribute::Parsed(AttributeKind::CfgTrace(..)) = attr {
48 attrs.push(attr.clone());
50 }
51 }
52}
53
54impl CfgPropagator<'_, '_> {
55 fn merge_with_parent_attributes(&mut self, item: &mut Item) {
58 let mut attrs = Vec::new();
59 if matches!(item.kind, ItemKind::ImplItem(_))
64 && let Some(mut next_def_id) = item.item_id.as_local_def_id()
65 {
66 while let Some(parent_def_id) = self.cx.tcx.opt_local_parent(next_def_id) {
67 let x = load_attrs(self.cx.tcx, parent_def_id.to_def_id());
68 add_only_cfg_attributes(&mut attrs, x);
69 next_def_id = parent_def_id;
70 }
71 }
72
73 let (_, cfg) = merge_attrs(
74 self.cx.tcx,
75 item.attrs.other_attrs.as_slice(),
76 Some((&attrs, None)),
77 &mut self.cfg_info,
78 );
79 item.inner.cfg = cfg;
80 }
81}
82
83impl DocFolder for CfgPropagator<'_, '_> {
84 fn fold_item(&mut self, mut item: Item) -> Option<Item> {
85 let old_cfg_info = self.cfg_info.clone();
86
87 if let ItemKind::ImplItem(_) = item.kind
90 && let Some(cfg_info) = self.impl_cfg_info.remove(&item.item_id)
91 {
92 self.cfg_info = cfg_info;
93 }
94
95 if let ItemKind::PlaceholderImplItem = item.kind {
96 self.impl_cfg_info.insert(item.item_id, self.cfg_info.clone());
100 } else {
101 self.merge_with_parent_attributes(&mut item);
102 }
103
104 let result = self.fold_item_recur(item);
105 self.cfg_info = old_cfg_info;
106
107 Some(result)
108 }
109}