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
54impl CfgPropagator<'_, '_> {
55    // Some items need to merge their attributes with their parents' otherwise a few of them
56    // (mostly `cfg` ones) will be missing.
57    fn merge_with_parent_attributes(&mut self, item: &mut Item) {
58        let mut attrs = Vec::new();
59        // We only need to merge an item attributes with its parent's in case it's an impl as an
60        // impl might not be defined in the same module as the item it implements.
61        //
62        // Otherwise, `cfg_info` already tracks everything we need so nothing else to do!
63        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 we have an impl, we check if it has an associated `cfg` "context", and if so we will
88        // use that context instead of the actual (wrong) one.
89        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            // If we have a placeholder impl, we store the current `cfg` "context" to be used
97            // on the actual impl later on (the impls are generated after we go through the whole
98            // AST so they're stored in the `krate` object at the end).
99            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}