Skip to main content

rustdoc/passes/
propagate_doc_cfg.rs

1//! Propagates [`#[doc(cfg(...))]`](https://github.com/rust-lang/rust/issues/43781) to child items.
2
3use 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    /// To ensure the `doc_cfg` feature works with how `rustdoc` handles impls, we need to store
33    /// the `cfg` info of `impl`s placeholder to use them later on the "real" impl item.
34    impl_cfg_info: FxHashMap<ItemId, CfgInfo>,
35}
36
37/// This function goes through the attributes list (`new_attrs`) and extract the `cfg` tokens from
38/// it and put them into `attrs`.
39fn 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            // If it's a `cfg()` attribute, we keep it.
49            attrs.push(attr.clone());
50        }
51    }
52}
53
54/// This function goes through the attributes list (`new_attrs`) and extracts the attributes that
55/// affect the cfg state propagated to detached items.
56fn add_cfg_state_attributes(attrs: &mut Vec<Attribute>, new_attrs: &[Attribute]) {
57    for attr in new_attrs {
58        if let Attribute::Parsed(AttributeKind::Doc(d)) = attr
59            && (!d.cfg.is_empty() || !d.auto_cfg.is_empty() || !d.auto_cfg_change.is_empty())
60        {
61            let mut new_attr = DocAttribute::default();
62            new_attr.cfg = d.cfg.clone();
63            new_attr.auto_cfg = d.auto_cfg.clone();
64            new_attr.auto_cfg_change = d.auto_cfg_change.clone();
65            attrs.push(Attribute::Parsed(AttributeKind::Doc(Box::new(new_attr))));
66        } else if let Attribute::Parsed(AttributeKind::CfgTrace(..)) = attr {
67            // If it's a `cfg()` attribute, we keep it.
68            attrs.push(attr.clone());
69        }
70    }
71}
72
73impl CfgPropagator<'_, '_> {
74    // Some items need to merge their attributes with their parents' otherwise a few of them
75    // (mostly `cfg` ones) will be missing.
76    fn merge_with_parent_attributes(&mut self, item: &mut Item) {
77        let mut attrs = Vec::new();
78        // We need to merge an item attributes with its parent's in case it's an impl as an
79        // impl might not be defined in the same module as the item it implements.
80        //
81        // Otherwise, `cfg_info` already tracks everything we need so nothing else to do!
82        if matches!(item.kind, ItemKind::ImplItem(_))
83            && let Some(mut next_def_id) = item.item_id.as_local_def_id()
84        {
85            while let Some(parent_def_id) = self.cx.tcx.opt_local_parent(next_def_id) {
86                let x = load_attrs(self.cx.tcx, parent_def_id.to_def_id());
87                add_only_cfg_attributes(&mut attrs, x);
88                next_def_id = parent_def_id;
89            }
90        }
91        // We also need to merge an item attributes with its parent's in case it's a macro with
92        // the `#[macro_export]` attribute, because it might not be defined at crate root.
93        if matches!(item.kind, ItemKind::MacroItem(_))
94            && item.inner.attrs.other_attrs.iter().any(|attr| {
95                matches!(
96                    attr,
97                    rustc_hir::Attribute::Parsed(
98                        rustc_hir::attrs::AttributeKind::MacroExport { .. }
99                    )
100                )
101            })
102        {
103            for parent_def_id in &item.cfg_parent_ids_for_detached_item(self.cx.tcx) {
104                let mut parent_attrs = Vec::new();
105                add_cfg_state_attributes(
106                    &mut parent_attrs,
107                    load_attrs(self.cx.tcx, parent_def_id.to_def_id()),
108                );
109                merge_attrs(self.cx.tcx, &[], Some((&parent_attrs, None)), &mut self.cfg_info);
110            }
111        }
112
113        let (_, cfg) = merge_attrs(
114            self.cx.tcx,
115            item.attrs.other_attrs.as_slice(),
116            Some((&attrs, None)),
117            &mut self.cfg_info,
118        );
119        item.inner.cfg = cfg;
120    }
121}
122
123impl DocFolder for CfgPropagator<'_, '_> {
124    fn fold_item(&mut self, mut item: Item) -> Option<Item> {
125        let old_cfg_info = self.cfg_info.clone();
126
127        // If we have an impl, we check if it has an associated `cfg` "context", and if so we will
128        // use that context instead of the actual (wrong) one.
129        if let ItemKind::ImplItem(_) = item.kind
130            && let Some(cfg_info) = self.impl_cfg_info.remove(&item.item_id)
131        {
132            self.cfg_info = cfg_info;
133        }
134
135        if let ItemKind::PlaceholderImplItem = item.kind {
136            // If we have a placeholder impl, we store the current `cfg` "context" to be used
137            // on the actual impl later on (the impls are generated after we go through the whole
138            // AST so they're stored in the `krate` object at the end).
139            self.impl_cfg_info.insert(item.item_id, self.cfg_info.clone());
140        } else {
141            self.merge_with_parent_attributes(&mut item);
142        }
143
144        let result = self.fold_item_recur(item);
145        self.cfg_info = old_cfg_info;
146
147        Some(result)
148    }
149}