1 //! A simplified AST that only contains items.
14 use ast::{AstNode, NameOwner, StructKind};
18 ast_id_map::FileAstId,
20 name::{name, AsName, Name},
23 use la_arena::{Arena, Idx, RawIdx};
24 use rustc_hash::FxHashMap;
25 use smallvec::SmallVec;
26 use syntax::{ast, match_ast};
30 attr::{Attrs, RawAttrs},
32 generics::GenericParams,
33 path::{path, AssociatedTypeBinding, GenericArgs, ImportAlias, ModPath, Path, PathKind},
34 type_ref::{Mutability, TypeBound, TypeRef},
35 visibility::RawVisibility,
38 #[derive(Copy, Clone, Eq, PartialEq)]
39 pub struct RawVisibilityId(u32);
41 impl RawVisibilityId {
42 pub const PUB: Self = RawVisibilityId(u32::max_value());
43 pub const PRIV: Self = RawVisibilityId(u32::max_value() - 1);
44 pub const PUB_CRATE: Self = RawVisibilityId(u32::max_value() - 2);
47 impl fmt::Debug for RawVisibilityId {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 let mut f = f.debug_tuple("RawVisibilityId");
51 Self::PUB => f.field(&"pub"),
52 Self::PRIV => f.field(&"pub(self)"),
53 Self::PUB_CRATE => f.field(&"pub(crate)"),
54 _ => f.field(&self.0),
60 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
61 pub struct GenericParamsId(u32);
63 impl GenericParamsId {
64 pub const EMPTY: Self = GenericParamsId(u32::max_value());
67 /// The item tree of a source file.
68 #[derive(Debug, Eq, PartialEq)]
70 top_level: SmallVec<[ModItem; 1]>,
71 attrs: FxHashMap<AttrOwner, RawAttrs>,
73 data: Option<Box<ItemTreeData>>,
77 pub(crate) fn item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<ItemTree> {
78 let _p = profile::span("item_tree_query").detail(|| format!("{:?}", file_id));
79 let syntax = if let Some(node) = db.parse_or_expand(file_id) {
82 return Arc::new(Self::empty());
85 let hygiene = Hygiene::new(db.upcast(), file_id);
86 let ctx = lower::Ctx::new(db, hygiene.clone(), file_id);
87 let mut top_attrs = None;
88 let mut item_tree = match_ast! {
90 ast::SourceFile(file) => {
91 top_attrs = Some(RawAttrs::new(&file, &hygiene));
92 ctx.lower_module_items(&file)
94 ast::MacroItems(items) => {
95 ctx.lower_module_items(&items)
97 ast::MacroStmts(stmts) => {
98 ctx.lower_inner_items(stmts.syntax())
100 // Macros can expand to expressions. We return an empty item tree in this case, but
101 // still need to collect inner items.
103 ctx.lower_inner_items(e.syntax())
106 panic!("cannot create item tree from {:?}", syntax);
111 if let Some(attrs) = top_attrs {
112 item_tree.attrs.insert(AttrOwner::TopLevel, attrs);
114 item_tree.shrink_to_fit();
119 Self { top_level: Default::default(), attrs: Default::default(), data: Default::default() }
122 fn shrink_to_fit(&mut self) {
123 if let Some(data) = &mut self.data {
147 imports.shrink_to_fit();
148 extern_crates.shrink_to_fit();
149 functions.shrink_to_fit();
150 structs.shrink_to_fit();
151 fields.shrink_to_fit();
152 unions.shrink_to_fit();
153 enums.shrink_to_fit();
154 variants.shrink_to_fit();
155 consts.shrink_to_fit();
156 statics.shrink_to_fit();
157 traits.shrink_to_fit();
158 impls.shrink_to_fit();
159 type_aliases.shrink_to_fit();
160 mods.shrink_to_fit();
161 macro_calls.shrink_to_fit();
162 macro_rules.shrink_to_fit();
163 macro_defs.shrink_to_fit();
165 vis.arena.shrink_to_fit();
166 generics.arena.shrink_to_fit();
168 inner_items.shrink_to_fit();
172 /// Returns an iterator over all items located at the top level of the `HirFileId` this
173 /// `ItemTree` was created from.
174 pub fn top_level_items(&self) -> &[ModItem] {
178 /// Returns the inner attributes of the source file.
179 pub fn top_level_attrs(&self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
180 self.attrs.get(&AttrOwner::TopLevel).unwrap_or(&RawAttrs::EMPTY).clone().filter(db, krate)
183 pub(crate) fn raw_attrs(&self, of: AttrOwner) -> &RawAttrs {
184 self.attrs.get(&of).unwrap_or(&RawAttrs::EMPTY)
187 pub fn attrs(&self, db: &dyn DefDatabase, krate: CrateId, of: AttrOwner) -> Attrs {
188 self.raw_attrs(of).clone().filter(db, krate)
191 pub fn all_inner_items(&self) -> impl Iterator<Item = ModItem> + '_ {
193 Some(data) => Some(data.inner_items.values().flatten().copied()).into_iter().flatten(),
194 None => None.into_iter().flatten(),
198 pub fn inner_items_of_block(&self, block: FileAstId<ast::BlockExpr>) -> &[ModItem] {
200 Some(data) => data.inner_items.get(&block).map(|it| &**it).unwrap_or(&[]),
205 pub fn source<S: ItemTreeNode>(&self, db: &dyn DefDatabase, of: ItemTreeId<S>) -> S::Source {
206 // This unwrap cannot fail, since it has either succeeded above, or resulted in an empty
207 // ItemTree (in which case there is no valid `FileItemTreeId` to call this method with).
209 db.parse_or_expand(of.file_id).expect("parse_or_expand failed on constructed ItemTree");
211 let id = self[of.value].ast_id();
212 let map = db.ast_id_map(of.file_id);
213 let ptr = map.get(id);
217 fn data(&self) -> &ItemTreeData {
218 self.data.as_ref().expect("attempted to access data of empty ItemTree")
221 fn data_mut(&mut self) -> &mut ItemTreeData {
222 self.data.get_or_insert_with(Box::default)
226 #[derive(Default, Debug, Eq, PartialEq)]
227 struct ItemVisibilities {
228 arena: Arena<RawVisibility>,
231 impl ItemVisibilities {
232 fn alloc(&mut self, vis: RawVisibility) -> RawVisibilityId {
234 RawVisibility::Public => RawVisibilityId::PUB,
235 RawVisibility::Module(path) if path.segments.is_empty() => match &path.kind {
236 PathKind::Super(0) => RawVisibilityId::PRIV,
237 PathKind::Crate => RawVisibilityId::PUB_CRATE,
238 _ => RawVisibilityId(self.arena.alloc(vis).into_raw().into()),
240 _ => RawVisibilityId(self.arena.alloc(vis).into_raw().into()),
245 static VIS_PUB: RawVisibility = RawVisibility::Public;
246 static VIS_PRIV: RawVisibility =
247 RawVisibility::Module(ModPath { kind: PathKind::Super(0), segments: Vec::new() });
248 static VIS_PUB_CRATE: RawVisibility =
249 RawVisibility::Module(ModPath { kind: PathKind::Crate, segments: Vec::new() });
251 #[derive(Default, Debug, Eq, PartialEq)]
252 struct GenericParamsStorage {
253 arena: Arena<GenericParams>,
256 impl GenericParamsStorage {
257 fn alloc(&mut self, params: GenericParams) -> GenericParamsId {
258 if params.types.is_empty()
259 && params.lifetimes.is_empty()
260 && params.consts.is_empty()
261 && params.where_predicates.is_empty()
263 return GenericParamsId::EMPTY;
266 GenericParamsId(self.arena.alloc(params).into_raw().into())
270 static EMPTY_GENERICS: GenericParams = GenericParams {
272 lifetimes: Arena::new(),
273 consts: Arena::new(),
274 where_predicates: Vec::new(),
277 #[derive(Default, Debug, Eq, PartialEq)]
278 struct ItemTreeData {
279 imports: Arena<Import>,
280 extern_crates: Arena<ExternCrate>,
281 functions: Arena<Function>,
282 structs: Arena<Struct>,
283 fields: Arena<Field>,
284 unions: Arena<Union>,
286 variants: Arena<Variant>,
287 consts: Arena<Const>,
288 statics: Arena<Static>,
289 traits: Arena<Trait>,
291 type_aliases: Arena<TypeAlias>,
293 macro_calls: Arena<MacroCall>,
294 macro_rules: Arena<MacroRules>,
295 macro_defs: Arena<MacroDef>,
297 vis: ItemVisibilities,
298 generics: GenericParamsStorage,
300 inner_items: FxHashMap<FileAstId<ast::BlockExpr>, SmallVec<[ModItem; 1]>>,
303 #[derive(Debug, Eq, PartialEq, Hash)]
305 /// Attributes on an item.
307 /// Inner attributes of the source file.
310 Variant(Idx<Variant>),
314 macro_rules! from_attrs {
315 ( $( $var:ident($t:ty) ),+ ) => {
317 impl From<$t> for AttrOwner {
318 fn from(t: $t) -> AttrOwner {
326 from_attrs!(ModItem(ModItem), Variant(Idx<Variant>), Field(Idx<Field>));
328 /// Trait implemented by all item nodes in the item tree.
329 pub trait ItemTreeNode: Clone {
330 type Source: AstNode + Into<ast::Item>;
332 fn ast_id(&self) -> FileAstId<Self::Source>;
334 /// Looks up an instance of `Self` in an item tree.
335 fn lookup(tree: &ItemTree, index: Idx<Self>) -> &Self;
337 /// Downcasts a `ModItem` to a `FileItemTreeId` specific to this type.
338 fn id_from_mod_item(mod_item: ModItem) -> Option<FileItemTreeId<Self>>;
340 /// Upcasts a `FileItemTreeId` to a generic `ModItem`.
341 fn id_to_mod_item(id: FileItemTreeId<Self>) -> ModItem;
344 pub struct FileItemTreeId<N: ItemTreeNode> {
349 impl<N: ItemTreeNode> Clone for FileItemTreeId<N> {
350 fn clone(&self) -> Self {
351 Self { index: self.index, _p: PhantomData }
354 impl<N: ItemTreeNode> Copy for FileItemTreeId<N> {}
356 impl<N: ItemTreeNode> PartialEq for FileItemTreeId<N> {
357 fn eq(&self, other: &FileItemTreeId<N>) -> bool {
358 self.index == other.index
361 impl<N: ItemTreeNode> Eq for FileItemTreeId<N> {}
363 impl<N: ItemTreeNode> Hash for FileItemTreeId<N> {
364 fn hash<H: Hasher>(&self, state: &mut H) {
365 self.index.hash(state)
369 impl<N: ItemTreeNode> fmt::Debug for FileItemTreeId<N> {
370 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375 pub type ItemTreeId<N> = InFile<FileItemTreeId<N>>;
377 macro_rules! mod_items {
378 ( $( $typ:ident in $fld:ident -> $ast:ty ),+ $(,)? ) => {
379 #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
382 $typ(FileItemTreeId<$typ>),
387 impl From<FileItemTreeId<$typ>> for ModItem {
388 fn from(id: FileItemTreeId<$typ>) -> ModItem {
395 impl ItemTreeNode for $typ {
398 fn ast_id(&self) -> FileAstId<Self::Source> {
402 fn lookup(tree: &ItemTree, index: Idx<Self>) -> &Self {
403 &tree.data().$fld[index]
406 fn id_from_mod_item(mod_item: ModItem) -> Option<FileItemTreeId<Self>> {
407 if let ModItem::$typ(id) = mod_item {
414 fn id_to_mod_item(id: FileItemTreeId<Self>) -> ModItem {
419 impl Index<Idx<$typ>> for ItemTree {
422 fn index(&self, index: Idx<$typ>) -> &Self::Output {
423 &self.data().$fld[index]
431 Import in imports -> ast::Use,
432 ExternCrate in extern_crates -> ast::ExternCrate,
433 Function in functions -> ast::Fn,
434 Struct in structs -> ast::Struct,
435 Union in unions -> ast::Union,
436 Enum in enums -> ast::Enum,
437 Const in consts -> ast::Const,
438 Static in statics -> ast::Static,
439 Trait in traits -> ast::Trait,
440 Impl in impls -> ast::Impl,
441 TypeAlias in type_aliases -> ast::TypeAlias,
442 Mod in mods -> ast::Module,
443 MacroCall in macro_calls -> ast::MacroCall,
444 MacroRules in macro_rules -> ast::MacroRules,
445 MacroDef in macro_defs -> ast::MacroDef,
448 macro_rules! impl_index {
449 ( $($fld:ident: $t:ty),+ $(,)? ) => {
451 impl Index<Idx<$t>> for ItemTree {
454 fn index(&self, index: Idx<$t>) -> &Self::Output {
455 &self.data().$fld[index]
462 impl_index!(fields: Field, variants: Variant);
464 impl Index<RawVisibilityId> for ItemTree {
465 type Output = RawVisibility;
466 fn index(&self, index: RawVisibilityId) -> &Self::Output {
468 RawVisibilityId::PRIV => &VIS_PRIV,
469 RawVisibilityId::PUB => &VIS_PUB,
470 RawVisibilityId::PUB_CRATE => &VIS_PUB_CRATE,
471 _ => &self.data().vis.arena[Idx::from_raw(index.0.into())],
476 impl Index<GenericParamsId> for ItemTree {
477 type Output = GenericParams;
479 fn index(&self, index: GenericParamsId) -> &Self::Output {
481 GenericParamsId::EMPTY => &EMPTY_GENERICS,
482 _ => &self.data().generics.arena[Idx::from_raw(index.0.into())],
487 impl<N: ItemTreeNode> Index<FileItemTreeId<N>> for ItemTree {
489 fn index(&self, id: FileItemTreeId<N>) -> &N {
490 N::lookup(self, id.index)
494 /// A desugared `use` import.
495 #[derive(Debug, Clone, Eq, PartialEq)]
498 pub alias: Option<ImportAlias>,
499 pub visibility: RawVisibilityId,
501 /// AST ID of the `use` or `extern crate` item this import was derived from. Note that many
502 /// `Import`s can map to the same `use` item.
503 pub ast_id: FileAstId<ast::Use>,
504 /// Index of this `Import` when the containing `Use` is visited via `ModPath::expand_use_item`.
506 /// This can be used to get the `UseTree` this `Import` corresponds to and allows emitting
507 /// precise diagnostics.
511 #[derive(Debug, Clone, Eq, PartialEq)]
512 pub struct ExternCrate {
514 pub alias: Option<ImportAlias>,
515 pub visibility: RawVisibilityId,
516 pub ast_id: FileAstId<ast::ExternCrate>,
519 #[derive(Debug, Clone, Eq, PartialEq)]
520 pub struct Function {
522 pub visibility: RawVisibilityId,
523 pub generic_params: GenericParamsId,
524 pub has_self_param: bool,
527 /// Whether the function is located in an `extern` block (*not* whether it is an
528 /// `extern "abi" fn`).
530 pub params: Box<[TypeRef]>,
531 pub is_varargs: bool,
532 pub ret_type: TypeRef,
533 pub ast_id: FileAstId<ast::Fn>,
536 #[derive(Debug, Clone, Eq, PartialEq)]
539 pub visibility: RawVisibilityId,
540 pub generic_params: GenericParamsId,
542 pub ast_id: FileAstId<ast::Struct>,
543 pub kind: StructDefKind,
546 #[derive(Debug, Clone, Eq, PartialEq)]
547 pub enum StructDefKind {
548 /// `struct S { ... }` - type namespace only.
556 #[derive(Debug, Clone, Eq, PartialEq)]
559 pub visibility: RawVisibilityId,
560 pub generic_params: GenericParamsId,
562 pub ast_id: FileAstId<ast::Union>,
565 #[derive(Debug, Clone, Eq, PartialEq)]
568 pub visibility: RawVisibilityId,
569 pub generic_params: GenericParamsId,
570 pub variants: IdRange<Variant>,
571 pub ast_id: FileAstId<ast::Enum>,
574 #[derive(Debug, Clone, Eq, PartialEq)]
576 /// const _: () = ();
577 pub name: Option<Name>,
578 pub visibility: RawVisibilityId,
579 pub type_ref: TypeRef,
580 pub ast_id: FileAstId<ast::Const>,
583 #[derive(Debug, Clone, Eq, PartialEq)]
586 pub visibility: RawVisibilityId,
588 /// Whether the static is in an `extern` block.
590 pub type_ref: TypeRef,
591 pub ast_id: FileAstId<ast::Static>,
594 #[derive(Debug, Clone, Eq, PartialEq)]
597 pub visibility: RawVisibilityId,
598 pub generic_params: GenericParamsId,
600 pub items: Box<[AssocItem]>,
601 pub ast_id: FileAstId<ast::Trait>,
604 #[derive(Debug, Clone, Eq, PartialEq)]
606 pub generic_params: GenericParamsId,
607 pub target_trait: Option<TypeRef>,
608 pub target_type: TypeRef,
609 pub is_negative: bool,
610 pub items: Box<[AssocItem]>,
611 pub ast_id: FileAstId<ast::Impl>,
614 #[derive(Debug, Clone, PartialEq, Eq)]
615 pub struct TypeAlias {
617 pub visibility: RawVisibilityId,
618 /// Bounds on the type alias itself. Only valid in trait declarations, eg. `type Assoc: Copy;`.
619 pub bounds: Box<[TypeBound]>,
620 pub generic_params: GenericParamsId,
621 pub type_ref: Option<TypeRef>,
623 pub ast_id: FileAstId<ast::TypeAlias>,
626 #[derive(Debug, Clone, Eq, PartialEq)]
629 pub visibility: RawVisibilityId,
631 pub ast_id: FileAstId<ast::Module>,
634 #[derive(Debug, Clone, Eq, PartialEq)]
637 Inline { items: Box<[ModItem]> },
643 #[derive(Debug, Clone, Eq, PartialEq)]
644 pub struct MacroCall {
645 /// Path to the called macro.
647 pub ast_id: FileAstId<ast::MacroCall>,
650 #[derive(Debug, Clone, Eq, PartialEq)]
651 pub struct MacroRules {
652 /// The name of the declared macro.
654 pub ast_id: FileAstId<ast::MacroRules>,
657 /// "Macros 2.0" macro definition.
658 #[derive(Debug, Clone, Eq, PartialEq)]
659 pub struct MacroDef {
661 pub visibility: RawVisibilityId,
662 pub ast_id: FileAstId<ast::MacroDef>,
665 macro_rules! impl_froms {
666 ($e:ident { $($v:ident ($t:ty)),* $(,)? }) => {
668 impl From<$t> for $e {
669 fn from(it: $t) -> $e {
678 pub fn as_assoc_item(&self) -> Option<AssocItem> {
681 | ModItem::ExternCrate(_)
689 | ModItem::MacroRules(_)
690 | ModItem::MacroDef(_) => None,
691 ModItem::MacroCall(call) => Some(AssocItem::MacroCall(*call)),
692 ModItem::Const(konst) => Some(AssocItem::Const(*konst)),
693 ModItem::TypeAlias(alias) => Some(AssocItem::TypeAlias(*alias)),
694 ModItem::Function(func) => Some(AssocItem::Function(*func)),
698 pub fn downcast<N: ItemTreeNode>(self) -> Option<FileItemTreeId<N>> {
699 N::id_from_mod_item(self)
702 pub fn ast_id(&self, tree: &ItemTree) -> FileAstId<ast::Item> {
704 ModItem::Import(it) => tree[it.index].ast_id().upcast(),
705 ModItem::ExternCrate(it) => tree[it.index].ast_id().upcast(),
706 ModItem::Function(it) => tree[it.index].ast_id().upcast(),
707 ModItem::Struct(it) => tree[it.index].ast_id().upcast(),
708 ModItem::Union(it) => tree[it.index].ast_id().upcast(),
709 ModItem::Enum(it) => tree[it.index].ast_id().upcast(),
710 ModItem::Const(it) => tree[it.index].ast_id().upcast(),
711 ModItem::Static(it) => tree[it.index].ast_id().upcast(),
712 ModItem::Trait(it) => tree[it.index].ast_id().upcast(),
713 ModItem::Impl(it) => tree[it.index].ast_id().upcast(),
714 ModItem::TypeAlias(it) => tree[it.index].ast_id().upcast(),
715 ModItem::Mod(it) => tree[it.index].ast_id().upcast(),
716 ModItem::MacroCall(it) => tree[it.index].ast_id().upcast(),
717 ModItem::MacroRules(it) => tree[it.index].ast_id().upcast(),
718 ModItem::MacroDef(it) => tree[it.index].ast_id().upcast(),
723 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
725 Function(FileItemTreeId<Function>),
726 TypeAlias(FileItemTreeId<TypeAlias>),
727 Const(FileItemTreeId<Const>),
728 MacroCall(FileItemTreeId<MacroCall>),
731 impl_froms!(AssocItem {
732 Function(FileItemTreeId<Function>),
733 TypeAlias(FileItemTreeId<TypeAlias>),
734 Const(FileItemTreeId<Const>),
735 MacroCall(FileItemTreeId<MacroCall>),
738 impl From<AssocItem> for ModItem {
739 fn from(item: AssocItem) -> Self {
741 AssocItem::Function(it) => it.into(),
742 AssocItem::TypeAlias(it) => it.into(),
743 AssocItem::Const(it) => it.into(),
744 AssocItem::MacroCall(it) => it.into(),
749 #[derive(Debug, Eq, PartialEq)]
755 pub struct IdRange<T> {
761 fn new(range: Range<Idx<T>>) -> Self {
762 Self { range: range.start.into_raw().into()..range.end.into_raw().into(), _p: PhantomData }
766 impl<T> Iterator for IdRange<T> {
768 fn next(&mut self) -> Option<Self::Item> {
769 self.range.next().map(|raw| Idx::from_raw(raw.into()))
773 impl<T> fmt::Debug for IdRange<T> {
774 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775 f.debug_tuple(&format!("IdRange::<{}>", type_name::<T>())).field(&self.range).finish()
779 impl<T> Clone for IdRange<T> {
780 fn clone(&self) -> Self {
781 Self { range: self.range.clone(), _p: PhantomData }
785 impl<T> PartialEq for IdRange<T> {
786 fn eq(&self, other: &Self) -> bool {
787 self.range == other.range
791 impl<T> Eq for IdRange<T> {}
793 #[derive(Debug, Clone, PartialEq, Eq)]
795 Record(IdRange<Field>),
796 Tuple(IdRange<Field>),
800 /// A single field of an enum variant or struct
801 #[derive(Debug, Clone, PartialEq, Eq)]
804 pub type_ref: TypeRef,
805 pub visibility: RawVisibilityId,