Skip to main content

hir_def/item_tree/
attrs.rs

1//! Defines attribute helpers for name resolution.
2//!
3//! Notice we don't preserve all attributes for name resolution, to save space:
4//! for example, we skip doc comments (desugared to `#[doc = "..."]` attributes)
5//! and `#[inline]`. The filtered attributes are listed in [`hir_expand::attrs`].
6
7use std::{
8    borrow::Cow,
9    convert::Infallible,
10    ops::{self, ControlFlow},
11};
12
13use base_db::SourceDatabase;
14use cfg::{CfgExpr, CfgOptions};
15use either::Either;
16use hir_expand::{
17    attrs::{Attr, AttrId, AttrInput, collect_item_tree_attrs},
18    mod_path::ModPath,
19    name::Name,
20};
21use intern::{Interned, Symbol, sym};
22use syntax::{AstNode, ast};
23use syntax_bridge::DocCommentDesugarMode;
24use tt::literal_from_str;
25
26use crate::item_tree::lower::Ctx;
27
28#[derive(Debug, PartialEq, Eq)]
29pub(crate) enum AttrsOrCfg {
30    Enabled {
31        attrs: AttrsOwned,
32    },
33    /// This only collects the attributes up to the disabled `cfg` (this is what needed for crate-level attributes.)
34    CfgDisabled(Box<(CfgExpr, AttrsOwned)>),
35}
36
37impl Default for AttrsOrCfg {
38    #[inline]
39    fn default() -> Self {
40        AttrsOrCfg::Enabled { attrs: AttrsOwned(Box::new([])) }
41    }
42}
43
44impl AttrsOrCfg {
45    pub(crate) fn lower<'a, S>(
46        db: &dyn SourceDatabase,
47        owner: &dyn ast::HasAttrs,
48        cfg_options: &dyn Fn() -> &'a CfgOptions,
49        span_map: S,
50    ) -> AttrsOrCfg
51    where
52        S: syntax_bridge::SpanMapper + Copy,
53    {
54        let mut attrs = Vec::new();
55        let result = collect_item_tree_attrs::<Infallible>(owner, cfg_options, |meta, _| {
56            // NOTE: We cannot early return from this function, *every* attribute must be pushed, otherwise we'll mess the `AttrId`
57            // tracking.
58            let path = meta.path();
59            let path_range = path
60                .as_ref()
61                .map(|path| path.syntax().text_range())
62                .unwrap_or_else(|| meta.syntax().text_range());
63            let (span, input) = match &meta {
64                ast::Meta::KeyValueMeta(meta) => {
65                    let span = span_map.span_for(path_range);
66                    let input = meta.expr().and_then(|value| {
67                        if let ast::Expr::Literal(value) = value
68                            && let Ok(lit) = literal_from_str(
69                                value.token().text(),
70                                span_map.span_for(value.syntax().text_range()),
71                            )
72                        {
73                            Some(Box::new(AttrInput::Literal(lit)))
74                        } else {
75                            None
76                        }
77                    });
78                    (span, input)
79                }
80                ast::Meta::TokenTreeMeta(meta) => {
81                    let span = span_map.span_for(path_range);
82                    let tt = syntax_bridge::syntax_node_to_token_tree(
83                        &meta
84                            .token_tree()
85                            .map(|it| it.syntax().clone())
86                            .unwrap_or_else(|| meta.syntax().clone()),
87                        span_map,
88                        span,
89                        DocCommentDesugarMode::ProcMacro,
90                    );
91                    let input = Some(Box::new(AttrInput::TokenTree(tt)));
92                    (span, input)
93                }
94                ast::Meta::PathMeta(_) => {
95                    let span = span_map.span_for(path_range);
96                    (span, None)
97                }
98                ast::Meta::CfgMeta(_) | ast::Meta::CfgAttrMeta(_) | ast::Meta::UnsafeMeta(_) => {
99                    unreachable!(
100                        "`cfg`, `cfg_attr` and `unsafe(...)` are handled in `collect_item_tree_attrs()`"
101                    )
102                }
103            };
104
105            let path = path.and_then(|path| {
106                ModPath::from_src(db, path, &mut |range| span_map.span_for(range).ctx)
107            });
108            let path = path.unwrap_or_else(|| Name::missing().into());
109
110            attrs.push(Attr { path: Interned::new(path), input, ctxt: span.ctx });
111            ControlFlow::Continue(())
112        });
113        let attrs = AttrsOwned(attrs.into_boxed_slice());
114        match result {
115            Some(Either::Right(cfg)) => AttrsOrCfg::CfgDisabled(Box::new((cfg, attrs))),
116            None => AttrsOrCfg::Enabled { attrs },
117        }
118    }
119
120    // Merges two `AttrsOrCfg`s, assuming `self` is placed before `other` in the source code.
121    // The operation follows these rules:
122    //
123    //   - If `self` and `other` are both `AttrsOrCfg::Enabled`, the result is a new
124    //     `AttrsOrCfg::Enabled`. It contains the concatenation of `self`'s attributes followed by
125    //     `other`'s.
126    //   - If `self` is `AttrsOrCfg::Enabled` but `other` is `AttrsOrCfg::CfgDisabled`, the result
127    //     is a new `AttrsOrCfg::CfgDisabled`. It contains the concatenation of `self`'s attributes
128    //     followed by `other`'s.
129    //   - If `self` is `AttrsOrCfg::CfgDisabled`, return `self` as-is.
130    //
131    // The rationale is that attribute collection is sequential and order-sensitive. This operation
132    // preserves those semantics when combining attributes from two different sources.
133    // `AttrsOrCfg::CfgDisabled` marks a point where collection stops due to a false `#![cfg(...)]`
134    // condition. It acts as a "breakpoint": attributes beyond it are not collected. Therefore,
135    // when merging, an `AttrsOrCfg::CfgDisabled` on the left-hand side short-circuits the
136    // operation, while an `AttrsOrCfg::CfgDisabled` on the right-hand side preserves all
137    // attributes collected up to that point.
138    //
139    // Note that this operation is neither commutative nor associative.
140    pub(crate) fn merge(self, other: AttrsOrCfg) -> AttrsOrCfg {
141        match (self, other) {
142            (AttrsOrCfg::Enabled { attrs }, AttrsOrCfg::Enabled { attrs: other_attrs }) => {
143                let mut v = attrs.0.into_vec();
144                v.extend(other_attrs.0);
145                AttrsOrCfg::Enabled { attrs: AttrsOwned(v.into_boxed_slice()) }
146            }
147            (AttrsOrCfg::Enabled { attrs }, AttrsOrCfg::CfgDisabled(mut other)) => {
148                let other_attrs = &mut other.1;
149                let mut v = attrs.0.into_vec();
150                v.extend(std::mem::take(&mut other_attrs.0));
151                other_attrs.0 = v.into_boxed_slice();
152                AttrsOrCfg::CfgDisabled(other)
153            }
154            (this @ AttrsOrCfg::CfgDisabled(_), _) => this,
155        }
156    }
157}
158
159#[derive(Debug, PartialEq, Eq)]
160pub(crate) struct AttrsOwned(Box<[Attr]>);
161
162#[derive(Debug, Clone, Copy)]
163pub(crate) struct Attrs<'a>(&'a [Attr]);
164
165impl ops::Deref for Attrs<'_> {
166    type Target = [Attr];
167
168    #[inline]
169    fn deref(&self) -> &Self::Target {
170        self.0
171    }
172}
173
174impl Ctx<'_> {
175    #[inline]
176    pub(super) fn lower_attrs(&self, owner: &dyn ast::HasAttrs) -> AttrsOrCfg {
177        AttrsOrCfg::lower(self.db, owner, &|| self.cfg_options(), self.span_map())
178    }
179}
180
181impl AttrsOwned {
182    #[inline]
183    pub(crate) fn as_ref(&self) -> Attrs<'_> {
184        Attrs(&self.0)
185    }
186}
187
188impl<'a> Attrs<'a> {
189    pub(crate) const EMPTY: Self = Attrs(&[]);
190
191    #[inline]
192    pub(crate) fn by_key(self, key: Symbol) -> AttrQuery<'a> {
193        AttrQuery { attrs: self, key }
194    }
195
196    #[inline]
197    pub(crate) fn iter(self) -> impl Iterator<Item = (AttrId, &'a Attr)> {
198        self.0.iter().enumerate().map(|(id, attr)| (AttrId::from_item_tree_index(id as u32), attr))
199    }
200
201    #[inline]
202    pub(crate) fn iter_after(
203        self,
204        after: Option<AttrId>,
205    ) -> impl Iterator<Item = (AttrId, &'a Attr)> {
206        let skip = after.map_or(0, |after| after.item_tree_index() + 1);
207        self.0[skip as usize..]
208            .iter()
209            .enumerate()
210            .map(move |(id, attr)| (AttrId::from_item_tree_index(id as u32 + skip), attr))
211    }
212
213    #[inline]
214    pub(crate) fn is_proc_macro(&self) -> bool {
215        self.by_key(sym::proc_macro).exists()
216    }
217
218    #[inline]
219    pub(crate) fn is_proc_macro_attribute(&self) -> bool {
220        self.by_key(sym::proc_macro_attribute).exists()
221    }
222}
223#[derive(Debug, Clone)]
224pub(crate) struct AttrQuery<'attr> {
225    attrs: Attrs<'attr>,
226    key: Symbol,
227}
228
229impl<'attr> AttrQuery<'attr> {
230    #[inline]
231    pub(crate) fn tt_values(self) -> impl Iterator<Item = &'attr crate::tt::TopSubtree> {
232        self.attrs().filter_map(|attr| attr.token_tree_value())
233    }
234
235    #[inline]
236    pub(crate) fn string_value_with_span(self) -> Option<(&'attr str, span::Span)> {
237        self.attrs().find_map(|attr| attr.string_value_with_span())
238    }
239
240    #[inline]
241    pub(crate) fn string_value_unescape(self) -> Option<Cow<'attr, str>> {
242        self.attrs().find_map(|attr| attr.string_value_unescape())
243    }
244
245    #[inline]
246    pub(crate) fn exists(self) -> bool {
247        self.attrs().next().is_some()
248    }
249
250    #[inline]
251    pub(crate) fn attrs(self) -> impl Iterator<Item = &'attr Attr> + Clone {
252        let key = self.key;
253        self.attrs.0.iter().filter(move |attr| attr.path.as_ident().is_some_and(|s| *s == key))
254    }
255}
256
257impl AttrsOrCfg {
258    #[inline]
259    pub(super) fn is_empty(&self) -> bool {
260        matches!(self, AttrsOrCfg::Enabled { attrs } if attrs.0.is_empty())
261    }
262}