Skip to main content

hir_def/
attrs.rs

1//! Attributes for anything that is not name resolution.
2//!
3//! The fundamental idea of this module stems from the observation that most "interesting"
4//! attributes have a more memory-compact form than storing their full syntax, and
5//! that most of the attributes are flags, and those that are not are rare. Therefore,
6//! this module defines [`AttrFlags`], which is a bitflag enum that contains only a yes/no
7//! answer to whether an attribute is present on an item. For most attributes, that's all
8//! that is interesting us; for the rest of them, we define another query that extracts
9//! their data. A key part is that every one of those queries will have a wrapper method
10//! that queries (or is given) the `AttrFlags` and checks for the presence of the attribute;
11//! if it is not present, we do not call the query, to prevent Salsa from needing to record
12//! its value. This way, queries are only called on items that have the attribute, which is
13//! usually only a few.
14//!
15//! Documentation (doc comments and `#[doc = "..."]` attributes) is handled by the [`docs`]
16//! submodule.
17
18use std::{convert::Infallible, iter::Peekable, ops::ControlFlow};
19
20use base_db::{Crate, SourceDatabase};
21use cfg::{CfgExpr, CfgOptions};
22use either::Either;
23use hir_expand::{
24    InFile, Lookup,
25    attrs::{AstKeyValueMetaExt, AstPathExt, expand_cfg_attr},
26    name::Name,
27};
28use intern::Symbol;
29use itertools::Itertools;
30use la_arena::ArenaMap;
31use rustc_abi::ReprOptions;
32use rustc_hash::FxHashSet;
33use smallvec::SmallVec;
34use syntax::{
35    AstNode, AstToken, NodeOrToken, SmolStr, SourceFile, T,
36    ast::{self, HasAttrs, TokenTreeChildren},
37};
38use tt::TextSize;
39
40use crate::{
41    AdtId, AstIdLoc, AttrDefId, FieldId, FunctionId, GenericDefId, HasModule, LifetimeParamId,
42    LocalFieldId, MacroId, ModuleId, TraitId, TypeOrConstParamId, VariantId,
43    hir::generics::{GenericParams, LocalLifetimeParamId, LocalTypeOrConstParamId},
44    nameres::ModuleOrigin,
45    resolver::{HasResolver, Resolver},
46    src::{HasChildSource, HasSource},
47};
48
49pub mod docs;
50
51pub use self::docs::{Docs, IsInnerDoc};
52
53#[inline]
54fn attrs_from_ast_id_loc<N: AstNode + Into<ast::AnyHasAttrs>>(
55    db: &dyn SourceDatabase,
56    lookup: impl Lookup<Data = impl AstIdLoc<Ast = N> + HasModule>,
57) -> (InFile<ast::AnyHasAttrs>, Crate) {
58    let loc = lookup.lookup(db);
59    let source = loc.source(db);
60    let krate = loc.krate(db);
61    (source.map(|it| it.into()), krate)
62}
63
64#[inline]
65fn extract_doc_tt_attr(attr_flags: &mut AttrFlags, tt: ast::TokenTree) {
66    for atom in DocAtom::parse(tt) {
67        match atom {
68            DocAtom::Flag(flag) => match &*flag {
69                "notable_trait" => attr_flags.insert(AttrFlags::IS_DOC_NOTABLE_TRAIT),
70                "hidden" => attr_flags.insert(AttrFlags::IS_DOC_HIDDEN),
71                _ => {}
72            },
73            DocAtom::KeyValue { key, value: _ } => match &*key {
74                "alias" => attr_flags.insert(AttrFlags::HAS_DOC_ALIASES),
75                "keyword" => attr_flags.insert(AttrFlags::HAS_DOC_KEYWORD),
76                _ => {}
77            },
78            DocAtom::Alias(_) => attr_flags.insert(AttrFlags::HAS_DOC_ALIASES),
79        }
80    }
81}
82
83fn extract_ra_completions(attr_flags: &mut AttrFlags, tt: ast::TokenTree) {
84    let tt = TokenTreeChildren::new(&tt);
85    if let Ok(NodeOrToken::Token(option)) = Itertools::exactly_one(tt)
86        && option.kind().is_any_identifier()
87    {
88        match option.text() {
89            "ignore_flyimport" => attr_flags.insert(AttrFlags::COMPLETE_IGNORE_FLYIMPORT),
90            "ignore_methods" => attr_flags.insert(AttrFlags::COMPLETE_IGNORE_METHODS),
91            "ignore_flyimport_methods" => {
92                attr_flags.insert(AttrFlags::COMPLETE_IGNORE_FLYIMPORT_METHODS)
93            }
94            _ => {}
95        }
96    }
97}
98
99fn extract_ra_macro_style(attr_flags: &mut AttrFlags, tt: ast::TokenTree) {
100    let tt = TokenTreeChildren::new(&tt);
101    if let Ok(NodeOrToken::Token(option)) = Itertools::exactly_one(tt)
102        && option.kind().is_any_identifier()
103    {
104        match option.text() {
105            "braces" => attr_flags.insert(AttrFlags::MACRO_STYLE_BRACES),
106            "brackets" => attr_flags.insert(AttrFlags::MACRO_STYLE_BRACKETS),
107            "parentheses" => attr_flags.insert(AttrFlags::MACRO_STYLE_PARENTHESES),
108            _ => {}
109        }
110    }
111}
112
113fn extract_rustc_skip_during_method_dispatch(attr_flags: &mut AttrFlags, tt: ast::TokenTree) {
114    let iter = TokenTreeChildren::new(&tt);
115    for kind in iter {
116        if let NodeOrToken::Token(kind) = kind
117            && kind.kind().is_any_identifier()
118        {
119            match kind.text() {
120                "array" => attr_flags.insert(AttrFlags::RUSTC_SKIP_ARRAY_DURING_METHOD_DISPATCH),
121                "boxed_slice" => {
122                    attr_flags.insert(AttrFlags::RUSTC_SKIP_BOXED_SLICE_DURING_METHOD_DISPATCH)
123                }
124                _ => {}
125            }
126        }
127    }
128}
129
130#[inline]
131fn match_attr_flags(attr_flags: &mut AttrFlags, attr: ast::Meta) -> ControlFlow<Infallible> {
132    match attr {
133        ast::Meta::CfgMeta(_) => attr_flags.insert(AttrFlags::HAS_CFG),
134        ast::Meta::KeyValueMeta(attr) => {
135            let Some(key) = attr.path().as_one_segment() else { return ControlFlow::Continue(()) };
136            match &*key {
137                "deprecated" => attr_flags.insert(AttrFlags::IS_DEPRECATED),
138                "ignore" => attr_flags.insert(AttrFlags::IS_IGNORE),
139                "lang" => attr_flags.insert(AttrFlags::LANG_ITEM),
140                "must_use" => attr_flags.insert(AttrFlags::IS_MUST_USE),
141                "path" => attr_flags.insert(AttrFlags::HAS_PATH),
142                "unstable" => attr_flags.insert(AttrFlags::IS_UNSTABLE),
143                "rustc_reservation_impl" => attr_flags.insert(AttrFlags::RUSTC_RESERVATION_IMPL),
144                "export_name" => {
145                    if let Some(value) = attr.value_string()
146                        && *value == *"main"
147                    {
148                        attr_flags.insert(AttrFlags::IS_EXPORT_NAME_MAIN);
149                    }
150                }
151                _ => {}
152            }
153        }
154        ast::Meta::TokenTreeMeta(attr) => {
155            let (Some((first_segment, second_segment)), Some(tt)) =
156                (attr.path().as_up_to_two_segment(), attr.token_tree())
157            else {
158                return ControlFlow::Continue(());
159            };
160            match second_segment {
161                None => match &*first_segment {
162                    "deprecated" => attr_flags.insert(AttrFlags::IS_DEPRECATED),
163                    "doc" => extract_doc_tt_attr(attr_flags, tt),
164                    "repr" | "rustc_scalable_vector" => attr_flags.insert(AttrFlags::HAS_REPR),
165                    "target_feature" => attr_flags.insert(AttrFlags::HAS_TARGET_FEATURE),
166                    "proc_macro_derive" | "rustc_builtin_macro" => {
167                        attr_flags.insert(AttrFlags::IS_DERIVE_OR_BUILTIN_MACRO)
168                    }
169                    "unstable" => attr_flags.insert(AttrFlags::IS_UNSTABLE),
170                    "rustc_layout_scalar_valid_range_start"
171                    | "rustc_layout_scalar_valid_range_end" => {
172                        attr_flags.insert(AttrFlags::RUSTC_LAYOUT_SCALAR_VALID_RANGE)
173                    }
174                    "rustc_legacy_const_generics" => {
175                        attr_flags.insert(AttrFlags::HAS_LEGACY_CONST_GENERICS)
176                    }
177                    "rustc_skip_during_method_dispatch" => {
178                        extract_rustc_skip_during_method_dispatch(attr_flags, tt)
179                    }
180                    "rustc_deprecated_safe_2024" => {
181                        attr_flags.insert(AttrFlags::RUSTC_DEPRECATED_SAFE_2024)
182                    }
183                    "rustc_must_implement_one_of" => {
184                        attr_flags.insert(AttrFlags::HAS_RUSTC_MUST_IMPLEMENT_ONE_OF)
185                    }
186                    _ => {}
187                },
188                Some(second_segment) => match &*first_segment {
189                    "rust_analyzer" => match &*second_segment {
190                        "completions" => extract_ra_completions(attr_flags, tt),
191                        "macro_style" => extract_ra_macro_style(attr_flags, tt),
192                        _ => {}
193                    },
194                    _ => {}
195                },
196            }
197        }
198        ast::Meta::PathMeta(attr) => {
199            let is_test = attr.path().is_some_and(|path| {
200                let Some(segment1) = (|| path.segment()?.name_ref())() else { return false };
201                let segment2 = path.qualifier();
202                let segment3 = segment2.as_ref().and_then(|it| it.qualifier());
203                let segment4 = segment3.as_ref().and_then(|it| it.qualifier());
204                let segment3 = segment3.and_then(|it| it.segment()?.name_ref());
205                let segment4 = segment4.and_then(|it| it.segment()?.name_ref());
206                segment1.text() == "test"
207                    && segment3.is_none_or(|it| it.text() == "prelude")
208                    && segment4.is_none_or(|it| matches!(it.text(), "core" | "std"))
209            });
210            if is_test {
211                attr_flags.insert(AttrFlags::IS_TEST);
212            }
213
214            let Some((first_segment, second_segment)) = attr.path().as_up_to_two_segment() else {
215                return ControlFlow::Continue(());
216            };
217            match second_segment {
218                None => match &*first_segment {
219                    "rustc_has_incoherent_inherent_impls" => {
220                        attr_flags.insert(AttrFlags::RUSTC_HAS_INCOHERENT_INHERENT_IMPLS)
221                    }
222                    "rustc_allow_incoherent_impl" => {
223                        attr_flags.insert(AttrFlags::RUSTC_ALLOW_INCOHERENT_IMPL)
224                    }
225                    "rustc_scalable_vector" => attr_flags.insert(AttrFlags::HAS_REPR),
226                    "fundamental" => attr_flags.insert(AttrFlags::FUNDAMENTAL),
227                    "no_std" => attr_flags.insert(AttrFlags::IS_NO_STD),
228                    "may_dangle" => attr_flags.insert(AttrFlags::MAY_DANGLE),
229                    "rustc_paren_sugar" => attr_flags.insert(AttrFlags::RUSTC_PAREN_SUGAR),
230                    "rustc_coinductive" => attr_flags.insert(AttrFlags::RUSTC_COINDUCTIVE),
231                    "rustc_force_inline" => attr_flags.insert(AttrFlags::RUSTC_FORCE_INLINE),
232                    "unstable" => attr_flags.insert(AttrFlags::IS_UNSTABLE),
233                    "deprecated" => attr_flags.insert(AttrFlags::IS_DEPRECATED),
234                    "macro_export" => attr_flags.insert(AttrFlags::IS_MACRO_EXPORT),
235                    "must_use" => attr_flags.insert(AttrFlags::IS_MUST_USE),
236                    "no_mangle" => attr_flags.insert(AttrFlags::NO_MANGLE),
237                    "pointee" => attr_flags.insert(AttrFlags::IS_POINTEE),
238                    "non_exhaustive" => attr_flags.insert(AttrFlags::NON_EXHAUSTIVE),
239                    "ignore" => attr_flags.insert(AttrFlags::IS_IGNORE),
240                    "bench" => attr_flags.insert(AttrFlags::IS_BENCH),
241                    "rustc_const_panic_str" => attr_flags.insert(AttrFlags::RUSTC_CONST_PANIC_STR),
242                    "rustc_intrinsic" => attr_flags.insert(AttrFlags::RUSTC_INTRINSIC),
243                    "rustc_safe_intrinsic" => attr_flags.insert(AttrFlags::RUSTC_SAFE_INTRINSIC),
244                    "rustc_intrinsic_must_be_overridden" => {
245                        attr_flags.insert(AttrFlags::RUSTC_INTRINSIC_MUST_BE_OVERRIDDEN)
246                    }
247                    "rustc_allocator" => attr_flags.insert(AttrFlags::RUSTC_ALLOCATOR),
248                    "rustc_deallocator" => attr_flags.insert(AttrFlags::RUSTC_DEALLOCATOR),
249                    "rustc_reallocator" => attr_flags.insert(AttrFlags::RUSTC_REALLOCATOR),
250                    "rustc_allocator_zeroed" => {
251                        attr_flags.insert(AttrFlags::RUSTC_ALLOCATOR_ZEROED)
252                    }
253                    "rustc_reservation_impl" => {
254                        attr_flags.insert(AttrFlags::RUSTC_RESERVATION_IMPL)
255                    }
256                    "rustc_deprecated_safe_2024" => {
257                        attr_flags.insert(AttrFlags::RUSTC_DEPRECATED_SAFE_2024)
258                    }
259                    "rustc_skip_array_during_method_dispatch" => {
260                        attr_flags.insert(AttrFlags::RUSTC_SKIP_ARRAY_DURING_METHOD_DISPATCH)
261                    }
262                    "rustc_dyn_incompatible_trait" => {
263                        attr_flags.insert(AttrFlags::RUSTC_DYN_INCOMPATIBLE_TRAIT)
264                    }
265                    "rustc_always_gca" => attr_flags.insert(AttrFlags::RUSTC_ALWAYS_GCA),
266                    _ => {}
267                },
268                Some(second_segment) => match &*first_segment {
269                    "rust_analyzer" => match &*second_segment {
270                        "skip" => attr_flags.insert(AttrFlags::RUST_ANALYZER_SKIP),
271                        "prefer_underscore_import" => {
272                            attr_flags.insert(AttrFlags::PREFER_UNDERSCORE_IMPORT)
273                        }
274                        _ => {}
275                    },
276                    "diagnostic" => match &*second_segment {
277                        "do_not_recommend" => {
278                            attr_flags.insert(AttrFlags::DIAGNOSTIC_DO_NOT_RECOMMEND)
279                        }
280                        _ => {}
281                    },
282                    _ => {}
283                },
284            }
285        }
286        _ => {}
287    };
288    ControlFlow::Continue(())
289}
290
291bitflags::bitflags! {
292    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
293    pub struct AttrFlags: u64 {
294        const RUST_ANALYZER_SKIP = 1 << 0;
295
296        const LANG_ITEM = 1 << 1;
297
298        const HAS_DOC_ALIASES = 1 << 2;
299        const HAS_DOC_KEYWORD = 1 << 3;
300        const IS_DOC_NOTABLE_TRAIT = 1 << 4;
301        const IS_DOC_HIDDEN = 1 << 5;
302
303        const RUSTC_HAS_INCOHERENT_INHERENT_IMPLS = 1 << 6;
304        const RUSTC_ALLOW_INCOHERENT_IMPL = 1 << 7;
305        const FUNDAMENTAL = 1 << 8;
306        const RUSTC_SKIP_ARRAY_DURING_METHOD_DISPATCH = 1 << 9;
307        const RUSTC_SKIP_BOXED_SLICE_DURING_METHOD_DISPATCH = 1 << 10;
308        const HAS_REPR = 1 << 11;
309        const HAS_TARGET_FEATURE = 1 << 12;
310        const RUSTC_DEPRECATED_SAFE_2024 = 1 << 13;
311        const HAS_LEGACY_CONST_GENERICS = 1 << 14;
312        const NO_MANGLE = 1 << 15;
313        const NON_EXHAUSTIVE = 1 << 16;
314        const RUSTC_RESERVATION_IMPL = 1 << 17;
315        const RUSTC_CONST_PANIC_STR = 1 << 18;
316        const MAY_DANGLE = 1 << 19;
317
318        const RUSTC_INTRINSIC = 1 << 20;
319        const RUSTC_SAFE_INTRINSIC = 1 << 21;
320        const RUSTC_INTRINSIC_MUST_BE_OVERRIDDEN = 1 << 22;
321        const RUSTC_ALLOCATOR = 1 << 23;
322        const RUSTC_DEALLOCATOR = 1 << 24;
323        const RUSTC_REALLOCATOR = 1 << 25;
324        const RUSTC_ALLOCATOR_ZEROED = 1 << 26;
325
326        const IS_UNSTABLE = 1 << 27;
327        const IS_IGNORE = 1 << 28;
328        // FIXME: `IS_TEST` and `IS_BENCH` should be based on semantic information, not textual match.
329        const IS_BENCH = 1 << 29;
330        const IS_TEST = 1 << 30;
331        const IS_EXPORT_NAME_MAIN = 1 << 31;
332        const IS_MACRO_EXPORT = 1 << 32;
333        const IS_NO_STD = 1 << 33;
334        const IS_DERIVE_OR_BUILTIN_MACRO = 1 << 34;
335        const IS_DEPRECATED = 1 << 35;
336        const HAS_PATH = 1 << 36;
337        const HAS_CFG = 1 << 37;
338
339        const COMPLETE_IGNORE_FLYIMPORT = 1 << 38;
340        const COMPLETE_IGNORE_FLYIMPORT_METHODS = 1 << 39;
341        const COMPLETE_IGNORE_METHODS = 1 << 40;
342
343        const RUSTC_LAYOUT_SCALAR_VALID_RANGE = 1 << 41;
344        const RUSTC_PAREN_SUGAR = 1 << 42;
345        const RUSTC_COINDUCTIVE = 1 << 43;
346        const RUSTC_FORCE_INLINE = 1 << 44;
347        const IS_POINTEE = 1 << 45;
348
349        const MACRO_STYLE_BRACES = 1 << 46;
350        const MACRO_STYLE_BRACKETS = 1 << 47;
351        const MACRO_STYLE_PARENTHESES = 1 << 48;
352
353        const PREFER_UNDERSCORE_IMPORT = 1 << 49;
354
355        const IS_MUST_USE = 1 << 50;
356
357        const DIAGNOSTIC_DO_NOT_RECOMMEND = 1 << 51;
358
359        const HAS_RUSTC_MUST_IMPLEMENT_ONE_OF = 1 << 52;
360        const RUSTC_DYN_INCOMPATIBLE_TRAIT = 1 << 53;
361        const RUSTC_ALWAYS_GCA = 1 << 54;
362    }
363}
364
365pub fn parse_extra_crate_attrs(db: &dyn SourceDatabase, krate: Crate) -> Option<SourceFile> {
366    let crate_data = krate.data(db);
367    let crate_attrs = &crate_data.crate_attrs;
368    if crate_attrs.is_empty() {
369        return None;
370    }
371    // All attributes are already enclosed in `#![]`.
372    let combined = crate_attrs.concat();
373    let p = SourceFile::parse(&combined, crate_data.edition);
374
375    let errs = p.errors();
376    if !errs.is_empty() {
377        let base_msg = "Failed to parse extra crate-level attribute";
378        let crate_name =
379            krate.extra_data(db).display_name.as_ref().map_or("{unknown}", |name| name.as_str());
380        let mut errs = errs.iter().peekable();
381        let mut offset = TextSize::from(0);
382        for raw_attr in crate_attrs {
383            let attr_end = offset + TextSize::of(&**raw_attr);
384            if errs.peeking_take_while(|e| e.range().start() < attr_end).count() > 0 {
385                tracing::error!("{base_msg} {raw_attr} for crate {crate_name}");
386            }
387            offset = attr_end
388        }
389        return None;
390    }
391
392    Some(p.tree())
393}
394
395/// Whether the crate root declares `#![no_std]`, looking through `cfg_attr` gating.
396#[salsa::tracked(returns(copy))]
397pub(crate) fn crate_supports_no_std(db: &dyn SourceDatabase, krate: Crate) -> bool {
398    fn contains_no_std(meta: ast::Meta) -> bool {
399        match meta {
400            ast::Meta::PathMeta(meta) => meta.path().is1("no_std"),
401            ast::Meta::CfgAttrMeta(meta) => meta.metas().any(contains_no_std),
402            ast::Meta::UnsafeMeta(meta) => meta.meta().is_some_and(contains_no_std),
403            ast::Meta::CfgMeta(_) | ast::Meta::KeyValueMeta(_) | ast::Meta::TokenTreeMeta(_) => {
404                false
405            }
406        }
407    }
408
409    let root_file = krate.root_file_id(db).parse(db).tree();
410    parse_extra_crate_attrs(db, krate)
411        .into_iter()
412        .flat_map(|extra| extra.attrs())
413        .chain(root_file.attrs())
414        .filter_map(|attr| attr.meta())
415        .any(contains_no_std)
416}
417
418fn attrs_source(
419    db: &dyn SourceDatabase,
420    owner: AttrDefId,
421) -> (InFile<ast::AnyHasAttrs>, Option<InFile<ast::Module>>, Option<SourceFile>, Crate) {
422    let (owner, krate) = match owner {
423        AttrDefId::ModuleId(id) => {
424            let def_map = id.def_map(db);
425            let krate = def_map.krate();
426            let (definition, declaration, extra_crate_attrs) = match def_map[id].origin {
427                ModuleOrigin::CrateRoot { definition } => {
428                    let definition_source = definition.parse(db).tree();
429                    let definition = InFile::new(definition.into(), definition_source.into());
430                    let extra_crate_attrs = parse_extra_crate_attrs(db, krate);
431                    (definition, None, extra_crate_attrs)
432                }
433                ModuleOrigin::File { declaration, declaration_tree_id, definition, .. } => {
434                    let definition_source = definition.parse(db).tree();
435                    let definition = InFile::new(definition.into(), definition_source.into());
436                    let declaration = InFile::new(declaration_tree_id.file_id(), declaration);
437                    let declaration = declaration.with_value(declaration.to_node(db));
438                    (definition, Some(declaration), None)
439                }
440                ModuleOrigin::Inline { definition_tree_id, definition } => {
441                    let definition = InFile::new(definition_tree_id.file_id(), definition);
442                    let definition = definition.with_value(definition.to_node(db).into());
443                    (definition, None, None)
444                }
445                ModuleOrigin::BlockExpr { block, .. } => {
446                    let definition = block.to_node(db);
447                    (block.with_value(definition.into()), None, None)
448                }
449            };
450            return (definition, declaration, extra_crate_attrs, krate);
451        }
452        AttrDefId::AdtId(AdtId::StructId(it)) => attrs_from_ast_id_loc(db, it),
453        AttrDefId::AdtId(AdtId::UnionId(it)) => attrs_from_ast_id_loc(db, it),
454        AttrDefId::AdtId(AdtId::EnumId(it)) => attrs_from_ast_id_loc(db, it),
455        AttrDefId::FunctionId(it) => attrs_from_ast_id_loc(db, it),
456        AttrDefId::EnumVariantId(it) => attrs_from_ast_id_loc(db, it),
457        AttrDefId::StaticId(it) => attrs_from_ast_id_loc(db, it),
458        AttrDefId::ConstId(it) => attrs_from_ast_id_loc(db, it),
459        AttrDefId::TraitId(it) => attrs_from_ast_id_loc(db, it),
460        AttrDefId::TypeAliasId(it) => attrs_from_ast_id_loc(db, it),
461        AttrDefId::MacroId(MacroId::MacroRulesId(it)) => attrs_from_ast_id_loc(db, it),
462        AttrDefId::MacroId(MacroId::Macro2Id(it)) => attrs_from_ast_id_loc(db, it),
463        AttrDefId::MacroId(MacroId::ProcMacroId(it)) => attrs_from_ast_id_loc(db, it),
464        AttrDefId::ImplId(it) => attrs_from_ast_id_loc(db, it),
465        AttrDefId::ExternBlockId(it) => attrs_from_ast_id_loc(db, it),
466        AttrDefId::ExternCrateId(it) => attrs_from_ast_id_loc(db, it),
467        AttrDefId::UseId(it) => attrs_from_ast_id_loc(db, it),
468    };
469    (owner, None, None, krate)
470}
471
472fn resolver_for_attr_def_id(db: &dyn SourceDatabase, owner: AttrDefId) -> Resolver<'_> {
473    match owner {
474        AttrDefId::ModuleId(id) => id.resolver(db),
475        AttrDefId::AdtId(AdtId::StructId(id)) => id.resolver(db),
476        AttrDefId::AdtId(AdtId::UnionId(id)) => id.resolver(db),
477        AttrDefId::AdtId(AdtId::EnumId(id)) => id.resolver(db),
478        AttrDefId::FunctionId(id) => id.resolver(db),
479        AttrDefId::EnumVariantId(id) => id.resolver(db),
480        AttrDefId::StaticId(id) => id.resolver(db),
481        AttrDefId::ConstId(id) => id.resolver(db),
482        AttrDefId::TraitId(id) => id.resolver(db),
483        AttrDefId::TypeAliasId(id) => id.resolver(db),
484        AttrDefId::MacroId(MacroId::Macro2Id(id)) => id.resolver(db),
485        AttrDefId::MacroId(MacroId::MacroRulesId(id)) => id.resolver(db),
486        AttrDefId::MacroId(MacroId::ProcMacroId(id)) => id.resolver(db),
487        AttrDefId::ImplId(id) => id.resolver(db),
488        AttrDefId::ExternBlockId(id) => id.resolver(db),
489        AttrDefId::ExternCrateId(id) => id.resolver(db),
490        AttrDefId::UseId(id) => id.resolver(db),
491    }
492}
493
494fn collect_attrs<BreakValue>(
495    db: &dyn SourceDatabase,
496    owner: AttrDefId,
497    mut callback: impl FnMut(ast::Meta) -> ControlFlow<BreakValue>,
498) -> Option<BreakValue> {
499    let (source, outer_mod_decl, extra_crate_attrs, krate) = attrs_source(db, owner);
500    let extra_attrs = extra_crate_attrs
501        .into_iter()
502        .flat_map(|src| src.attrs())
503        .chain(outer_mod_decl.into_iter().flat_map(|it| it.value.attrs()));
504
505    let mut cfg_options = None;
506    expand_cfg_attr(
507        extra_attrs.chain(ast::attrs_including_inner(&source.value)),
508        || cfg_options.get_or_insert_with(|| krate.cfg_options(db)),
509        move |meta, _| callback(meta),
510    )
511}
512
513fn collect_field_attrs<T>(
514    db: &dyn SourceDatabase,
515    variant: VariantId,
516    mut field_attrs: impl FnMut(&CfgOptions, InFile<ast::AnyHasAttrs>) -> T,
517) -> ArenaMap<LocalFieldId, T> {
518    let (variant_syntax, krate) = match variant {
519        VariantId::EnumVariantId(it) => attrs_from_ast_id_loc(db, it),
520        VariantId::StructId(it) => attrs_from_ast_id_loc(db, it),
521        VariantId::UnionId(it) => attrs_from_ast_id_loc(db, it),
522    };
523    let cfg_options = krate.cfg_options(db);
524    let variant_syntax = variant_syntax
525        .with_value(ast::VariantDef::cast(variant_syntax.value.syntax().clone()).unwrap());
526    let fields = match &variant_syntax.value {
527        ast::VariantDef::Struct(it) => it.field_list(),
528        ast::VariantDef::Union(it) => it.record_field_list().map(ast::FieldList::RecordFieldList),
529        ast::VariantDef::Variant(it) => it.field_list(),
530    };
531    let Some(fields) = fields else {
532        return ArenaMap::new();
533    };
534
535    let mut result = ArenaMap::new();
536    let mut idx = 0;
537    match fields {
538        ast::FieldList::RecordFieldList(fields) => {
539            for field in fields.fields() {
540                if AttrFlags::is_cfg_enabled_for(&field, cfg_options).is_ok() {
541                    result.insert(
542                        la_arena::Idx::from_raw(la_arena::RawIdx::from_u32(idx)),
543                        field_attrs(cfg_options, variant_syntax.with_value(field.into())),
544                    );
545                    idx += 1;
546                }
547            }
548        }
549        ast::FieldList::TupleFieldList(fields) => {
550            for field in fields.fields() {
551                if AttrFlags::is_cfg_enabled_for(&field, cfg_options).is_ok() {
552                    result.insert(
553                        la_arena::Idx::from_raw(la_arena::RawIdx::from_u32(idx)),
554                        field_attrs(cfg_options, variant_syntax.with_value(field.into())),
555                    );
556                    idx += 1;
557                }
558            }
559        }
560    }
561    result.shrink_to_fit();
562    result
563}
564
565#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
566pub struct RustcLayoutScalarValidRange {
567    pub start: Option<u128>,
568    pub end: Option<u128>,
569}
570
571#[derive(Debug, PartialEq, Eq, Hash)]
572pub struct DeriveInfo {
573    pub trait_name: Symbol,
574    pub helpers: Box<[Symbol]>,
575}
576
577fn extract_doc_aliases(result: &mut Vec<Symbol>, attr: ast::Meta) -> ControlFlow<Infallible> {
578    if let ast::Meta::TokenTreeMeta(attr) = attr
579        && attr.path().is1("doc")
580        && let Some(tt) = attr.token_tree()
581    {
582        for atom in DocAtom::parse(tt) {
583            match atom {
584                DocAtom::Alias(aliases) => {
585                    result.extend(aliases.into_iter().map(|alias| Symbol::intern(&alias)))
586                }
587                DocAtom::KeyValue { key, value } if key == "alias" => {
588                    result.push(Symbol::intern(&value))
589                }
590                _ => {}
591            }
592        }
593    }
594    ControlFlow::Continue(())
595}
596
597fn extract_cfgs(result: &mut Vec<CfgExpr>, attr: ast::Meta) -> ControlFlow<Infallible> {
598    if let ast::Meta::CfgMeta(attr) = attr
599        && let Some(cfg_predicate) = attr.cfg_predicate()
600    {
601        result.push(CfgExpr::parse_from_ast(cfg_predicate));
602    }
603    ControlFlow::Continue(())
604}
605
606#[salsa::tracked]
607impl AttrFlags {
608    #[salsa::tracked(returns(copy))]
609    pub fn query(db: &dyn SourceDatabase, owner: AttrDefId) -> AttrFlags {
610        let mut attr_flags = AttrFlags::empty();
611        collect_attrs(db, owner, |attr| match_attr_flags(&mut attr_flags, attr));
612        attr_flags
613    }
614
615    #[inline]
616    pub fn query_field(db: &dyn SourceDatabase, field: FieldId) -> AttrFlags {
617        return field_attr_flags(db, field.parent)
618            .get(field.local_id)
619            .copied()
620            .unwrap_or_else(AttrFlags::empty);
621
622        #[salsa::tracked(returns(ref))]
623        fn field_attr_flags(
624            db: &dyn SourceDatabase,
625            variant: VariantId,
626        ) -> ArenaMap<LocalFieldId, AttrFlags> {
627            collect_field_attrs(db, variant, |cfg_options, field| {
628                let mut attr_flags = AttrFlags::empty();
629                expand_cfg_attr(
630                    field.value.attrs(),
631                    || cfg_options,
632                    |attr, _| match_attr_flags(&mut attr_flags, attr),
633                );
634                attr_flags
635            })
636        }
637    }
638
639    #[inline]
640    pub fn query_generic_params(
641        db: &dyn SourceDatabase,
642        def: GenericDefId,
643    ) -> &(ArenaMap<LocalLifetimeParamId, AttrFlags>, ArenaMap<LocalTypeOrConstParamId, AttrFlags>)
644    {
645        let generic_params = GenericParams::of(db, def);
646        let params_count_excluding_self =
647            generic_params.len() - usize::from(generic_params.trait_self_param().is_some());
648        if params_count_excluding_self == 0 {
649            return const { &(ArenaMap::new(), ArenaMap::new()) };
650        }
651        return generic_params_attr_flags(db, def);
652
653        #[salsa::tracked(returns(ref))]
654        fn generic_params_attr_flags(
655            db: &dyn SourceDatabase,
656            def: GenericDefId,
657        ) -> (ArenaMap<LocalLifetimeParamId, AttrFlags>, ArenaMap<LocalTypeOrConstParamId, AttrFlags>)
658        {
659            let mut lifetimes = ArenaMap::new();
660            let mut type_and_consts = ArenaMap::new();
661
662            let mut cfg_options = None;
663            let mut cfg_options =
664                || *cfg_options.get_or_insert_with(|| def.krate(db).cfg_options(db));
665
666            let lifetimes_source = HasChildSource::<LocalLifetimeParamId>::child_source(&def, db);
667            for (lifetime_id, lifetime) in lifetimes_source.value.iter() {
668                let mut attr_flags = AttrFlags::empty();
669                expand_cfg_attr(lifetime.attrs(), &mut cfg_options, |attr, _| {
670                    match_attr_flags(&mut attr_flags, attr)
671                });
672                if !attr_flags.is_empty() {
673                    lifetimes.insert(lifetime_id, attr_flags);
674                }
675            }
676
677            let type_and_consts_source =
678                HasChildSource::<LocalTypeOrConstParamId>::child_source(&def, db);
679            for (type_or_const_id, type_or_const) in type_and_consts_source.value.iter() {
680                let mut attr_flags = AttrFlags::empty();
681                expand_cfg_attr(type_or_const.attrs(), &mut cfg_options, |attr, _| {
682                    match_attr_flags(&mut attr_flags, attr)
683                });
684                if !attr_flags.is_empty() {
685                    type_and_consts.insert(type_or_const_id, attr_flags);
686                }
687            }
688
689            lifetimes.shrink_to_fit();
690            type_and_consts.shrink_to_fit();
691            (lifetimes, type_and_consts)
692        }
693    }
694
695    #[inline]
696    pub fn query_lifetime_param(db: &dyn SourceDatabase, owner: LifetimeParamId) -> AttrFlags {
697        AttrFlags::query_generic_params(db, owner.parent)
698            .0
699            .get(owner.local_id)
700            .copied()
701            .unwrap_or_else(AttrFlags::empty)
702    }
703    #[inline]
704    pub fn query_type_or_const_param(
705        db: &dyn SourceDatabase,
706        owner: TypeOrConstParamId,
707    ) -> AttrFlags {
708        AttrFlags::query_generic_params(db, owner.parent)
709            .1
710            .get(owner.local_id)
711            .copied()
712            .unwrap_or_else(AttrFlags::empty)
713    }
714
715    pub(crate) fn is_cfg_enabled_for(
716        owner: &dyn HasAttrs,
717        cfg_options: &CfgOptions,
718    ) -> Result<(), CfgExpr> {
719        let attrs = ast::attrs_including_inner(owner);
720        let result = expand_cfg_attr(
721            attrs,
722            || cfg_options,
723            |attr, _| {
724                if let ast::Meta::CfgMeta(attr) = attr
725                    && let Some(cfg_predicate) = attr.cfg_predicate()
726                    && let cfg = CfgExpr::parse_from_ast(cfg_predicate)
727                    && cfg_options.check(&cfg) == Some(false)
728                {
729                    ControlFlow::Break(cfg)
730                } else {
731                    ControlFlow::Continue(())
732                }
733            },
734        );
735        match result {
736            Some(cfg) => Err(cfg),
737            None => Ok(()),
738        }
739    }
740
741    #[inline]
742    pub fn lang_item(db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Symbol> {
743        AttrFlags::query(db, owner).lang_item_with_attrs(db, owner)
744    }
745
746    #[inline]
747    pub fn lang_item_with_attrs(self, db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Symbol> {
748        if !self.contains(AttrFlags::LANG_ITEM) {
749            // Don't create the query in case this is not a lang item, this wastes memory.
750            return None;
751        }
752
753        return lang_item(db, owner);
754
755        #[salsa::tracked(returns(clone))]
756        fn lang_item(db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Symbol> {
757            collect_attrs(db, owner, |attr| {
758                if let ast::Meta::KeyValueMeta(attr) = attr
759                    && attr.path().is1("lang")
760                    && let Some(value) = attr.value_string()
761                {
762                    ControlFlow::Break(Symbol::intern(&value))
763                } else {
764                    ControlFlow::Continue(())
765                }
766            })
767        }
768    }
769
770    #[inline]
771    pub fn repr(db: &dyn SourceDatabase, owner: AdtId) -> Option<ReprOptions> {
772        if !AttrFlags::query(db, owner.into()).contains(AttrFlags::HAS_REPR) {
773            // Don't create the query in case this has no repr, this wastes memory.
774            return None;
775        }
776
777        Self::repr_assume_has(db, owner)
778    }
779
780    /// Only call this when you've verified the type indeed has a `#[repr]` attribute!
781    ///
782    /// Prefer [`AttrFlags::repr()`] in non-perf-sensitive places as it also has a check that
783    /// that the ADT has repr.
784    #[salsa::tracked(returns(copy))]
785    pub fn repr_assume_has(db: &dyn SourceDatabase, owner: AdtId) -> Option<ReprOptions> {
786        let mut result = None;
787        collect_attrs::<Infallible>(db, owner.into(), |attr| {
788            let mut current = None;
789            if let ast::Meta::TokenTreeMeta(attr) = &attr
790                && let Some(path) = attr.path()
791                && let Some(tt) = attr.token_tree()
792            {
793                if path.is1("repr")
794                    && let Some(repr) = parse_repr_tt(&tt)
795                {
796                    current = Some(repr);
797                } else if path.is1("rustc_scalable_vector")
798                    && let mut tt = TokenTreeChildren::new(&tt)
799                    && let Some(NodeOrToken::Token(scalable)) = tt.next()
800                    && let Some(scalable) = ast::IntNumber::cast(scalable)
801                    && let Ok(scalable) = scalable.value()
802                    && let Ok(scalable) = scalable.try_into()
803                {
804                    current = Some(ReprOptions {
805                        scalable: Some(rustc_abi::ScalableElt::ElementCount(scalable)),
806                        ..ReprOptions::default()
807                    });
808                }
809            } else if let ast::Meta::PathMeta(attr) = &attr
810                && attr.path().is1("rustc_scalable_vector")
811            {
812                current = Some(ReprOptions {
813                    scalable: Some(rustc_abi::ScalableElt::Container),
814                    ..ReprOptions::default()
815                });
816            }
817
818            if let Some(current) = current {
819                match &mut result {
820                    Some(existing) => merge_repr(existing, current),
821                    None => result = Some(current),
822                }
823            }
824            ControlFlow::Continue(())
825        });
826        result
827    }
828
829    /// Call this only if there are legacy const generics, to save memory.
830    #[salsa::tracked(returns(ref))]
831    pub(crate) fn legacy_const_generic_indices(
832        db: &dyn SourceDatabase,
833        owner: FunctionId,
834    ) -> Option<Box<[u32]>> {
835        let result = collect_attrs(db, owner.into(), |attr| {
836            if let ast::Meta::TokenTreeMeta(attr) = attr
837                && attr.path().is1("rustc_legacy_const_generics")
838                && let Some(tt) = attr.token_tree()
839            {
840                let result = parse_rustc_legacy_const_generics(tt);
841                ControlFlow::Break(result)
842            } else {
843                ControlFlow::Continue(())
844            }
845        });
846        result.filter(|it| !it.is_empty())
847    }
848
849    // There aren't typically many crates, so it's okay to always make this a query without a flag.
850    #[salsa::tracked(returns(ref))]
851    pub fn doc_html_root_url(db: &dyn SourceDatabase, krate: Crate) -> Option<SmolStr> {
852        let root_file_id = krate.root_file_id(db);
853        let syntax = root_file_id.parse(db).tree();
854        let extra_crate_attrs =
855            parse_extra_crate_attrs(db, krate).into_iter().flat_map(|src| src.attrs());
856
857        let mut cfg_options = None;
858        expand_cfg_attr(
859            extra_crate_attrs.chain(syntax.attrs()),
860            || cfg_options.get_or_insert(krate.cfg_options(db)),
861            |attr, _| {
862                if let ast::Meta::TokenTreeMeta(attr) = attr
863                    && attr.path().is1("doc")
864                    && let Some(tt) = attr.token_tree()
865                    && let Some(result) = DocAtom::parse(tt).into_iter().find_map(|atom| {
866                        if let DocAtom::KeyValue { key, value } = atom
867                            && key == "html_root_url"
868                        {
869                            Some(value)
870                        } else {
871                            None
872                        }
873                    })
874                {
875                    ControlFlow::Break(result)
876                } else {
877                    ControlFlow::Continue(())
878                }
879            },
880        )
881    }
882
883    #[inline]
884    pub fn target_features(db: &dyn SourceDatabase, owner: FunctionId) -> &FxHashSet<Symbol> {
885        if !AttrFlags::query(db, owner.into()).contains(AttrFlags::HAS_TARGET_FEATURE) {
886            return const { &FxHashSet::with_hasher(rustc_hash::FxBuildHasher) };
887        }
888
889        return target_features(db, owner);
890
891        #[salsa::tracked(returns(ref))]
892        fn target_features(db: &dyn SourceDatabase, owner: FunctionId) -> FxHashSet<Symbol> {
893            let mut result = FxHashSet::default();
894            collect_attrs::<Infallible>(db, owner.into(), |attr| {
895                if let ast::Meta::TokenTreeMeta(attr) = attr
896                    && attr.path().is1("target_feature")
897                    && let Some(tt) = attr.token_tree()
898                {
899                    let mut tt = TokenTreeChildren::new(&tt);
900                    while let Some(NodeOrToken::Token(enable_ident)) = tt.next()
901                        && enable_ident.text() == "enable"
902                        && let Some(NodeOrToken::Token(eq_token)) = tt.next()
903                        && eq_token.kind() == T![=]
904                        && let Some(NodeOrToken::Token(features)) = tt.next()
905                        && let Some(features) = ast::String::cast(features)
906                        && let Ok(features) = features.value()
907                    {
908                        result.extend(features.split(',').map(Symbol::intern));
909                        if tt
910                            .next()
911                            .and_then(NodeOrToken::into_token)
912                            .is_none_or(|it| it.kind() != T![,])
913                        {
914                            break;
915                        }
916                    }
917                }
918                ControlFlow::Continue(())
919            });
920            result.shrink_to_fit();
921            result
922        }
923    }
924
925    #[inline]
926    pub fn rustc_layout_scalar_valid_range(
927        db: &dyn SourceDatabase,
928        owner: AdtId,
929    ) -> RustcLayoutScalarValidRange {
930        if !AttrFlags::query(db, owner.into()).contains(AttrFlags::RUSTC_LAYOUT_SCALAR_VALID_RANGE)
931        {
932            return RustcLayoutScalarValidRange::default();
933        }
934
935        return rustc_layout_scalar_valid_range(db, owner);
936
937        #[salsa::tracked(returns(copy))]
938        fn rustc_layout_scalar_valid_range(
939            db: &dyn SourceDatabase,
940            owner: AdtId,
941        ) -> RustcLayoutScalarValidRange {
942            let mut result = RustcLayoutScalarValidRange::default();
943            collect_attrs::<Infallible>(db, owner.into(), |attr| {
944                if let ast::Meta::TokenTreeMeta(attr) = attr
945                    && let path = attr.path()
946                    && (path.is1("rustc_layout_scalar_valid_range_start")
947                        || path.is1("rustc_layout_scalar_valid_range_end"))
948                    && let Some(tt) = attr.token_tree()
949                    && let tt = TokenTreeChildren::new(&tt)
950                    && let Ok(NodeOrToken::Token(value)) = Itertools::exactly_one(tt)
951                    && let Some(value) = ast::IntNumber::cast(value)
952                    && let Ok(value) = value.value()
953                {
954                    if path.is1("rustc_layout_scalar_valid_range_start") {
955                        result.start = Some(value)
956                    } else {
957                        result.end = Some(value);
958                    }
959                }
960                ControlFlow::Continue(())
961            });
962            result
963        }
964    }
965
966    #[inline]
967    pub fn doc_aliases(
968        self,
969        db: &dyn SourceDatabase,
970        owner: Either<AttrDefId, FieldId>,
971    ) -> &[Symbol] {
972        if !self.contains(AttrFlags::HAS_DOC_ALIASES) {
973            return &[];
974        }
975        return match owner {
976            Either::Left(it) => doc_aliases(db, it),
977            Either::Right(field) => fields_doc_aliases(db, field.parent)
978                .get(field.local_id)
979                .map(|it| &**it)
980                .unwrap_or_default(),
981        };
982
983        #[salsa::tracked(returns(ref))]
984        fn doc_aliases(db: &dyn SourceDatabase, owner: AttrDefId) -> Box<[Symbol]> {
985            let mut result = Vec::new();
986            collect_attrs::<Infallible>(db, owner, |attr| extract_doc_aliases(&mut result, attr));
987            result.into_boxed_slice()
988        }
989
990        #[salsa::tracked(returns(ref))]
991        fn fields_doc_aliases(
992            db: &dyn SourceDatabase,
993            variant: VariantId,
994        ) -> ArenaMap<LocalFieldId, Box<[Symbol]>> {
995            collect_field_attrs(db, variant, |cfg_options, field| {
996                let mut result = Vec::new();
997                expand_cfg_attr(
998                    field.value.attrs(),
999                    || cfg_options,
1000                    |attr, _| extract_doc_aliases(&mut result, attr),
1001                );
1002                result.into_boxed_slice()
1003            })
1004        }
1005    }
1006
1007    #[inline]
1008    pub fn cfgs(
1009        self,
1010        db: &dyn SourceDatabase,
1011        owner: Either<AttrDefId, FieldId>,
1012    ) -> Option<&CfgExpr> {
1013        if !self.contains(AttrFlags::HAS_CFG) {
1014            return None;
1015        }
1016        return match owner {
1017            Either::Left(it) => cfgs(db, it).as_ref(),
1018            Either::Right(field) => {
1019                fields_cfgs(db, field.parent).get(field.local_id).and_then(|it| it.as_ref())
1020            }
1021        };
1022
1023        // We LRU this query because it is only used by IDE.
1024        #[salsa::tracked(returns(ref), lru = 250)]
1025        fn cfgs(db: &dyn SourceDatabase, owner: AttrDefId) -> Option<CfgExpr> {
1026            let mut result = Vec::new();
1027            collect_attrs::<Infallible>(db, owner, |attr| extract_cfgs(&mut result, attr));
1028            match result.len() {
1029                0 => None,
1030                1 => result.into_iter().next(),
1031                _ => Some(CfgExpr::All(result.into_boxed_slice())),
1032            }
1033        }
1034
1035        // We LRU this query because it is only used by IDE.
1036        #[salsa::tracked(returns(ref), lru = 50)]
1037        fn fields_cfgs(
1038            db: &dyn SourceDatabase,
1039            variant: VariantId,
1040        ) -> ArenaMap<LocalFieldId, Option<CfgExpr>> {
1041            collect_field_attrs(db, variant, |cfg_options, field| {
1042                let mut result = Vec::new();
1043                expand_cfg_attr(
1044                    field.value.attrs(),
1045                    || cfg_options,
1046                    |attr, _| extract_cfgs(&mut result, attr),
1047                );
1048                match result.len() {
1049                    0 => None,
1050                    1 => result.into_iter().next(),
1051                    _ => Some(CfgExpr::All(result.into_boxed_slice())),
1052                }
1053            })
1054        }
1055    }
1056
1057    #[inline]
1058    pub fn doc_keyword(db: &dyn SourceDatabase, owner: ModuleId) -> Option<Symbol> {
1059        if !AttrFlags::query(db, AttrDefId::ModuleId(owner)).contains(AttrFlags::HAS_DOC_KEYWORD) {
1060            return None;
1061        }
1062        return doc_keyword(db, owner);
1063
1064        #[salsa::tracked(returns(clone))]
1065        fn doc_keyword(db: &dyn SourceDatabase, owner: ModuleId) -> Option<Symbol> {
1066            collect_attrs(db, AttrDefId::ModuleId(owner), |attr| {
1067                if let ast::Meta::TokenTreeMeta(attr) = attr
1068                    && attr.path().is1("doc")
1069                    && let Some(tt) = attr.token_tree()
1070                {
1071                    for atom in DocAtom::parse(tt) {
1072                        if let DocAtom::KeyValue { key, value } = atom
1073                            && key == "keyword"
1074                        {
1075                            return ControlFlow::Break(Symbol::intern(&value));
1076                        }
1077                    }
1078                }
1079                ControlFlow::Continue(())
1080            })
1081        }
1082    }
1083
1084    // We LRU this query because it is only used by IDE.
1085    #[salsa::tracked(returns(as_deref), lru = 250)]
1086    pub fn docs(db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Box<Docs>> {
1087        let (source, outer_mod_decl, _extra_crate_attrs, krate) = attrs_source(db, owner);
1088        let inner_attrs_node = source.value.inner_attributes_node();
1089        // Note: we don't have to pass down `_extra_crate_attrs` here, since `extract_docs`
1090        // does not handle crate-level attributes related to docs.
1091        // See: https://doc.rust-lang.org/rustdoc/write-documentation/the-doc-attribute.html#at-the-crate-level
1092        self::docs::extract_docs(
1093            db,
1094            krate,
1095            &|| resolver_for_attr_def_id(db, owner),
1096            &|| krate.cfg_options(db),
1097            source,
1098            outer_mod_decl,
1099            inner_attrs_node,
1100        )
1101    }
1102
1103    #[inline]
1104    pub fn field_docs(db: &dyn SourceDatabase, field: FieldId) -> Option<&Docs> {
1105        Self::fields_docs(db, field.parent).get(field.local_id).and_then(|it| it.as_deref())
1106    }
1107
1108    // We LRU this query because it is only used by IDE.
1109    #[salsa::tracked(returns(ref), lru = 50)]
1110    pub fn fields_docs(
1111        db: &dyn SourceDatabase,
1112        variant: VariantId,
1113    ) -> ArenaMap<LocalFieldId, Option<Box<Docs>>> {
1114        let krate = variant.module(db).krate(db);
1115        collect_field_attrs(db, variant, |cfg_options, field| {
1116            self::docs::extract_docs(
1117                db,
1118                krate,
1119                &|| variant.resolver(db),
1120                &|| cfg_options,
1121                field,
1122                None,
1123                None,
1124            )
1125        })
1126    }
1127
1128    #[inline]
1129    pub fn derive_info(db: &dyn SourceDatabase, owner: MacroId) -> Option<&DeriveInfo> {
1130        if !AttrFlags::query(db, owner.into()).contains(AttrFlags::IS_DERIVE_OR_BUILTIN_MACRO) {
1131            return None;
1132        }
1133
1134        return derive_info(db, owner).as_ref();
1135
1136        #[salsa::tracked(returns(ref))]
1137        fn derive_info(db: &dyn SourceDatabase, owner: MacroId) -> Option<DeriveInfo> {
1138            collect_attrs(db, owner.into(), |attr| {
1139                if let ast::Meta::TokenTreeMeta(attr) = attr
1140                    && (attr.path().is1("proc_macro_derive")
1141                        || attr.path().is1("rustc_builtin_macro"))
1142                    && let Some(tt) = attr.token_tree()
1143                    && let mut tt = TokenTreeChildren::new(&tt)
1144                    && let Some(NodeOrToken::Token(trait_name)) = tt.next()
1145                    && trait_name.kind().is_any_identifier()
1146                {
1147                    let trait_name = Symbol::intern(trait_name.text());
1148
1149                    let helpers = if let Some(NodeOrToken::Token(comma)) = tt.next()
1150                        && comma.kind() == T![,]
1151                        && let Some(NodeOrToken::Token(attributes)) = tt.next()
1152                        && attributes.text() == "attributes"
1153                        && let Some(NodeOrToken::Node(attributes)) = tt.next()
1154                    {
1155                        attributes
1156                            .syntax()
1157                            .children_with_tokens()
1158                            .filter_map(NodeOrToken::into_token)
1159                            .filter(|it| it.kind().is_any_identifier())
1160                            .map(|it| Symbol::intern(it.text()))
1161                            .collect::<Box<[_]>>()
1162                    } else {
1163                        Box::new([])
1164                    };
1165
1166                    ControlFlow::Break(DeriveInfo { trait_name, helpers })
1167                } else {
1168                    ControlFlow::Continue(())
1169                }
1170            })
1171        }
1172    }
1173
1174    pub fn unstable_feature(self, db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Symbol> {
1175        if !self.contains(AttrFlags::IS_UNSTABLE) {
1176            return None;
1177        }
1178
1179        return unstable_feature(db, owner);
1180
1181        #[salsa::tracked(returns(clone))]
1182        fn unstable_feature(db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Symbol> {
1183            collect_attrs(db, owner, |attr| {
1184                if let ast::Meta::TokenTreeMeta(attr) = attr
1185                    && let path = attr.path()
1186                    && path.is1("unstable")
1187                    && let Some(tt) = attr.token_tree()
1188                {
1189                    let mut tt = TokenTreeChildren::new(&tt);
1190                    // Technically the `feature = "..."` always comes first, but it's not a requirement.
1191                    while let Some(token) = tt.next() {
1192                        if let NodeOrToken::Token(token) = token
1193                            && token.text() == "feature"
1194                            && let Some(NodeOrToken::Token(eq)) = tt.next()
1195                            && eq.kind() == T![=]
1196                            && let Some(NodeOrToken::Token(feature)) = tt.next()
1197                            && let Some(feature) = ast::String::cast(feature)
1198                            && let Ok(feature) = feature.value()
1199                        {
1200                            return ControlFlow::Break(Symbol::intern(&feature));
1201                        }
1202                    }
1203                }
1204                ControlFlow::Continue(())
1205            })
1206        }
1207    }
1208
1209    /// Returns `None` if there is no `#[must_use]`, `Some(None)` if there is a `#[must_use]` without a message,
1210    /// and `Some(Some(message))` if there is a `#[must_use]` with a message.
1211    pub fn must_use_message(db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Option<&str>> {
1212        if !AttrFlags::query(db, owner).contains(AttrFlags::IS_MUST_USE) {
1213            return None;
1214        }
1215        return Some(must_use_message(db, owner));
1216
1217        #[salsa::tracked(returns(as_deref))]
1218        fn must_use_message(db: &dyn SourceDatabase, owner: AttrDefId) -> Option<Box<str>> {
1219            collect_attrs(db, owner, |attr| {
1220                if let ast::Meta::KeyValueMeta(attr) = attr
1221                    && attr.path().is1("must_use")
1222                    && let Some(message) = attr.value_string()
1223                {
1224                    return ControlFlow::Break(Box::from(&*message));
1225                }
1226                ControlFlow::Continue(())
1227            })
1228        }
1229    }
1230
1231    pub fn must_implement_one_of(db: &dyn SourceDatabase, owner: TraitId) -> Option<&[Name]> {
1232        if !AttrFlags::query(db, owner.into()).contains(AttrFlags::HAS_RUSTC_MUST_IMPLEMENT_ONE_OF)
1233        {
1234            return None;
1235        }
1236        return must_implement_one_of(db, owner);
1237
1238        #[salsa::tracked(returns(as_deref))]
1239        pub fn must_implement_one_of(
1240            db: &dyn SourceDatabase,
1241            owner: TraitId,
1242        ) -> Option<Box<[Name]>> {
1243            collect_attrs(db, owner.into(), |attr| {
1244                if let ast::Meta::TokenTreeMeta(attr) = attr
1245                    && attr.path().is1("rustc_must_implement_one_of")
1246                    && let Some(tt) = attr.token_tree()
1247                    && let names = tt
1248                        .token_trees_and_tokens()
1249                        .filter_map(|it| ast::Ident::cast(it.into_token()?))
1250                        .map(|name| Name::new_symbol_root(Symbol::intern(name.text())))
1251                        .collect::<Box<[_]>>()
1252                    && !names.is_empty()
1253                {
1254                    return ControlFlow::Break(names);
1255                }
1256                ControlFlow::Continue(())
1257            })
1258        }
1259    }
1260}
1261
1262fn merge_repr(this: &mut ReprOptions, other: ReprOptions) {
1263    let ReprOptions { int, align, pack, flags, scalable, field_shuffle_seed: _ } = this;
1264    flags.insert(other.flags);
1265    *align = (*align).max(other.align);
1266    *pack = match (*pack, other.pack) {
1267        (Some(pack), None) | (None, Some(pack)) => Some(pack),
1268        _ => (*pack).min(other.pack),
1269    };
1270    if other.int.is_some() {
1271        *int = other.int;
1272    }
1273    if other.scalable.is_some() {
1274        *scalable = other.scalable;
1275    }
1276}
1277
1278fn parse_repr_tt(tt: &ast::TokenTree) -> Option<ReprOptions> {
1279    use crate::builtin_type::{BuiltinInt, BuiltinUint};
1280    use rustc_abi::{Align, Integer, IntegerType, ReprFlags, ReprOptions};
1281
1282    let mut tts = TokenTreeChildren::new(tt).peekable();
1283
1284    let mut acc = ReprOptions::default();
1285    while let Some(tt) = tts.next() {
1286        let NodeOrToken::Token(ident) = tt else {
1287            continue;
1288        };
1289        if !ident.kind().is_any_identifier() {
1290            continue;
1291        }
1292        let repr = match ident.text() {
1293            "packed" => {
1294                let pack = if let Some(NodeOrToken::Node(tt)) = tts.peek() {
1295                    let tt = tt.clone();
1296                    tts.next();
1297                    let mut tt_iter = TokenTreeChildren::new(&tt);
1298                    if let Some(NodeOrToken::Token(lit)) = tt_iter.next()
1299                        && let Some(lit) = ast::IntNumber::cast(lit)
1300                        && let Ok(lit) = lit.value()
1301                        && let Ok(lit) = lit.try_into()
1302                    {
1303                        lit
1304                    } else {
1305                        0
1306                    }
1307                } else {
1308                    0
1309                };
1310                let pack = Some(Align::from_bytes(pack).unwrap_or(Align::ONE));
1311                ReprOptions { pack, ..Default::default() }
1312            }
1313            "align" => {
1314                let mut align = None;
1315                if let Some(NodeOrToken::Node(tt)) = tts.peek() {
1316                    let tt = tt.clone();
1317                    tts.next();
1318                    let mut tt_iter = TokenTreeChildren::new(&tt);
1319                    if let Some(NodeOrToken::Token(lit)) = tt_iter.next()
1320                        && let Some(lit) = ast::IntNumber::cast(lit)
1321                        && let Ok(lit) = lit.value()
1322                        && let Ok(lit) = lit.try_into()
1323                    {
1324                        align = Align::from_bytes(lit).ok();
1325                    }
1326                }
1327                ReprOptions { align, ..Default::default() }
1328            }
1329            "C" => ReprOptions { flags: ReprFlags::IS_C, ..Default::default() },
1330            "transparent" => ReprOptions { flags: ReprFlags::IS_TRANSPARENT, ..Default::default() },
1331            "simd" => ReprOptions { flags: ReprFlags::IS_SIMD, ..Default::default() },
1332            repr => {
1333                let mut int = None;
1334                if let Some(builtin) = BuiltinInt::from_suffix(repr)
1335                    .map(Either::Left)
1336                    .or_else(|| BuiltinUint::from_suffix(repr).map(Either::Right))
1337                {
1338                    int = Some(match builtin {
1339                        Either::Left(bi) => match bi {
1340                            BuiltinInt::Isize => IntegerType::Pointer(true),
1341                            BuiltinInt::I8 => IntegerType::Fixed(Integer::I8, true),
1342                            BuiltinInt::I16 => IntegerType::Fixed(Integer::I16, true),
1343                            BuiltinInt::I32 => IntegerType::Fixed(Integer::I32, true),
1344                            BuiltinInt::I64 => IntegerType::Fixed(Integer::I64, true),
1345                            BuiltinInt::I128 => IntegerType::Fixed(Integer::I128, true),
1346                        },
1347                        Either::Right(bu) => match bu {
1348                            BuiltinUint::Usize => IntegerType::Pointer(false),
1349                            BuiltinUint::U8 => IntegerType::Fixed(Integer::I8, false),
1350                            BuiltinUint::U16 => IntegerType::Fixed(Integer::I16, false),
1351                            BuiltinUint::U32 => IntegerType::Fixed(Integer::I32, false),
1352                            BuiltinUint::U64 => IntegerType::Fixed(Integer::I64, false),
1353                            BuiltinUint::U128 => IntegerType::Fixed(Integer::I128, false),
1354                        },
1355                    });
1356                }
1357                ReprOptions { int, ..Default::default() }
1358            }
1359        };
1360        merge_repr(&mut acc, repr);
1361    }
1362
1363    Some(acc)
1364}
1365
1366fn parse_rustc_legacy_const_generics(tt: ast::TokenTree) -> Box<[u32]> {
1367    TokenTreeChildren::new(&tt)
1368        .filter_map(|param| {
1369            ast::IntNumber::cast(param.into_token()?)?.value().ok()?.try_into().ok()
1370        })
1371        .collect()
1372}
1373
1374#[derive(Debug)]
1375enum DocAtom {
1376    /// eg. `#[doc(hidden)]`
1377    Flag(SmolStr),
1378    /// eg. `#[doc(alias = "it")]`
1379    ///
1380    /// Note that a key can have multiple values that are all considered "active" at the same time.
1381    /// For example, `#[doc(alias = "x")]` and `#[doc(alias = "y")]`.
1382    KeyValue { key: SmolStr, value: SmolStr },
1383    /// eg. `#[doc(alias("x", "y"))]`
1384    Alias(Vec<SmolStr>),
1385}
1386
1387impl DocAtom {
1388    fn parse(tt: ast::TokenTree) -> SmallVec<[DocAtom; 1]> {
1389        let mut iter = TokenTreeChildren::new(&tt).peekable();
1390        let mut result = SmallVec::new();
1391        while iter.peek().is_some() {
1392            if let Some(expr) = next_doc_expr(&mut iter) {
1393                result.push(expr);
1394            }
1395        }
1396        result
1397    }
1398}
1399
1400fn next_doc_expr(it: &mut Peekable<TokenTreeChildren>) -> Option<DocAtom> {
1401    let name = match it.next() {
1402        Some(NodeOrToken::Token(token)) if token.kind().is_any_identifier() => {
1403            SmolStr::new(token.text())
1404        }
1405        _ => return None,
1406    };
1407
1408    let ret = match it.peek() {
1409        Some(NodeOrToken::Token(eq)) if eq.kind() == T![=] => {
1410            it.next();
1411            if let Some(NodeOrToken::Token(value)) = it.next()
1412                && let Some(value) = ast::String::cast(value)
1413                && let Ok(value) = value.value()
1414            {
1415                DocAtom::KeyValue { key: name, value: SmolStr::new(&*value) }
1416            } else {
1417                return None;
1418            }
1419        }
1420        Some(NodeOrToken::Node(_)) if name == "notable_trait" => DocAtom::Flag(name),
1421        Some(NodeOrToken::Node(subtree)) => {
1422            if name != "alias" {
1423                return None;
1424            }
1425            let aliases = TokenTreeChildren::new(subtree)
1426                .filter_map(|alias| {
1427                    Some(SmolStr::new(&*ast::String::cast(alias.into_token()?)?.value().ok()?))
1428                })
1429                .collect();
1430            it.next();
1431            DocAtom::Alias(aliases)
1432        }
1433        _ => DocAtom::Flag(name),
1434    };
1435    Some(ret)
1436}
1437
1438#[cfg(test)]
1439mod tests {
1440    use test_fixture::WithFixture;
1441
1442    use crate::AttrDefId;
1443    use crate::attrs::AttrFlags;
1444    use crate::test_db::TestDB;
1445
1446    #[test]
1447    fn crate_attrs() {
1448        let fixture = r#"
1449//- /lib.rs crate:foo crate-attr:no_std crate-attr:cfg(target_arch="x86")
1450        "#;
1451        let (db, file_id) = TestDB::with_single_file(fixture);
1452        let module = db.module_for_file(file_id.file_id(&db));
1453        let attrs = AttrFlags::query(&db, AttrDefId::ModuleId(module));
1454        assert!(attrs.contains(AttrFlags::IS_NO_STD | AttrFlags::HAS_CFG));
1455    }
1456}