Skip to main content

rustc_attr_parsing/
synthetic.rs

1use rustc_ast::SyntheticAttr;
2use rustc_ast::attr::data_structures::CfgEntry;
3use rustc_attr_ir::{Attribute, AttributeKind};
4use rustc_span::Span;
5use thin_vec::ThinVec;
6
7/// Contains the state necessary to convert synthetic attributes to parsed attributes.
8///
9/// The only conversion that really happens here is that multiple synthetic attributes are
10/// merged into a single `rustc_attr_ir::attribute`, representing their combined state.
11/// FIXME: We should make this a nice and extendable system if this is going to be used more often
12#[derive(#[automatically_derived]impl ::core::default::Default for SyntheticAttrState {
    #[inline]
    fn default() -> Self {
        SyntheticAttrState {
            cfg_trace: ::core::default::Default::default(),
            cfg_attr_trace: ::core::default::Default::default(),
            test_entrypoint: ::core::default::Default::default(),
        }
    }
}Default)]
13pub(crate) struct SyntheticAttrState {
14    /// Attribute state for `SyntheticAttr::CfgTrace` attributes.
15    cfg_trace: ThinVec<(CfgEntry, Span)>,
16
17    /// Attribute state for `SyntheticAttr::CfgAttrTrace` attributes.
18    cfg_attr_trace: ThinVec<(CfgEntry, Span)>,
19
20    /// Whether a `SyntheticAttr::TestEntrypoint` attribute was seen.
21    test_entrypoint: bool,
22}
23
24impl SyntheticAttrState {
25    pub(crate) fn accept_synthetic_attr(
26        &mut self,
27        attr_span: Span,
28        lower_span: impl Copy + Fn(Span) -> Span,
29        synthetic: &SyntheticAttr,
30    ) {
31        match synthetic {
32            SyntheticAttr::CfgTrace(cfg) => {
33                let mut cfg = cfg.clone();
34                cfg.lower_spans(lower_span);
35                self.cfg_trace.push((cfg, attr_span));
36            }
37            SyntheticAttr::CfgAttrTrace(cfg) => {
38                let mut cfg = cfg.clone();
39                cfg.lower_spans(lower_span);
40                self.cfg_attr_trace.push((cfg, attr_span));
41            }
42            SyntheticAttr::TestEntrypoint => {
43                self.test_entrypoint = true;
44            }
45        }
46    }
47
48    pub(crate) fn finalize_synthetic_attrs(self, attributes: &mut Vec<Attribute>) {
49        if !self.cfg_trace.is_empty() {
50            attributes.push(Attribute::Parsed(AttributeKind::CfgTrace(self.cfg_trace)));
51        }
52        if !self.cfg_attr_trace.is_empty() {
53            attributes.push(Attribute::Parsed(AttributeKind::CfgAttrTrace(self.cfg_attr_trace)));
54        }
55        if self.test_entrypoint {
56            attributes.push(Attribute::Parsed(AttributeKind::RustcTestEntrypointMarker));
57        }
58    }
59}