1 use super::{ItemTree, ModItem, ModKind};
2 use crate::{db::DefDatabase, test_db::TestDB};
3 use hir_expand::db::AstDatabase;
4 use insta::assert_snapshot;
5 use ra_db::fixture::WithFixture;
6 use ra_syntax::{ast, AstNode};
7 use rustc_hash::FxHashSet;
11 fn test_inner_items(ra_fixture: &str) {
12 let (db, file_id) = TestDB::with_single_file(ra_fixture);
13 let tree = db.item_tree(file_id.into());
14 let root = db.parse_or_expand(file_id.into()).unwrap();
15 let ast_id_map = db.ast_id_map(file_id.into());
17 // Traverse the item tree and collect all module/impl/trait-level items as AST nodes.
18 let mut outer_items = FxHashSet::default();
19 let mut worklist = tree.top_level_items().to_vec();
20 while let Some(item) = worklist.pop() {
21 let node: ast::ModuleItem = match item {
22 ModItem::Import(it) => tree.source(&db, it).into(),
23 ModItem::ExternCrate(it) => tree.source(&db, it).into(),
24 ModItem::Function(it) => tree.source(&db, it).into(),
25 ModItem::Struct(it) => tree.source(&db, it).into(),
26 ModItem::Union(it) => tree.source(&db, it).into(),
27 ModItem::Enum(it) => tree.source(&db, it).into(),
28 ModItem::Const(it) => tree.source(&db, it).into(),
29 ModItem::Static(it) => tree.source(&db, it).into(),
30 ModItem::TypeAlias(it) => tree.source(&db, it).into(),
32 if let ModKind::Inline { items } = &tree[it].kind {
33 worklist.extend(items);
35 tree.source(&db, it).into()
37 ModItem::Trait(it) => {
38 worklist.extend(tree[it].items.iter().map(|item| ModItem::from(*item)));
39 tree.source(&db, it).into()
41 ModItem::Impl(it) => {
42 worklist.extend(tree[it].items.iter().map(|item| ModItem::from(*item)));
43 tree.source(&db, it).into()
45 ModItem::MacroCall(_) => continue,
48 outer_items.insert(node);
51 // Now descend the root node and check that all `ast::ModuleItem`s are either recorded above, or
52 // registered as inner items.
53 for item in root.descendants().skip(1).filter_map(ast::ModuleItem::cast) {
54 if outer_items.contains(&item) {
58 let ast_id = ast_id_map.ast_id(&item);
59 assert!(!tree.inner_items(ast_id).is_empty());
63 fn item_tree(ra_fixture: &str) -> Arc<ItemTree> {
64 let (db, file_id) = TestDB::with_single_file(ra_fixture);
65 db.item_tree(file_id.into())
68 fn print_item_tree(ra_fixture: &str) -> String {
69 let tree = item_tree(ra_fixture);
70 let mut out = String::new();
72 format_to!(out, "inner attrs: {:?}\n\n", tree.top_level_attrs());
73 format_to!(out, "top-level items:\n");
74 for item in tree.top_level_items() {
75 fmt_mod_item(&mut out, &tree, *item);
76 format_to!(out, "\n");
79 if !tree.inner_items.is_empty() {
80 format_to!(out, "\ninner items:\n");
81 for (ast_id, items) in &tree.inner_items {
82 format_to!(out, "{:?}:\n", ast_id);
84 format_to!(out, "- ");
85 fmt_mod_item(&mut out, &tree, *inner);
86 format_to!(out, "\n");
94 fn fmt_mod_item(out: &mut String, tree: &ItemTree, item: ModItem) {
96 ModItem::ExternCrate(it) => {
97 format_to!(out, "{:?}", tree[it]);
99 ModItem::Import(it) => {
100 format_to!(out, "{:?}", tree[it]);
102 ModItem::Function(it) => {
103 format_to!(out, "{:?}", tree[it]);
105 ModItem::Struct(it) => {
106 format_to!(out, "{:?}", tree[it]);
108 ModItem::Union(it) => {
109 format_to!(out, "{:?}", tree[it]);
111 ModItem::Enum(it) => {
112 format_to!(out, "{:?}", tree[it]);
114 ModItem::Const(it) => {
115 format_to!(out, "{:?}", tree[it]);
117 ModItem::Static(it) => {
118 format_to!(out, "{:?}", tree[it]);
120 ModItem::Trait(it) => {
121 format_to!(out, "{:?}", tree[it]);
123 ModItem::Impl(it) => {
124 format_to!(out, "{:?}", tree[it]);
126 ModItem::TypeAlias(it) => {
127 format_to!(out, "{:?}", tree[it]);
129 ModItem::Mod(it) => {
130 format_to!(out, "{:?}", tree[it]);
132 ModItem::MacroCall(it) => {
133 format_to!(out, "{:?}", tree[it]);
140 assert_snapshot!(print_item_tree(r"
147 type AssocTy: Tr<()>;
150 fn dfl_method(&mut self) {}
153 struct Struct0<T = ()>;
154 struct Struct1<T>(u8);
169 inner attrs: Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr"))] }, input: None }]) }
172 Import { path: ModPath { kind: Plain, segments: [Name(Text("a"))] }, alias: None, visibility: Module(ModPath { kind: Super(0), segments: [] }), is_glob: false, is_prelude: false, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UseItem>(0) }
173 Import { path: ModPath { kind: Plain, segments: [Name(Text("b"))] }, alias: None, visibility: Module(ModPath { kind: Super(0), segments: [] }), is_glob: true, is_prelude: false, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UseItem>(0) }
174 ExternCrate { path: ModPath { kind: Plain, segments: [Name(Text("krate"))] }, alias: None, visibility: Module(ModPath { kind: Super(0), segments: [] }), is_macro_use: false, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::ExternCrateItem>(1) }
175 Trait { name: Name(Text("Tr")), visibility: Module(ModPath { kind: Super(0), segments: [] }), generic_params: GenericParams { types: Arena { len: 2, data: [TypeParamData { name: Some(Name(Text("Self"))), default: None, provenance: TraitSelf }, TypeParamData { name: Some(Name(Text("U"))), default: None, provenance: TypeParamList }] }, where_predicates: [] }, auto: false, items: [TypeAlias(Idx::<TypeAlias>(0)), Const(Idx::<Const>(0)), Function(Idx::<Function>(0)), Function(Idx::<Function>(1))], ast_id: FileAstId::<ra_syntax::ast::generated::nodes::TraitDef>(2) }
176 Struct { name: Name(Text("Struct0")), attrs: Attrs { entries: None }, visibility: Module(ModPath { kind: Super(0), segments: [] }), generic_params: GenericParams { types: Arena { len: 1, data: [TypeParamData { name: Some(Name(Text("T"))), default: Some(Tuple([])), provenance: TypeParamList }] }, where_predicates: [] }, fields: Unit, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(3), kind: Unit }
177 Struct { name: Name(Text("Struct1")), attrs: Attrs { entries: None }, visibility: Module(ModPath { kind: Super(0), segments: [] }), generic_params: GenericParams { types: Arena { len: 1, data: [TypeParamData { name: Some(Name(Text("T"))), default: None, provenance: TypeParamList }] }, where_predicates: [] }, fields: Tuple(Idx::<Field>(0)..Idx::<Field>(1)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(4), kind: Tuple }
178 Struct { name: Name(Text("Struct2")), attrs: Attrs { entries: None }, visibility: Module(ModPath { kind: Super(0), segments: [] }), generic_params: GenericParams { types: Arena { len: 1, data: [TypeParamData { name: Some(Name(Text("T"))), default: None, provenance: TypeParamList }] }, where_predicates: [] }, fields: Record(Idx::<Field>(1)..Idx::<Field>(2)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(5), kind: Record }
179 Enum { name: Name(Text("En")), attrs: Attrs { entries: None }, visibility: Module(ModPath { kind: Super(0), segments: [] }), generic_params: GenericParams { types: Arena { len: 0, data: [] }, where_predicates: [] }, variants: Idx::<Variant>(0)..Idx::<Variant>(1), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::EnumDef>(6) }
180 Union { name: Name(Text("Un")), attrs: Attrs { entries: None }, visibility: Module(ModPath { kind: Super(0), segments: [] }), generic_params: GenericParams { types: Arena { len: 0, data: [] }, where_predicates: [] }, fields: Record(Idx::<Field>(3)..Idx::<Field>(4)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UnionDef>(7) }
185 fn simple_inner_items() {
186 let tree = print_item_tree(
188 impl<T:A> D for Response<T> {
199 assert_snapshot!(tree, @r###"
200 inner attrs: Attrs { entries: None }
203 Impl { generic_params: GenericParams { types: Arena { len: 1, data: [TypeParamData { name: Some(Name(Text("T"))), default: None, provenance: TypeParamList }] }, where_predicates: [WherePredicate { target: TypeRef(Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("T"))] }, generic_args: [None] })), bound: Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("A"))] }, generic_args: [None] }) }] }, target_trait: Some(Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("D"))] }, generic_args: [None] })), target_type: Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("Response"))] }, generic_args: [Some(GenericArgs { args: [Type(Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("T"))] }, generic_args: [None] }))], has_self_type: false, bindings: [] })] }), is_negative: false, items: [Function(Idx::<Function>(1))], ast_id: FileAstId::<ra_syntax::ast::generated::nodes::ImplDef>(0) }
206 FileAstId::<ra_syntax::ast::generated::nodes::ModuleItem>(2):
207 - Function { name: Name(Text("end")), attrs: Attrs { entries: None }, visibility: Module(ModPath { kind: Super(0), segments: [] }), generic_params: GenericParams { types: Arena { len: 1, data: [TypeParamData { name: Some(Name(Text("W"))), default: None, provenance: TypeParamList }] }, where_predicates: [WherePredicate { target: TypeRef(Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("W"))] }, generic_args: [None] })), bound: Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("Write"))] }, generic_args: [None] }) }] }, has_self_param: false, is_unsafe: false, params: [], ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(2) }
212 fn cursed_inner_items() {
215 struct S<T: Trait = [u8; { fn f() {} 0 }]>(T);
219 t: [(); { trait Inner {} 0 }],
222 Var2([u16; { enum Inner {} 0 }]),
225 type Ty = [En; { struct Inner; 0 }];
230 struct InnerStruct {}
231 impl InnerTrait for InnerStruct {}
239 fn assoc_item_macros() {
240 let tree = print_item_tree(
248 assert_snapshot!(tree, @r###"
249 inner attrs: Attrs { entries: None }
252 Impl { generic_params: GenericParams { types: Arena { len: 0, data: [] }, where_predicates: [] }, target_trait: None, target_type: Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("S"))] }, generic_args: [None] }), is_negative: false, items: [MacroCall(Idx::<MacroCall>(0))], ast_id: FileAstId::<ra_syntax::ast::generated::nodes::ImplDef>(0) }