]> git.lizzy.rs Git - rust.git/blob - crates/ra_hir_def/src/item_tree/tests.rs
Make remaining item data queries use item tree
[rust.git] / crates / ra_hir_def / src / item_tree / tests.rs
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;
8 use std::sync::Arc;
9 use stdx::format_to;
10
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());
16
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(),
31             ModItem::Mod(it) => {
32                 if let ModKind::Inline { items } = &tree[it].kind {
33                     worklist.extend(items);
34                 }
35                 tree.source(&db, it).into()
36             }
37             ModItem::Trait(it) => {
38                 worklist.extend(tree[it].items.iter().map(|item| ModItem::from(*item)));
39                 tree.source(&db, it).into()
40             }
41             ModItem::Impl(it) => {
42                 worklist.extend(tree[it].items.iter().map(|item| ModItem::from(*item)));
43                 tree.source(&db, it).into()
44             }
45             ModItem::MacroCall(_) => continue,
46         };
47
48         outer_items.insert(node);
49     }
50
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) {
55             continue;
56         }
57
58         let ast_id = ast_id_map.ast_id(&item);
59         assert!(!tree.inner_items(ast_id).is_empty());
60     }
61 }
62
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())
66 }
67
68 fn print_item_tree(ra_fixture: &str) -> String {
69     let tree = item_tree(ra_fixture);
70     let mut out = String::new();
71
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");
77     }
78
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);
83             for inner in items {
84                 format_to!(out, "- ");
85                 fmt_mod_item(&mut out, &tree, *inner);
86                 format_to!(out, "\n");
87             }
88         }
89     }
90
91     out
92 }
93
94 fn fmt_mod_item(out: &mut String, tree: &ItemTree, item: ModItem) {
95     match item {
96         ModItem::ExternCrate(it) => {
97             format_to!(out, "{:?}", tree[it]);
98         }
99         ModItem::Import(it) => {
100             format_to!(out, "{:?}", tree[it]);
101         }
102         ModItem::Function(it) => {
103             format_to!(out, "{:?}", tree[it]);
104         }
105         ModItem::Struct(it) => {
106             format_to!(out, "{:?}", tree[it]);
107         }
108         ModItem::Union(it) => {
109             format_to!(out, "{:?}", tree[it]);
110         }
111         ModItem::Enum(it) => {
112             format_to!(out, "{:?}", tree[it]);
113         }
114         ModItem::Const(it) => {
115             format_to!(out, "{:?}", tree[it]);
116         }
117         ModItem::Static(it) => {
118             format_to!(out, "{:?}", tree[it]);
119         }
120         ModItem::Trait(it) => {
121             format_to!(out, "{:?}", tree[it]);
122         }
123         ModItem::Impl(it) => {
124             format_to!(out, "{:?}", tree[it]);
125         }
126         ModItem::TypeAlias(it) => {
127             format_to!(out, "{:?}", tree[it]);
128         }
129         ModItem::Mod(it) => {
130             format_to!(out, "{:?}", tree[it]);
131         }
132         ModItem::MacroCall(it) => {
133             format_to!(out, "{:?}", tree[it]);
134         }
135     }
136 }
137
138 #[test]
139 fn smoke() {
140     assert_snapshot!(print_item_tree(r"
141         #![attr]
142
143         use {a, b::*};
144         extern crate krate;
145
146         trait Tr<U> {
147             type AssocTy: Tr<()>;
148             const CONST: u8;
149             fn method(&self);
150             fn dfl_method(&mut self) {}
151         }
152
153         struct Struct0<T = ()>;
154         struct Struct1<T>(u8);
155         struct Struct2<T> {
156             fld: (T, ),
157         }
158
159         enum En {
160             Variant {
161                 field: u8,
162             },
163         }
164
165         union Un {
166             fld: u16,
167         }
168     "), @r###"
169 inner attrs: Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr"))] }, input: None }]) }
170
171 top-level items:
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) }
181     "###);
182 }
183
184 #[test]
185 fn simple_inner_items() {
186     let tree = print_item_tree(
187         r"
188         impl<T:A> D for Response<T> {
189             fn foo() {
190                 end();
191                 fn end<W: Write>() {
192                     let _x: T = loop {};
193                 }
194             }
195         }
196     ",
197     );
198
199     assert_snapshot!(tree, @r###"
200 inner attrs: Attrs { entries: None }
201
202 top-level items:
203 Impl { generic_params: GenericParams { types: Arena { len: 0, data: [] }, where_predicates: [] }, 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) }
204
205 inner items:
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) }
208     "###);
209 }
210
211 #[test]
212 fn cursed_inner_items() {
213     test_inner_items(
214         r"
215         struct S<T: Trait = [u8; { fn f() {} 0 }]>(T);
216
217         enum En {
218             Var1 {
219                 t: [(); { trait Inner {} 0 }],
220             },
221
222             Var2([u16; { enum Inner {} 0 }]),
223         }
224
225         type Ty = [En; { struct Inner; 0 }];
226
227         impl En {
228             fn assoc() {
229                 trait InnerTrait {}
230                 struct InnerStruct {}
231                 impl InnerTrait for InnerStruct {}
232             }
233         }
234     ",
235     );
236 }
237
238 #[test]
239 fn assoc_item_macros() {
240     let tree = print_item_tree(
241         r"
242         impl S {
243             items!();
244         }
245     ",
246     );
247
248     assert_snapshot!(tree, @r###"
249 inner attrs: Attrs { entries: None }
250
251 top-level items:
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) }
253     "###);
254 }