1 //! A simplified AST that only contains items.
3 //! This is the primary IR used throughout `hir_def`. It is the input to the name resolution
4 //! algorithm, as well as to the queries defined in `adt.rs`, `data.rs`, and most things in
7 //! `ItemTree`s are built per `HirFileId`, from the syntax tree of the parsed file. This means that
8 //! they are crate-independent: they don't know which `#[cfg]`s are active or which module they
9 //! belong to, since those concepts don't exist at this level (a single `ItemTree` might be part of
10 //! multiple crates, or might be included into the same crate twice via `#[path]`).
12 //! One important purpose of this layer is to provide an "invalidation barrier" for incremental
13 //! computations: when typing inside an item body, the `ItemTree` of the modified file is typically
14 //! unaffected, so we don't have to recompute name resolution results or item data (see `data.rs`).
16 //! The `ItemTree` for the currently open file can be displayed by using the VS Code command
17 //! "Rust Analyzer: Debug ItemTree".
19 //! Compared to rustc's architecture, `ItemTree` has properties from both rustc's AST and HIR: many
20 //! syntax-level Rust features are already desugared to simpler forms in the `ItemTree`, but name
21 //! resolution has not yet been performed. `ItemTree`s are per-file, while rustc's AST and HIR are
22 //! per-crate, because we are interested in incrementally computing it.
24 //! The representation of items in the `ItemTree` should generally mirror the surface syntax: it is
25 //! usually a bad idea to desugar a syntax-level construct to something that is structurally
26 //! different here. Name resolution needs to be able to process attributes and expand macros
27 //! (including attribute macros), and having a 1-to-1 mapping between syntax and the `ItemTree`
28 //! avoids introducing subtle bugs.
30 //! In general, any item in the `ItemTree` stores its `AstId`, which allows mapping it back to its
46 use ast::{AstNode, HasName, StructKind};
50 ast_id_map::FileAstId,
52 name::{name, AsName, Name},
53 ExpandTo, HirFileId, InFile,
55 use la_arena::{Arena, Idx, IdxRange, RawIdx};
57 use rustc_hash::FxHashMap;
58 use smallvec::SmallVec;
59 use syntax::{ast, match_ast, SyntaxKind};
62 attr::{Attrs, RawAttrs},
64 generics::GenericParams,
66 path::{path, AssociatedTypeBinding, GenericArgs, ImportAlias, ModPath, Path, PathKind},
67 type_ref::{Mutability, TraitRef, TypeBound, TypeRef},
68 visibility::RawVisibility,
72 #[derive(Copy, Clone, Eq, PartialEq)]
73 pub struct RawVisibilityId(u32);
75 impl RawVisibilityId {
76 pub const PUB: Self = RawVisibilityId(u32::max_value());
77 pub const PRIV: Self = RawVisibilityId(u32::max_value() - 1);
78 pub const PUB_CRATE: Self = RawVisibilityId(u32::max_value() - 2);
81 impl fmt::Debug for RawVisibilityId {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 let mut f = f.debug_tuple("RawVisibilityId");
85 Self::PUB => f.field(&"pub"),
86 Self::PRIV => f.field(&"pub(self)"),
87 Self::PUB_CRATE => f.field(&"pub(crate)"),
88 _ => f.field(&self.0),
94 /// The item tree of a source file.
95 #[derive(Debug, Default, Eq, PartialEq)]
99 top_level: SmallVec<[ModItem; 1]>,
100 attrs: FxHashMap<AttrOwner, RawAttrs>,
102 data: Option<Box<ItemTreeData>>,
106 pub(crate) fn file_item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<ItemTree> {
107 let _p = profile::span("item_tree_query").detail(|| format!("{:?}", file_id));
108 let syntax = if let Some(node) = db.parse_or_expand(file_id) {
109 if node.kind() == SyntaxKind::ERROR {
110 // FIXME: not 100% sure why these crop up, but return an empty tree to avoid a panic
111 return Default::default();
115 return Default::default();
118 let hygiene = Hygiene::new(db.upcast(), file_id);
119 let ctx = lower::Ctx::new(db, hygiene.clone(), file_id);
120 let mut top_attrs = None;
121 let mut item_tree = match_ast! {
123 ast::SourceFile(file) => {
124 top_attrs = Some(RawAttrs::new(db, &file, &hygiene));
125 ctx.lower_module_items(&file)
127 ast::MacroItems(items) => {
128 ctx.lower_module_items(&items)
130 ast::MacroStmts(stmts) => {
131 // The produced statements can include items, which should be added as top-level
133 ctx.lower_macro_stmts(stmts)
136 // FIXME: This occurs because macros in pattern position are treated as inner
137 // items and expanded during block DefMap computation
138 return Default::default();
141 // Types can contain inner items. We return an empty item tree in this case, but
142 // still need to collect inner items.
143 ctx.lower_inner_items(ty.syntax())
146 // Macros can expand to expressions. We return an empty item tree in this case, but
147 // still need to collect inner items.
148 ctx.lower_inner_items(e.syntax())
151 panic!("cannot create item tree from {:?} {}", syntax, syntax);
156 if let Some(attrs) = top_attrs {
157 item_tree.attrs.insert(AttrOwner::TopLevel, attrs);
159 item_tree.shrink_to_fit();
163 fn shrink_to_fit(&mut self) {
164 if let Some(data) = &mut self.data {
189 imports.shrink_to_fit();
190 extern_crates.shrink_to_fit();
191 extern_blocks.shrink_to_fit();
192 functions.shrink_to_fit();
193 params.shrink_to_fit();
194 structs.shrink_to_fit();
195 fields.shrink_to_fit();
196 unions.shrink_to_fit();
197 enums.shrink_to_fit();
198 variants.shrink_to_fit();
199 consts.shrink_to_fit();
200 statics.shrink_to_fit();
201 traits.shrink_to_fit();
202 impls.shrink_to_fit();
203 type_aliases.shrink_to_fit();
204 mods.shrink_to_fit();
205 macro_calls.shrink_to_fit();
206 macro_rules.shrink_to_fit();
207 macro_defs.shrink_to_fit();
209 vis.arena.shrink_to_fit();
211 inner_items.shrink_to_fit();
215 /// Returns an iterator over all items located at the top level of the `HirFileId` this
216 /// `ItemTree` was created from.
217 pub fn top_level_items(&self) -> &[ModItem] {
221 /// Returns the inner attributes of the source file.
222 pub fn top_level_attrs(&self, db: &dyn DefDatabase, krate: CrateId) -> Attrs {
223 self.attrs.get(&AttrOwner::TopLevel).unwrap_or(&RawAttrs::EMPTY).clone().filter(db, krate)
226 pub(crate) fn raw_attrs(&self, of: AttrOwner) -> &RawAttrs {
227 self.attrs.get(&of).unwrap_or(&RawAttrs::EMPTY)
230 pub fn attrs(&self, db: &dyn DefDatabase, krate: CrateId, of: AttrOwner) -> Attrs {
231 self.raw_attrs(of).clone().filter(db, krate)
234 pub fn inner_items_of_block(&self, block: FileAstId<ast::BlockExpr>) -> &[ModItem] {
236 Some(data) => data.inner_items.get(&block).map(|it| &**it).unwrap_or(&[]),
241 pub fn pretty_print(&self) -> String {
242 pretty::print_item_tree(self)
245 fn data(&self) -> &ItemTreeData {
246 self.data.as_ref().expect("attempted to access data of empty ItemTree")
249 fn data_mut(&mut self) -> &mut ItemTreeData {
250 self.data.get_or_insert_with(Box::default)
254 #[derive(Default, Debug, Eq, PartialEq)]
255 struct ItemVisibilities {
256 arena: Arena<RawVisibility>,
259 impl ItemVisibilities {
260 fn alloc(&mut self, vis: RawVisibility) -> RawVisibilityId {
262 RawVisibility::Public => RawVisibilityId::PUB,
263 RawVisibility::Module(path) if path.segments().is_empty() => match &path.kind {
264 PathKind::Super(0) => RawVisibilityId::PRIV,
265 PathKind::Crate => RawVisibilityId::PUB_CRATE,
266 _ => RawVisibilityId(self.arena.alloc(vis).into_raw().into()),
268 _ => RawVisibilityId(self.arena.alloc(vis).into_raw().into()),
273 static VIS_PUB: RawVisibility = RawVisibility::Public;
274 static VIS_PRIV: RawVisibility = RawVisibility::Module(ModPath::from_kind(PathKind::Super(0)));
275 static VIS_PUB_CRATE: RawVisibility = RawVisibility::Module(ModPath::from_kind(PathKind::Crate));
277 #[derive(Default, Debug, Eq, PartialEq)]
278 struct ItemTreeData {
279 imports: Arena<Import>,
280 extern_crates: Arena<ExternCrate>,
281 extern_blocks: Arena<ExternBlock>,
282 functions: Arena<Function>,
283 params: Arena<Param>,
284 structs: Arena<Struct>,
285 fields: Arena<Field>,
286 unions: Arena<Union>,
288 variants: Arena<Variant>,
289 consts: Arena<Const>,
290 statics: Arena<Static>,
291 traits: Arena<Trait>,
293 type_aliases: Arena<TypeAlias>,
295 macro_calls: Arena<MacroCall>,
296 macro_rules: Arena<MacroRules>,
297 macro_defs: Arena<MacroDef>,
299 vis: ItemVisibilities,
301 inner_items: FxHashMap<FileAstId<ast::BlockExpr>, SmallVec<[ModItem; 1]>>,
304 #[derive(Debug, Eq, PartialEq, Hash)]
306 /// Attributes on an item.
308 /// Inner attributes of the source file.
311 Variant(Idx<Variant>),
316 macro_rules! from_attrs {
317 ( $( $var:ident($t:ty) ),+ ) => {
319 impl From<$t> for AttrOwner {
320 fn from(t: $t) -> AttrOwner {
328 from_attrs!(ModItem(ModItem), Variant(Idx<Variant>), Field(Idx<Field>), Param(Idx<Param>));
330 /// Trait implemented by all item nodes in the item tree.
331 pub trait ItemTreeNode: Clone {
332 type Source: AstNode + Into<ast::Item>;
334 fn ast_id(&self) -> FileAstId<Self::Source>;
336 /// Looks up an instance of `Self` in an item tree.
337 fn lookup(tree: &ItemTree, index: Idx<Self>) -> &Self;
339 /// Downcasts a `ModItem` to a `FileItemTreeId` specific to this type.
340 fn id_from_mod_item(mod_item: ModItem) -> Option<FileItemTreeId<Self>>;
342 /// Upcasts a `FileItemTreeId` to a generic `ModItem`.
343 fn id_to_mod_item(id: FileItemTreeId<Self>) -> ModItem;
346 pub struct FileItemTreeId<N: ItemTreeNode> {
351 impl<N: ItemTreeNode> Clone for FileItemTreeId<N> {
352 fn clone(&self) -> Self {
353 Self { index: self.index, _p: PhantomData }
356 impl<N: ItemTreeNode> Copy for FileItemTreeId<N> {}
358 impl<N: ItemTreeNode> PartialEq for FileItemTreeId<N> {
359 fn eq(&self, other: &FileItemTreeId<N>) -> bool {
360 self.index == other.index
363 impl<N: ItemTreeNode> Eq for FileItemTreeId<N> {}
365 impl<N: ItemTreeNode> Hash for FileItemTreeId<N> {
366 fn hash<H: Hasher>(&self, state: &mut H) {
367 self.index.hash(state)
371 impl<N: ItemTreeNode> fmt::Debug for FileItemTreeId<N> {
372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377 /// Identifies a particular [`ItemTree`].
378 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
381 block: Option<BlockId>,
385 pub(crate) fn new(file: HirFileId, block: Option<BlockId>) -> Self {
389 pub(crate) fn item_tree(&self, db: &dyn DefDatabase) -> Arc<ItemTree> {
391 Some(_) => unreachable!("per-block ItemTrees are not yet implemented"),
392 None => db.file_item_tree(self.file),
396 pub(crate) fn file_id(self) -> HirFileId {
402 pub struct ItemTreeId<N: ItemTreeNode> {
404 pub value: FileItemTreeId<N>,
407 impl<N: ItemTreeNode> ItemTreeId<N> {
408 pub fn new(tree: TreeId, idx: FileItemTreeId<N>) -> Self {
409 Self { tree, value: idx }
412 pub fn file_id(self) -> HirFileId {
416 pub fn tree_id(self) -> TreeId {
420 pub fn item_tree(self, db: &dyn DefDatabase) -> Arc<ItemTree> {
421 self.tree.item_tree(db)
425 impl<N: ItemTreeNode> Copy for ItemTreeId<N> {}
426 impl<N: ItemTreeNode> Clone for ItemTreeId<N> {
427 fn clone(&self) -> Self {
432 impl<N: ItemTreeNode> PartialEq for ItemTreeId<N> {
433 fn eq(&self, other: &Self) -> bool {
434 self.tree == other.tree && self.value == other.value
438 impl<N: ItemTreeNode> Eq for ItemTreeId<N> {}
440 impl<N: ItemTreeNode> Hash for ItemTreeId<N> {
441 fn hash<H: Hasher>(&self, state: &mut H) {
442 self.tree.hash(state);
443 self.value.hash(state);
447 macro_rules! mod_items {
448 ( $( $typ:ident in $fld:ident -> $ast:ty ),+ $(,)? ) => {
449 #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
452 $typ(FileItemTreeId<$typ>),
457 impl From<FileItemTreeId<$typ>> for ModItem {
458 fn from(id: FileItemTreeId<$typ>) -> ModItem {
465 impl ItemTreeNode for $typ {
468 fn ast_id(&self) -> FileAstId<Self::Source> {
472 fn lookup(tree: &ItemTree, index: Idx<Self>) -> &Self {
473 &tree.data().$fld[index]
476 fn id_from_mod_item(mod_item: ModItem) -> Option<FileItemTreeId<Self>> {
478 ModItem::$typ(id) => Some(id),
483 fn id_to_mod_item(id: FileItemTreeId<Self>) -> ModItem {
488 impl Index<Idx<$typ>> for ItemTree {
491 fn index(&self, index: Idx<$typ>) -> &Self::Output {
492 &self.data().$fld[index]
500 Import in imports -> ast::Use,
501 ExternCrate in extern_crates -> ast::ExternCrate,
502 ExternBlock in extern_blocks -> ast::ExternBlock,
503 Function in functions -> ast::Fn,
504 Struct in structs -> ast::Struct,
505 Union in unions -> ast::Union,
506 Enum in enums -> ast::Enum,
507 Const in consts -> ast::Const,
508 Static in statics -> ast::Static,
509 Trait in traits -> ast::Trait,
510 Impl in impls -> ast::Impl,
511 TypeAlias in type_aliases -> ast::TypeAlias,
512 Mod in mods -> ast::Module,
513 MacroCall in macro_calls -> ast::MacroCall,
514 MacroRules in macro_rules -> ast::MacroRules,
515 MacroDef in macro_defs -> ast::MacroDef,
518 macro_rules! impl_index {
519 ( $($fld:ident: $t:ty),+ $(,)? ) => {
521 impl Index<Idx<$t>> for ItemTree {
524 fn index(&self, index: Idx<$t>) -> &Self::Output {
525 &self.data().$fld[index]
532 impl_index!(fields: Field, variants: Variant, params: Param);
534 impl Index<RawVisibilityId> for ItemTree {
535 type Output = RawVisibility;
536 fn index(&self, index: RawVisibilityId) -> &Self::Output {
538 RawVisibilityId::PRIV => &VIS_PRIV,
539 RawVisibilityId::PUB => &VIS_PUB,
540 RawVisibilityId::PUB_CRATE => &VIS_PUB_CRATE,
541 _ => &self.data().vis.arena[Idx::from_raw(index.0.into())],
546 impl<N: ItemTreeNode> Index<FileItemTreeId<N>> for ItemTree {
548 fn index(&self, id: FileItemTreeId<N>) -> &N {
549 N::lookup(self, id.index)
553 #[derive(Debug, Clone, Eq, PartialEq)]
555 pub visibility: RawVisibilityId,
556 pub ast_id: FileAstId<ast::Use>,
557 pub use_tree: UseTree,
560 #[derive(Debug, Clone, Eq, PartialEq)]
562 pub index: Idx<ast::UseTree>,
566 #[derive(Debug, Clone, Eq, PartialEq)]
567 pub enum UseTreeKind {
569 /// use path::to::Item;
570 /// use path::to::Item as Renamed;
571 /// use path::to::Trait as _;
573 Single { path: Interned<ModPath>, alias: Option<ImportAlias> },
576 /// use *; // (invalid, but can occur in nested tree)
579 Glob { path: Option<Interned<ModPath>> },
582 /// use prefix::{self, Item, ...};
584 Prefixed { prefix: Option<Interned<ModPath>>, list: Box<[UseTree]> },
587 #[derive(Debug, Clone, Eq, PartialEq)]
588 pub struct ExternCrate {
590 pub alias: Option<ImportAlias>,
591 pub visibility: RawVisibilityId,
592 pub ast_id: FileAstId<ast::ExternCrate>,
595 #[derive(Debug, Clone, Eq, PartialEq)]
596 pub struct ExternBlock {
597 pub abi: Option<Interned<str>>,
598 pub ast_id: FileAstId<ast::ExternBlock>,
599 pub children: Box<[ModItem]>,
602 #[derive(Debug, Clone, Eq, PartialEq)]
603 pub struct Function {
605 pub visibility: RawVisibilityId,
606 pub explicit_generic_params: Interned<GenericParams>,
607 pub abi: Option<Interned<str>>,
608 pub params: IdxRange<Param>,
609 pub ret_type: Interned<TypeRef>,
610 pub async_ret_type: Option<Interned<TypeRef>>,
611 pub ast_id: FileAstId<ast::Fn>,
612 pub(crate) flags: FnFlags,
615 #[derive(Debug, Clone, Eq, PartialEq)]
617 Normal(Interned<TypeRef>),
621 #[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
622 pub(crate) struct FnFlags {
626 pub(crate) const HAS_SELF_PARAM: u8 = 1 << 0;
627 pub(crate) const HAS_BODY: u8 = 1 << 1;
628 pub(crate) const IS_DEFAULT: u8 = 1 << 2;
629 pub(crate) const IS_CONST: u8 = 1 << 3;
630 pub(crate) const IS_ASYNC: u8 = 1 << 4;
631 pub(crate) const IS_UNSAFE: u8 = 1 << 5;
632 /// Whether the function is located in an `extern` block (*not* whether it is an
633 /// `extern "abi" fn`).
634 pub(crate) const IS_IN_EXTERN_BLOCK: u8 = 1 << 6;
635 pub(crate) const IS_VARARGS: u8 = 1 << 7;
638 #[derive(Debug, Clone, Eq, PartialEq)]
641 pub visibility: RawVisibilityId,
642 pub generic_params: Interned<GenericParams>,
644 pub ast_id: FileAstId<ast::Struct>,
647 #[derive(Debug, Clone, Eq, PartialEq)]
650 pub visibility: RawVisibilityId,
651 pub generic_params: Interned<GenericParams>,
653 pub ast_id: FileAstId<ast::Union>,
656 #[derive(Debug, Clone, Eq, PartialEq)]
659 pub visibility: RawVisibilityId,
660 pub generic_params: Interned<GenericParams>,
661 pub variants: IdxRange<Variant>,
662 pub ast_id: FileAstId<ast::Enum>,
665 #[derive(Debug, Clone, Eq, PartialEq)]
667 /// const _: () = ();
668 pub name: Option<Name>,
669 pub visibility: RawVisibilityId,
670 pub type_ref: Interned<TypeRef>,
671 pub ast_id: FileAstId<ast::Const>,
674 #[derive(Debug, Clone, Eq, PartialEq)]
677 pub visibility: RawVisibilityId,
679 /// Whether the static is in an `extern` block.
681 pub type_ref: Interned<TypeRef>,
682 pub ast_id: FileAstId<ast::Static>,
685 #[derive(Debug, Clone, Eq, PartialEq)]
688 pub visibility: RawVisibilityId,
689 pub generic_params: Interned<GenericParams>,
692 pub items: Box<[AssocItem]>,
693 pub ast_id: FileAstId<ast::Trait>,
696 #[derive(Debug, Clone, Eq, PartialEq)]
698 pub generic_params: Interned<GenericParams>,
699 pub target_trait: Option<Interned<TraitRef>>,
700 pub self_ty: Interned<TypeRef>,
701 pub is_negative: bool,
702 pub items: Box<[AssocItem]>,
703 pub ast_id: FileAstId<ast::Impl>,
706 #[derive(Debug, Clone, PartialEq, Eq)]
707 pub struct TypeAlias {
709 pub visibility: RawVisibilityId,
710 /// Bounds on the type alias itself. Only valid in trait declarations, eg. `type Assoc: Copy;`.
711 pub bounds: Box<[Interned<TypeBound>]>,
712 pub generic_params: Interned<GenericParams>,
713 pub type_ref: Option<Interned<TypeRef>>,
715 pub ast_id: FileAstId<ast::TypeAlias>,
718 #[derive(Debug, Clone, Eq, PartialEq)]
721 pub visibility: RawVisibilityId,
723 pub ast_id: FileAstId<ast::Module>,
726 #[derive(Debug, Clone, Eq, PartialEq)]
729 Inline { items: Box<[ModItem]> },
735 #[derive(Debug, Clone, Eq, PartialEq)]
736 pub struct MacroCall {
737 /// Path to the called macro.
738 pub path: Interned<ModPath>,
739 pub ast_id: FileAstId<ast::MacroCall>,
740 pub expand_to: ExpandTo,
743 #[derive(Debug, Clone, Eq, PartialEq)]
744 pub struct MacroRules {
745 /// The name of the declared macro.
747 pub ast_id: FileAstId<ast::MacroRules>,
750 /// "Macros 2.0" macro definition.
751 #[derive(Debug, Clone, Eq, PartialEq)]
752 pub struct MacroDef {
754 pub visibility: RawVisibilityId,
755 pub ast_id: FileAstId<ast::MacroDef>,
759 /// Maps a `UseTree` contained in this import back to its AST node.
760 pub fn use_tree_to_ast(
762 db: &dyn DefDatabase,
764 index: Idx<ast::UseTree>,
766 // Re-lower the AST item and get the source map.
767 // Note: The AST unwraps are fine, since if they fail we should have never obtained `index`.
768 let ast = InFile::new(file_id, self.ast_id).to_node(db.upcast());
769 let ast_use_tree = ast.use_tree().expect("missing `use_tree`");
770 let hygiene = Hygiene::new(db.upcast(), file_id);
771 let (_, source_map) =
772 lower::lower_use_tree(db, &hygiene, ast_use_tree).expect("failed to lower use tree");
773 source_map[index].clone()
777 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
778 pub enum ImportKind {
779 /// The `ModPath` is imported normally.
781 /// This is a glob-import of all names in the `ModPath`.
783 /// This is a `some::path::self` import, which imports `some::path` only in type namespace.
788 /// Expands the `UseTree` into individually imported `ModPath`s.
791 mut cb: impl FnMut(Idx<ast::UseTree>, ModPath, ImportKind, Option<ImportAlias>),
793 self.expand_impl(None, &mut cb)
798 prefix: Option<ModPath>,
799 cb: &mut dyn FnMut(Idx<ast::UseTree>, ModPath, ImportKind, Option<ImportAlias>),
802 prefix: Option<ModPath>,
804 ) -> Option<(ModPath, ImportKind)> {
805 match (prefix, &path.kind) {
806 (None, _) => Some((path.clone(), ImportKind::Plain)),
807 (Some(mut prefix), PathKind::Plain) => {
808 for segment in path.segments() {
809 prefix.push_segment(segment.clone());
811 Some((prefix, ImportKind::Plain))
813 (Some(prefix), PathKind::Super(0)) => {
814 // `some::path::self` == `some::path`
815 if path.segments().is_empty() {
816 Some((prefix, ImportKind::TypeOnly))
821 (Some(_), _) => None,
826 UseTreeKind::Single { path, alias } => {
827 if let Some((path, kind)) = concat_mod_paths(prefix, path) {
828 cb(self.index, path, kind, alias.clone());
831 UseTreeKind::Glob { path: Some(path) } => {
832 if let Some((path, _)) = concat_mod_paths(prefix, path) {
833 cb(self.index, path, ImportKind::Glob, None);
836 UseTreeKind::Glob { path: None } => {
837 if let Some(prefix) = prefix {
838 cb(self.index, prefix, ImportKind::Glob, None);
841 UseTreeKind::Prefixed { prefix: additional_prefix, list } => {
842 let prefix = match additional_prefix {
843 Some(path) => match concat_mod_paths(prefix, path) {
844 Some((path, ImportKind::Plain)) => Some(path),
849 for tree in &**list {
850 tree.expand_impl(prefix.clone(), cb);
857 macro_rules! impl_froms {
858 ($e:ident { $($v:ident ($t:ty)),* $(,)? }) => {
860 impl From<$t> for $e {
861 fn from(it: $t) -> $e {
870 pub fn as_assoc_item(&self) -> Option<AssocItem> {
873 | ModItem::ExternCrate(_)
874 | ModItem::ExternBlock(_)
882 | ModItem::MacroRules(_)
883 | ModItem::MacroDef(_) => None,
884 ModItem::MacroCall(call) => Some(AssocItem::MacroCall(*call)),
885 ModItem::Const(konst) => Some(AssocItem::Const(*konst)),
886 ModItem::TypeAlias(alias) => Some(AssocItem::TypeAlias(*alias)),
887 ModItem::Function(func) => Some(AssocItem::Function(*func)),
891 pub fn downcast<N: ItemTreeNode>(self) -> Option<FileItemTreeId<N>> {
892 N::id_from_mod_item(self)
895 pub fn ast_id(&self, tree: &ItemTree) -> FileAstId<ast::Item> {
897 ModItem::Import(it) => tree[it.index].ast_id().upcast(),
898 ModItem::ExternCrate(it) => tree[it.index].ast_id().upcast(),
899 ModItem::ExternBlock(it) => tree[it.index].ast_id().upcast(),
900 ModItem::Function(it) => tree[it.index].ast_id().upcast(),
901 ModItem::Struct(it) => tree[it.index].ast_id().upcast(),
902 ModItem::Union(it) => tree[it.index].ast_id().upcast(),
903 ModItem::Enum(it) => tree[it.index].ast_id().upcast(),
904 ModItem::Const(it) => tree[it.index].ast_id().upcast(),
905 ModItem::Static(it) => tree[it.index].ast_id().upcast(),
906 ModItem::Trait(it) => tree[it.index].ast_id().upcast(),
907 ModItem::Impl(it) => tree[it.index].ast_id().upcast(),
908 ModItem::TypeAlias(it) => tree[it.index].ast_id().upcast(),
909 ModItem::Mod(it) => tree[it.index].ast_id().upcast(),
910 ModItem::MacroCall(it) => tree[it.index].ast_id().upcast(),
911 ModItem::MacroRules(it) => tree[it.index].ast_id().upcast(),
912 ModItem::MacroDef(it) => tree[it.index].ast_id().upcast(),
917 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
919 Function(FileItemTreeId<Function>),
920 TypeAlias(FileItemTreeId<TypeAlias>),
921 Const(FileItemTreeId<Const>),
922 MacroCall(FileItemTreeId<MacroCall>),
925 impl_froms!(AssocItem {
926 Function(FileItemTreeId<Function>),
927 TypeAlias(FileItemTreeId<TypeAlias>),
928 Const(FileItemTreeId<Const>),
929 MacroCall(FileItemTreeId<MacroCall>),
932 impl From<AssocItem> for ModItem {
933 fn from(item: AssocItem) -> Self {
935 AssocItem::Function(it) => it.into(),
936 AssocItem::TypeAlias(it) => it.into(),
937 AssocItem::Const(it) => it.into(),
938 AssocItem::MacroCall(it) => it.into(),
943 #[derive(Debug, Eq, PartialEq)]
949 #[derive(Debug, Clone, PartialEq, Eq)]
951 Record(IdxRange<Field>),
952 Tuple(IdxRange<Field>),
956 /// A single field of an enum variant or struct
957 #[derive(Debug, Clone, PartialEq, Eq)]
960 pub type_ref: Interned<TypeRef>,
961 pub visibility: RawVisibilityId,