Skip to main content

rustc_attr_ir/
attr.rs

1use std::fmt;
2
3use rustc_ast::attr::AttributeExt;
4use rustc_ast::token::DocFragmentKind;
5use rustc_ast::{AttrStyle, DelimArgs, MetaItemLit, ast, join_path_idents};
6use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
7use rustc_error_messages::{DiagArgValue, IntoDiagArg};
8use rustc_lint_defs::ToolOptions;
9use rustc_macros::{Decodable, Encodable, StableHash};
10use rustc_span::{AttrId, DUMMY_SP, Ident, Span, Symbol};
11
12use crate::AttributeKind;
13
14/// Arguments of a unparsed attribute.
15#[derive(#[automatically_derived]impl ::core::clone::Clone for AttrArgs {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Empty => AttrArgs::Empty,
            Self::Delimited(__self_0) =>
                AttrArgs::Delimited(::core::clone::Clone::clone(__self_0)),
            Self::Eq { eq_span: __self_0, expr: __self_1 } =>
                AttrArgs::Eq {
                    eq_span: ::core::clone::Clone::clone(__self_0),
                    expr: ::core::clone::Clone::clone(__self_1),
                },
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AttrArgs {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Empty => ::core::fmt::Formatter::write_str(f, "Empty"),
            Self::Delimited(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Delimited", &__self_0),
            Self::Eq { eq_span: __self_0, expr: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Eq eq_span expr", __self_0, &__self_1),
        }
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for AttrArgs {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    AttrArgs::Empty => 0u8.stable_hash(__hcx, __hasher),
                    AttrArgs::Delimited(ref __binding_0) =>
                        1u8.stable_hash(__hcx, __hasher),
                    AttrArgs::Eq {
                        eq_span: ref __binding_0, expr: ref __binding_1 } =>
                        2u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    AttrArgs::Empty => {}
                    AttrArgs::Delimited(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    AttrArgs::Eq {
                        eq_span: ref __binding_0, expr: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for AttrArgs {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        AttrArgs::Empty => { 0usize }
                        AttrArgs::Delimited(ref __binding_0) => { 1usize }
                        AttrArgs::Eq {
                            eq_span: ref __binding_0, expr: ref __binding_1 } => {
                            2usize
                        }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    AttrArgs::Empty => {}
                    AttrArgs::Delimited(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    AttrArgs::Eq {
                        eq_span: ref __binding_0, expr: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for AttrArgs {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => { AttrArgs::Empty }
                    1usize => {
                        AttrArgs::Delimited(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    2usize => {
                        AttrArgs::Eq {
                            eq_span: ::rustc_serialize::Decodable::decode(__decoder),
                            expr: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `AttrArgs`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable)]
16pub enum AttrArgs {
17    /// No arguments: `#[attr]`.
18    Empty,
19    /// Delimited arguments: `#[attr()/[]/{}]`.
20    Delimited(DelimArgs),
21    /// Arguments of a key-value attribute: `#[attr = "value"]`.
22    Eq {
23        /// Span of the `=` token.
24        eq_span: Span,
25        /// The "value".
26        expr: MetaItemLit,
27    },
28}
29
30#[derive(#[automatically_derived]impl ::core::clone::Clone for AttrPath {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        AttrPath {
            segments: ::core::clone::Clone::clone(&self.segments),
            span: ::core::clone::Clone::clone(&self.span),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AttrPath {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "AttrPath segments span", &self.segments, &&self.span)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for AttrPath {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    AttrPath { segments: ref __binding_0, span: ref __binding_1
                        } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for AttrPath {
            fn encode(&self, __encoder: &mut __E) {
                let AttrPath {
                        segments: ref __binding_0, span: ref __binding_1 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for AttrPath {
            fn decode(__decoder: &mut __D) -> Self {
                AttrPath {
                    segments: ::rustc_serialize::Decodable::decode(__decoder),
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
31pub struct AttrPath {
32    pub segments: Box<[Symbol]>,
33    pub span: Span,
34}
35
36impl IntoDiagArg for AttrPath {
37    fn into_diag_arg(self, path: &mut Option<std::path::PathBuf>) -> DiagArgValue {
38        self.to_string().into_diag_arg(path)
39    }
40}
41
42impl AttrPath {
43    pub fn from_ast(path: &ast::Path, lower_span: impl Copy + Fn(Span) -> Span) -> Self {
44        AttrPath {
45            segments: path
46                .segments
47                .iter()
48                .map(|i| i.ident.name)
49                .collect::<Vec<_>>()
50                .into_boxed_slice(),
51            span: lower_span(path.span),
52        }
53    }
54}
55
56impl fmt::Display for AttrPath {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.write_fmt(format_args!("{0}",
        join_path_idents(self.segments.iter().map(|i|
                    Ident { name: *i, span: DUMMY_SP }))))write!(
59            f,
60            "{}",
61            join_path_idents(self.segments.iter().map(|i| Ident { name: *i, span: DUMMY_SP }))
62        )
63    }
64}
65
66/// A non built-in attribute.
67///
68/// This is either a tool attribute or a derive helper attribute.
69#[derive(#[automatically_derived]impl ::core::clone::Clone for AttrItem {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        AttrItem {
            path: ::core::clone::Clone::clone(&self.path),
            args: ::core::clone::Clone::clone(&self.args),
            style: ::core::clone::Clone::clone(&self.style),
            span: ::core::clone::Clone::clone(&self.span),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for AttrItem {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "AttrItem path args style span", &self.path, &self.args,
            &self.style, &&self.span)
    }
}Debug, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for AttrItem {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    AttrItem {
                        path: ref __binding_0,
                        args: ref __binding_1,
                        style: ref __binding_2,
                        span: ref __binding_3 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                        { __binding_2.stable_hash(__hcx, __hasher); }
                        { __binding_3.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for AttrItem {
            fn encode(&self, __encoder: &mut __E) {
                let AttrItem {
                        path: ref __binding_0,
                        args: ref __binding_1,
                        style: ref __binding_2,
                        span: ref __binding_3 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                    __encoder);
                ::rustc_serialize::Encodable::<__E>::encode(__binding_3,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for AttrItem {
            fn decode(__decoder: &mut __D) -> Self {
                AttrItem {
                    path: ::rustc_serialize::Decodable::decode(__decoder),
                    args: ::rustc_serialize::Decodable::decode(__decoder),
                    style: ::rustc_serialize::Decodable::decode(__decoder),
                    span: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable)]
70pub struct AttrItem {
71    // Not lowered to hir::Path because we have no NodeId to resolve to.
72    pub path: AttrPath,
73    pub args: AttrArgs,
74    /// Denotes if the attribute decorates the following construct (outer)
75    /// or the construct this attribute is contained within (inner).
76    pub style: AttrStyle,
77    /// Span of the entire attribute
78    pub span: Span,
79}
80
81/// The derived implementation of [`StableHash`] on [`Attribute`]s shouldn't hash
82/// [`AttrId`]s. By wrapping them in this, we make sure we never do.
83#[derive(#[automatically_derived]impl ::core::marker::Copy for HashIgnoredAttrId { }Copy, #[automatically_derived]impl ::core::fmt::Debug for HashIgnoredAttrId {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "HashIgnoredAttrId attr_id", &&self.attr_id)
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for HashIgnoredAttrId {
            fn encode(&self, __encoder: &mut __E) {
                let HashIgnoredAttrId { attr_id: ref __binding_0 } = *self;
                ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                    __encoder);
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for HashIgnoredAttrId {
            fn decode(__decoder: &mut __D) -> Self {
                HashIgnoredAttrId {
                    attr_id: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };Decodable, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for HashIgnoredAttrId {
}
#[automatically_derived]impl ::core::clone::Clone for HashIgnoredAttrId {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<AttrId>;
        *self
    }
}Clone)]
84pub struct HashIgnoredAttrId {
85    pub attr_id: AttrId,
86}
87
88impl StableHash for HashIgnoredAttrId {
89    fn stable_hash<Hcx: StableHashCtxt>(&self, _hcx: &mut Hcx, _hasher: &mut StableHasher) {
90        /* we don't hash HashIgnoredAttrId, we ignore them */
91    }
92}
93/// A high level representation of an attribute.
94///
95/// Not to be confused with [`ast::Attribute`], which represents the syntax-level form of
96/// an attribute.
97///
98/// [`ast::Attribute`]: rustc_ast::ast::Attribute
99#[derive(#[automatically_derived]impl ::core::clone::Clone for Attribute {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Parsed(__self_0) =>
                Attribute::Parsed(::core::clone::Clone::clone(__self_0)),
            Self::Tool { item: __self_0, opts: __self_1 } =>
                Attribute::Tool {
                    item: ::core::clone::Clone::clone(__self_0),
                    opts: ::core::clone::Clone::clone(__self_1),
                },
            Self::DeriveHelper(__self_0) =>
                Attribute::DeriveHelper(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Attribute {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Parsed(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Parsed", &__self_0),
            Self::Tool { item: __self_0, opts: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "Tool item opts", __self_0, &__self_1),
            Self::DeriveHelper(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "DeriveHelper", &__self_0),
        }
    }
}Debug, const _: () =
    {
        impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
            for Attribute {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        Attribute::Parsed(ref __binding_0) => { 0usize }
                        Attribute::Tool {
                            item: ref __binding_0, opts: ref __binding_1 } => {
                            1usize
                        }
                        Attribute::DeriveHelper(ref __binding_0) => { 2usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    Attribute::Parsed(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                    Attribute::Tool {
                        item: ref __binding_0, opts: ref __binding_1 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    Attribute::DeriveHelper(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };Encodable, const _: () =
    {
        impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
            for Attribute {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        Attribute::Parsed(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        Attribute::Tool {
                            item: ::rustc_serialize::Decodable::decode(__decoder),
                            opts: ::rustc_serialize::Decodable::decode(__decoder),
                        }
                    }
                    2usize => {
                        Attribute::DeriveHelper(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `Attribute`, expected 0..3, actual {0}",
                                n));
                    }
                }
            }
        }
    };Decodable, const _: () =
    {
        impl ::rustc_data_structures::stable_hash::StableHash for Attribute {
            #[inline]
            fn stable_hash<__Hcx: ::rustc_data_structures::stable_hash::StableHashCtxt>(&self,
                __hcx: &mut __Hcx,
                __hasher:
                    &mut ::rustc_data_structures::stable_hash::StableHasher) {
                match *self {
                    Attribute::Parsed(ref __binding_0) =>
                        0u8.stable_hash(__hcx, __hasher),
                    Attribute::Tool {
                        item: ref __binding_0, opts: ref __binding_1 } =>
                        1u8.stable_hash(__hcx, __hasher),
                    Attribute::DeriveHelper(ref __binding_0) =>
                        2u8.stable_hash(__hcx, __hasher),
                }
                match *self {
                    Attribute::Parsed(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                    Attribute::Tool {
                        item: ref __binding_0, opts: ref __binding_1 } => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                        { __binding_1.stable_hash(__hcx, __hasher); }
                    }
                    Attribute::DeriveHelper(ref __binding_0) => {
                        { __binding_0.stable_hash(__hcx, __hasher); }
                    }
                }
            }
        }
    };StableHash)]
100pub enum Attribute {
101    /// A parsed built-in attribute.
102    ///
103    /// Parsed attributes don't generally have a span associated with them. This is because
104    /// multiple syntax-level attributes can be represented into a single semantic attribute. For
105    /// example, an item can have multiple `repr` attributes on it, which will coalesce into a
106    /// single [`AttributeKind::Repr`], and the `stable`, `unstable`, and
107    /// `rustc_allowed_through_unstable_modules` all combine into a single
108    /// [`AttributeKind::Stability`] attribute. Most `Attribute` variants do have a [`Span`] field,
109    /// though, mostly for the purpose of generating diagnostics later in the compilation process.
110    Parsed(AttributeKind),
111
112    /// A tool attribute.
113    ///
114    /// Tool attributes, with the exception of diagnostic attributes, are not converted into a
115    /// parsed form.
116    Tool { item: Box<AttrItem>, opts: ToolOptions },
117
118    /// A derive helper attribute.
119    ///
120    /// Derive helper attributes serve no use beyond macro expansion, but they are useful to
121    /// consumers of `rustdoc-json`, so we keep them around. See
122    /// <https://github.com/rust-lang/rust/issues/157107> for context.
123    DeriveHelper(Box<AttrItem>),
124}
125
126impl Attribute {
127    pub fn value_lit(&self) -> Option<&MetaItemLit> {
128        match &self {
129            Attribute::Tool { item: n, .. } | Attribute::DeriveHelper(n) => match n.as_ref() {
130                AttrItem { args: AttrArgs::Eq { eq_span: _, expr }, .. } => Some(expr),
131                _ => None,
132            },
133            _ => None,
134        }
135    }
136
137    pub fn is_prefix_attr_for_suggestions(&self) -> bool {
138        match self {
139            Attribute::Tool { item: attr, .. } | Attribute::DeriveHelper(attr) => {
140                attr.span.desugaring_kind().is_none()
141            }
142            // Other parsed attributes that can appear on expressions originate from source and
143            // should make suggestions treat the expression like a prefixed form.
144            Attribute::Parsed(_) => true,
145        }
146    }
147}
148
149impl AttributeExt for Attribute {
150    #[inline]
151    fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind, Span)> {
152        match &self {
153            Attribute::Parsed(AttributeKind::DocComment { kind, comment, span, .. }) => {
154                Some((*comment, *kind, *span))
155            }
156            _ => None,
157        }
158    }
159
160    fn doc_resolution_scope(&self) -> Option<AttrStyle> {
161        match self {
162            Attribute::Parsed(AttributeKind::DocComment { style, .. }) => Some(*style),
163            _ => None,
164        }
165    }
166}