aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_def/src/item_tree
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_def/src/item_tree')
-rw-r--r--crates/ra_hir_def/src/item_tree/lower.rs708
-rw-r--r--crates/ra_hir_def/src/item_tree/tests.rs439
2 files changed, 1147 insertions, 0 deletions
diff --git a/crates/ra_hir_def/src/item_tree/lower.rs b/crates/ra_hir_def/src/item_tree/lower.rs
new file mode 100644
index 000000000..f79b8fca3
--- /dev/null
+++ b/crates/ra_hir_def/src/item_tree/lower.rs
@@ -0,0 +1,708 @@
1//! AST -> `ItemTree` lowering code.
2
3use super::*;
4use crate::{
5 attr::Attrs,
6 generics::{GenericParams, TypeParamData, TypeParamProvenance},
7};
8use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, HirFileId};
9use ra_arena::map::ArenaMap;
10use ra_syntax::{
11 ast::{self, ModuleItemOwner},
12 SyntaxNode,
13};
14use smallvec::SmallVec;
15use std::{collections::hash_map::Entry, mem, sync::Arc};
16
17fn id<N: ItemTreeNode>(index: Idx<N>) -> FileItemTreeId<N> {
18 FileItemTreeId { index, _p: PhantomData }
19}
20
21struct ModItems(SmallVec<[ModItem; 1]>);
22
23impl<T> From<T> for ModItems
24where
25 T: Into<ModItem>,
26{
27 fn from(t: T) -> Self {
28 ModItems(SmallVec::from_buf([t.into(); 1]))
29 }
30}
31
32pub(super) struct Ctx {
33 tree: ItemTree,
34 hygiene: Hygiene,
35 file: HirFileId,
36 source_ast_id_map: Arc<AstIdMap>,
37 body_ctx: crate::body::LowerCtx,
38 inner_items: Vec<ModItem>,
39 forced_visibility: Option<RawVisibilityId>,
40}
41
42impl Ctx {
43 pub(super) fn new(db: &dyn DefDatabase, hygiene: Hygiene, file: HirFileId) -> Self {
44 Self {
45 tree: ItemTree::empty(),
46 hygiene,
47 file,
48 source_ast_id_map: db.ast_id_map(file),
49 body_ctx: crate::body::LowerCtx::new(db, file),
50 inner_items: Vec::new(),
51 forced_visibility: None,
52 }
53 }
54
55 pub(super) fn lower_module_items(mut self, item_owner: &dyn ModuleItemOwner) -> ItemTree {
56 self.tree.top_level = item_owner
57 .items()
58 .flat_map(|item| self.lower_mod_item(&item, false))
59 .flat_map(|items| items.0)
60 .collect();
61 self.tree
62 }
63
64 pub(super) fn lower_inner_items(mut self, within: &SyntaxNode) -> ItemTree {
65 self.collect_inner_items(within);
66 self.tree
67 }
68
69 fn data(&mut self) -> &mut ItemTreeData {
70 self.tree.data_mut()
71 }
72
73 fn lower_mod_item(&mut self, item: &ast::ModuleItem, inner: bool) -> Option<ModItems> {
74 assert!(inner || self.inner_items.is_empty());
75
76 // Collect inner items for 1-to-1-lowered items.
77 match item {
78 ast::ModuleItem::StructDef(_)
79 | ast::ModuleItem::UnionDef(_)
80 | ast::ModuleItem::EnumDef(_)
81 | ast::ModuleItem::FnDef(_)
82 | ast::ModuleItem::TypeAliasDef(_)
83 | ast::ModuleItem::ConstDef(_)
84 | ast::ModuleItem::StaticDef(_)
85 | ast::ModuleItem::MacroCall(_) => {
86 // Skip this if we're already collecting inner items. We'll descend into all nodes
87 // already.
88 if !inner {
89 self.collect_inner_items(item.syntax());
90 }
91 }
92
93 // These are handled in their respective `lower_X` method (since we can't just blindly
94 // walk them).
95 ast::ModuleItem::TraitDef(_)
96 | ast::ModuleItem::ImplDef(_)
97 | ast::ModuleItem::ExternBlock(_) => {}
98
99 // These don't have inner items.
100 ast::ModuleItem::Module(_)
101 | ast::ModuleItem::ExternCrateItem(_)
102 | ast::ModuleItem::UseItem(_) => {}
103 };
104
105 let attrs = Attrs::new(item, &self.hygiene);
106 let items = match item {
107 ast::ModuleItem::StructDef(ast) => self.lower_struct(ast).map(Into::into),
108 ast::ModuleItem::UnionDef(ast) => self.lower_union(ast).map(Into::into),
109 ast::ModuleItem::EnumDef(ast) => self.lower_enum(ast).map(Into::into),
110 ast::ModuleItem::FnDef(ast) => self.lower_function(ast).map(Into::into),
111 ast::ModuleItem::TypeAliasDef(ast) => self.lower_type_alias(ast).map(Into::into),
112 ast::ModuleItem::StaticDef(ast) => self.lower_static(ast).map(Into::into),
113 ast::ModuleItem::ConstDef(ast) => Some(self.lower_const(ast).into()),
114 ast::ModuleItem::Module(ast) => self.lower_module(ast).map(Into::into),
115 ast::ModuleItem::TraitDef(ast) => self.lower_trait(ast).map(Into::into),
116 ast::ModuleItem::ImplDef(ast) => self.lower_impl(ast).map(Into::into),
117 ast::ModuleItem::UseItem(ast) => Some(ModItems(
118 self.lower_use(ast).into_iter().map(Into::into).collect::<SmallVec<_>>(),
119 )),
120 ast::ModuleItem::ExternCrateItem(ast) => self.lower_extern_crate(ast).map(Into::into),
121 ast::ModuleItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
122 ast::ModuleItem::ExternBlock(ast) => {
123 Some(ModItems(self.lower_extern_block(ast).into_iter().collect::<SmallVec<_>>()))
124 }
125 };
126
127 if !attrs.is_empty() {
128 for item in items.iter().flat_map(|items| &items.0) {
129 self.add_attrs((*item).into(), attrs.clone());
130 }
131 }
132
133 items
134 }
135
136 fn add_attrs(&mut self, item: AttrOwner, attrs: Attrs) {
137 match self.tree.attrs.entry(item) {
138 Entry::Occupied(mut entry) => {
139 *entry.get_mut() = entry.get().merge(attrs);
140 }
141 Entry::Vacant(entry) => {
142 entry.insert(attrs);
143 }
144 }
145 }
146
147 fn collect_inner_items(&mut self, container: &SyntaxNode) {
148 let forced_vis = self.forced_visibility.take();
149 let mut inner_items = mem::take(&mut self.tree.inner_items);
150 inner_items.extend(
151 container.descendants().skip(1).filter_map(ast::ModuleItem::cast).filter_map(|item| {
152 let ast_id = self.source_ast_id_map.ast_id(&item);
153 Some((ast_id, self.lower_mod_item(&item, true)?.0))
154 }),
155 );
156 self.tree.inner_items = inner_items;
157 self.forced_visibility = forced_vis;
158 }
159
160 fn lower_assoc_item(&mut self, item: &ast::ModuleItem) -> Option<AssocItem> {
161 match item {
162 ast::ModuleItem::FnDef(ast) => self.lower_function(ast).map(Into::into),
163 ast::ModuleItem::TypeAliasDef(ast) => self.lower_type_alias(ast).map(Into::into),
164 ast::ModuleItem::ConstDef(ast) => Some(self.lower_const(ast).into()),
165 ast::ModuleItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
166 _ => None,
167 }
168 }
169
170 fn lower_struct(&mut self, strukt: &ast::StructDef) -> Option<FileItemTreeId<Struct>> {
171 let visibility = self.lower_visibility(strukt);
172 let name = strukt.name()?.as_name();
173 let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
174 let fields = self.lower_fields(&strukt.kind());
175 let ast_id = self.source_ast_id_map.ast_id(strukt);
176 let kind = match strukt.kind() {
177 ast::StructKind::Record(_) => StructDefKind::Record,
178 ast::StructKind::Tuple(_) => StructDefKind::Tuple,
179 ast::StructKind::Unit => StructDefKind::Unit,
180 };
181 let res = Struct { name, visibility, generic_params, fields, ast_id, kind };
182 Some(id(self.data().structs.alloc(res)))
183 }
184
185 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
186 match strukt_kind {
187 ast::StructKind::Record(it) => {
188 let range = self.lower_record_fields(it);
189 Fields::Record(range)
190 }
191 ast::StructKind::Tuple(it) => {
192 let range = self.lower_tuple_fields(it);
193 Fields::Tuple(range)
194 }
195 ast::StructKind::Unit => Fields::Unit,
196 }
197 }
198
199 fn lower_record_fields(&mut self, fields: &ast::RecordFieldDefList) -> IdRange<Field> {
200 let start = self.next_field_idx();
201 for field in fields.fields() {
202 if let Some(data) = self.lower_record_field(&field) {
203 let idx = self.data().fields.alloc(data);
204 self.add_attrs(idx.into(), Attrs::new(&field, &self.hygiene));
205 }
206 }
207 let end = self.next_field_idx();
208 IdRange::new(start..end)
209 }
210
211 fn lower_record_field(&mut self, field: &ast::RecordFieldDef) -> Option<Field> {
212 let name = field.name()?.as_name();
213 let visibility = self.lower_visibility(field);
214 let type_ref = self.lower_type_ref_opt(field.ascribed_type());
215 let res = Field { name, type_ref, visibility };
216 Some(res)
217 }
218
219 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldDefList) -> IdRange<Field> {
220 let start = self.next_field_idx();
221 for (i, field) in fields.fields().enumerate() {
222 let data = self.lower_tuple_field(i, &field);
223 let idx = self.data().fields.alloc(data);
224 self.add_attrs(idx.into(), Attrs::new(&field, &self.hygiene));
225 }
226 let end = self.next_field_idx();
227 IdRange::new(start..end)
228 }
229
230 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleFieldDef) -> Field {
231 let name = Name::new_tuple_field(idx);
232 let visibility = self.lower_visibility(field);
233 let type_ref = self.lower_type_ref_opt(field.type_ref());
234 let res = Field { name, type_ref, visibility };
235 res
236 }
237
238 fn lower_union(&mut self, union: &ast::UnionDef) -> Option<FileItemTreeId<Union>> {
239 let visibility = self.lower_visibility(union);
240 let name = union.name()?.as_name();
241 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
242 let fields = match union.record_field_def_list() {
243 Some(record_field_def_list) => {
244 self.lower_fields(&StructKind::Record(record_field_def_list))
245 }
246 None => Fields::Record(IdRange::new(self.next_field_idx()..self.next_field_idx())),
247 };
248 let ast_id = self.source_ast_id_map.ast_id(union);
249 let res = Union { name, visibility, generic_params, fields, ast_id };
250 Some(id(self.data().unions.alloc(res)))
251 }
252
253 fn lower_enum(&mut self, enum_: &ast::EnumDef) -> Option<FileItemTreeId<Enum>> {
254 let visibility = self.lower_visibility(enum_);
255 let name = enum_.name()?.as_name();
256 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
257 let variants = match &enum_.variant_list() {
258 Some(variant_list) => self.lower_variants(variant_list),
259 None => IdRange::new(self.next_variant_idx()..self.next_variant_idx()),
260 };
261 let ast_id = self.source_ast_id_map.ast_id(enum_);
262 let res = Enum { name, visibility, generic_params, variants, ast_id };
263 Some(id(self.data().enums.alloc(res)))
264 }
265
266 fn lower_variants(&mut self, variants: &ast::EnumVariantList) -> IdRange<Variant> {
267 let start = self.next_variant_idx();
268 for variant in variants.variants() {
269 if let Some(data) = self.lower_variant(&variant) {
270 let idx = self.data().variants.alloc(data);
271 self.add_attrs(idx.into(), Attrs::new(&variant, &self.hygiene));
272 }
273 }
274 let end = self.next_variant_idx();
275 IdRange::new(start..end)
276 }
277
278 fn lower_variant(&mut self, variant: &ast::EnumVariant) -> Option<Variant> {
279 let name = variant.name()?.as_name();
280 let fields = self.lower_fields(&variant.kind());
281 let res = Variant { name, fields };
282 Some(res)
283 }
284
285 fn lower_function(&mut self, func: &ast::FnDef) -> Option<FileItemTreeId<Function>> {
286 let visibility = self.lower_visibility(func);
287 let name = func.name()?.as_name();
288
289 let mut params = Vec::new();
290 let mut has_self_param = false;
291 if let Some(param_list) = func.param_list() {
292 if let Some(self_param) = param_list.self_param() {
293 let self_type = match self_param.ascribed_type() {
294 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
295 None => {
296 let self_type = TypeRef::Path(name![Self].into());
297 match self_param.kind() {
298 ast::SelfParamKind::Owned => self_type,
299 ast::SelfParamKind::Ref => {
300 TypeRef::Reference(Box::new(self_type), Mutability::Shared)
301 }
302 ast::SelfParamKind::MutRef => {
303 TypeRef::Reference(Box::new(self_type), Mutability::Mut)
304 }
305 }
306 }
307 };
308 params.push(self_type);
309 has_self_param = true;
310 }
311 for param in param_list.params() {
312 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ascribed_type());
313 params.push(type_ref);
314 }
315 }
316
317 let mut is_varargs = false;
318 if let Some(params) = func.param_list() {
319 if let Some(last) = params.params().last() {
320 is_varargs = last.dotdotdot_token().is_some();
321 }
322 }
323
324 let ret_type = match func.ret_type().and_then(|rt| rt.type_ref()) {
325 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
326 _ => TypeRef::unit(),
327 };
328
329 let ret_type = if func.async_token().is_some() {
330 let future_impl = desugar_future_path(ret_type);
331 let ty_bound = TypeBound::Path(future_impl);
332 TypeRef::ImplTrait(vec![ty_bound])
333 } else {
334 ret_type
335 };
336
337 let ast_id = self.source_ast_id_map.ast_id(func);
338 let mut res = Function {
339 name,
340 visibility,
341 generic_params: GenericParamsId::EMPTY,
342 has_self_param,
343 is_unsafe: func.unsafe_token().is_some(),
344 params: params.into_boxed_slice(),
345 is_varargs,
346 ret_type,
347 ast_id,
348 };
349 res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
350
351 Some(id(self.data().functions.alloc(res)))
352 }
353
354 fn lower_type_alias(
355 &mut self,
356 type_alias: &ast::TypeAliasDef,
357 ) -> Option<FileItemTreeId<TypeAlias>> {
358 let name = type_alias.name()?.as_name();
359 let type_ref = type_alias.type_ref().map(|it| self.lower_type_ref(&it));
360 let visibility = self.lower_visibility(type_alias);
361 let bounds = self.lower_type_bounds(type_alias);
362 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
363 let ast_id = self.source_ast_id_map.ast_id(type_alias);
364 let res = TypeAlias {
365 name,
366 visibility,
367 bounds: bounds.into_boxed_slice(),
368 generic_params,
369 type_ref,
370 ast_id,
371 };
372 Some(id(self.data().type_aliases.alloc(res)))
373 }
374
375 fn lower_static(&mut self, static_: &ast::StaticDef) -> Option<FileItemTreeId<Static>> {
376 let name = static_.name()?.as_name();
377 let type_ref = self.lower_type_ref_opt(static_.ascribed_type());
378 let visibility = self.lower_visibility(static_);
379 let mutable = static_.mut_token().is_some();
380 let ast_id = self.source_ast_id_map.ast_id(static_);
381 let res = Static { name, visibility, mutable, type_ref, ast_id };
382 Some(id(self.data().statics.alloc(res)))
383 }
384
385 fn lower_const(&mut self, konst: &ast::ConstDef) -> FileItemTreeId<Const> {
386 let name = konst.name().map(|it| it.as_name());
387 let type_ref = self.lower_type_ref_opt(konst.ascribed_type());
388 let visibility = self.lower_visibility(konst);
389 let ast_id = self.source_ast_id_map.ast_id(konst);
390 let res = Const { name, visibility, type_ref, ast_id };
391 id(self.data().consts.alloc(res))
392 }
393
394 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
395 let name = module.name()?.as_name();
396 let visibility = self.lower_visibility(module);
397 let kind = if module.semicolon_token().is_some() {
398 ModKind::Outline {}
399 } else {
400 ModKind::Inline {
401 items: module
402 .item_list()
403 .map(|list| {
404 list.items()
405 .flat_map(|item| self.lower_mod_item(&item, false))
406 .flat_map(|items| items.0)
407 .collect()
408 })
409 .unwrap_or_else(|| {
410 mark::hit!(name_res_works_for_broken_modules);
411 Box::new([]) as Box<[_]>
412 }),
413 }
414 };
415 let ast_id = self.source_ast_id_map.ast_id(module);
416 let res = Mod { name, visibility, kind, ast_id };
417 Some(id(self.data().mods.alloc(res)))
418 }
419
420 fn lower_trait(&mut self, trait_def: &ast::TraitDef) -> Option<FileItemTreeId<Trait>> {
421 let name = trait_def.name()?.as_name();
422 let visibility = self.lower_visibility(trait_def);
423 let generic_params =
424 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
425 let auto = trait_def.auto_token().is_some();
426 let items = trait_def.item_list().map(|list| {
427 self.with_inherited_visibility(visibility, |this| {
428 list.items()
429 .filter_map(|item| {
430 let attrs = Attrs::new(&item, &this.hygiene);
431 this.collect_inner_items(item.syntax());
432 this.lower_assoc_item(&item).map(|item| {
433 this.add_attrs(ModItem::from(item).into(), attrs);
434 item
435 })
436 })
437 .collect()
438 })
439 });
440 let ast_id = self.source_ast_id_map.ast_id(trait_def);
441 let res = Trait {
442 name,
443 visibility,
444 generic_params,
445 auto,
446 items: items.unwrap_or_default(),
447 ast_id,
448 };
449 Some(id(self.data().traits.alloc(res)))
450 }
451
452 fn lower_impl(&mut self, impl_def: &ast::ImplDef) -> Option<FileItemTreeId<Impl>> {
453 let generic_params =
454 self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
455 let target_trait = impl_def.target_trait().map(|tr| self.lower_type_ref(&tr));
456 let target_type = self.lower_type_ref(&impl_def.target_type()?);
457 let is_negative = impl_def.excl_token().is_some();
458
459 // We cannot use `assoc_items()` here as that does not include macro calls.
460 let items = impl_def
461 .item_list()
462 .into_iter()
463 .flat_map(|it| it.items())
464 .filter_map(|item| {
465 self.collect_inner_items(item.syntax());
466 let assoc = self.lower_assoc_item(&item)?;
467 let attrs = Attrs::new(&item, &self.hygiene);
468 self.add_attrs(ModItem::from(assoc).into(), attrs);
469 Some(assoc)
470 })
471 .collect();
472 let ast_id = self.source_ast_id_map.ast_id(impl_def);
473 let res = Impl { generic_params, target_trait, target_type, is_negative, items, ast_id };
474 Some(id(self.data().impls.alloc(res)))
475 }
476
477 fn lower_use(&mut self, use_item: &ast::UseItem) -> Vec<FileItemTreeId<Import>> {
478 // FIXME: cfg_attr
479 let is_prelude = use_item.has_atom_attr("prelude_import");
480 let visibility = self.lower_visibility(use_item);
481 let ast_id = self.source_ast_id_map.ast_id(use_item);
482
483 // Every use item can expand to many `Import`s.
484 let mut imports = Vec::new();
485 let tree = self.tree.data_mut();
486 ModPath::expand_use_item(
487 InFile::new(self.file, use_item.clone()),
488 &self.hygiene,
489 |path, _tree, is_glob, alias| {
490 imports.push(id(tree.imports.alloc(Import {
491 path,
492 alias,
493 visibility,
494 is_glob,
495 is_prelude,
496 ast_id,
497 })));
498 },
499 );
500
501 imports
502 }
503
504 fn lower_extern_crate(
505 &mut self,
506 extern_crate: &ast::ExternCrateItem,
507 ) -> Option<FileItemTreeId<ExternCrate>> {
508 let path = ModPath::from_name_ref(&extern_crate.name_ref()?);
509 let alias = extern_crate.alias().map(|a| {
510 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
511 });
512 let visibility = self.lower_visibility(extern_crate);
513 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
514 // FIXME: cfg_attr
515 let is_macro_use = extern_crate.has_atom_attr("macro_use");
516
517 let res = ExternCrate { path, alias, visibility, is_macro_use, ast_id };
518 Some(id(self.data().extern_crates.alloc(res)))
519 }
520
521 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
522 let name = m.name().map(|it| it.as_name());
523 let attrs = Attrs::new(m, &self.hygiene);
524 let path = ModPath::from_src(m.path()?, &self.hygiene)?;
525
526 let ast_id = self.source_ast_id_map.ast_id(m);
527
528 // FIXME: cfg_attr
529 let export_attr = attrs.by_key("macro_export");
530
531 let is_export = export_attr.exists();
532 let is_local_inner = if is_export {
533 export_attr.tt_values().map(|it| &it.token_trees).flatten().any(|it| match it {
534 tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
535 ident.text.contains("local_inner_macros")
536 }
537 _ => false,
538 })
539 } else {
540 false
541 };
542
543 let is_builtin = attrs.by_key("rustc_builtin_macro").exists();
544 let res = MacroCall { name, path, is_export, is_builtin, is_local_inner, ast_id };
545 Some(id(self.data().macro_calls.alloc(res)))
546 }
547
548 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> Vec<ModItem> {
549 block.extern_item_list().map_or(Vec::new(), |list| {
550 list.extern_items()
551 .filter_map(|item| {
552 self.collect_inner_items(item.syntax());
553 let attrs = Attrs::new(&item, &self.hygiene);
554 let id: ModItem = match item {
555 ast::ExternItem::FnDef(ast) => {
556 let func = self.lower_function(&ast)?;
557 self.data().functions[func.index].is_unsafe = true;
558 func.into()
559 }
560 ast::ExternItem::StaticDef(ast) => {
561 let statik = self.lower_static(&ast)?;
562 statik.into()
563 }
564 };
565 self.add_attrs(id.into(), attrs);
566 Some(id)
567 })
568 .collect()
569 })
570 }
571
572 /// Lowers generics defined on `node` and collects inner items defined within.
573 fn lower_generic_params_and_inner_items(
574 &mut self,
575 owner: GenericsOwner<'_>,
576 node: &impl ast::TypeParamsOwner,
577 ) -> GenericParamsId {
578 // Generics are part of item headers and may contain inner items we need to collect.
579 if let Some(params) = node.type_param_list() {
580 self.collect_inner_items(params.syntax());
581 }
582 if let Some(clause) = node.where_clause() {
583 self.collect_inner_items(clause.syntax());
584 }
585
586 self.lower_generic_params(owner, node)
587 }
588
589 fn lower_generic_params(
590 &mut self,
591 owner: GenericsOwner<'_>,
592 node: &impl ast::TypeParamsOwner,
593 ) -> GenericParamsId {
594 let mut sm = &mut ArenaMap::default();
595 let mut generics = GenericParams::default();
596 match owner {
597 GenericsOwner::Function(func) => {
598 generics.fill(&self.body_ctx, sm, node);
599 // lower `impl Trait` in arguments
600 for param in &*func.params {
601 generics.fill_implicit_impl_trait_args(param);
602 }
603 }
604 GenericsOwner::Struct
605 | GenericsOwner::Enum
606 | GenericsOwner::Union
607 | GenericsOwner::TypeAlias => {
608 generics.fill(&self.body_ctx, sm, node);
609 }
610 GenericsOwner::Trait(trait_def) => {
611 // traits get the Self type as an implicit first type parameter
612 let self_param_id = generics.types.alloc(TypeParamData {
613 name: Some(name![Self]),
614 default: None,
615 provenance: TypeParamProvenance::TraitSelf,
616 });
617 sm.insert(self_param_id, Either::Left(trait_def.clone()));
618 // add super traits as bounds on Self
619 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
620 let self_param = TypeRef::Path(name![Self].into());
621 generics.fill_bounds(&self.body_ctx, trait_def, self_param);
622
623 generics.fill(&self.body_ctx, &mut sm, node);
624 }
625 GenericsOwner::Impl => {
626 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
627 // type-parameter, but rather is a type-alias for impl's target
628 // type, so this is handled by the resolver.
629 generics.fill(&self.body_ctx, &mut sm, node);
630 }
631 }
632
633 self.data().generics.alloc(generics)
634 }
635
636 fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<TypeBound> {
637 match node.type_bound_list() {
638 Some(bound_list) => {
639 bound_list.bounds().map(|it| TypeBound::from_ast(&self.body_ctx, it)).collect()
640 }
641 None => Vec::new(),
642 }
643 }
644
645 fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
646 let vis = match self.forced_visibility {
647 Some(vis) => return vis,
648 None => RawVisibility::from_ast_with_hygiene(item.visibility(), &self.hygiene),
649 };
650
651 self.data().vis.alloc(vis)
652 }
653
654 fn lower_type_ref(&self, type_ref: &ast::TypeRef) -> TypeRef {
655 TypeRef::from_ast(&self.body_ctx, type_ref.clone())
656 }
657 fn lower_type_ref_opt(&self, type_ref: Option<ast::TypeRef>) -> TypeRef {
658 type_ref.map(|ty| self.lower_type_ref(&ty)).unwrap_or(TypeRef::Error)
659 }
660
661 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
662 fn with_inherited_visibility<R>(
663 &mut self,
664 vis: RawVisibilityId,
665 f: impl FnOnce(&mut Self) -> R,
666 ) -> R {
667 let old = mem::replace(&mut self.forced_visibility, Some(vis));
668 let res = f(self);
669 self.forced_visibility = old;
670 res
671 }
672
673 fn next_field_idx(&self) -> Idx<Field> {
674 Idx::from_raw(RawId::from(
675 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
676 ))
677 }
678 fn next_variant_idx(&self) -> Idx<Variant> {
679 Idx::from_raw(RawId::from(
680 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
681 ))
682 }
683}
684
685fn desugar_future_path(orig: TypeRef) -> Path {
686 let path = path![core::future::Future];
687 let mut generic_args: Vec<_> = std::iter::repeat(None).take(path.segments.len() - 1).collect();
688 let mut last = GenericArgs::empty();
689 let binding =
690 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
691 last.bindings.push(binding);
692 generic_args.push(Some(Arc::new(last)));
693
694 Path::from_known_path(path, generic_args)
695}
696
697enum GenericsOwner<'a> {
698 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
699 /// position.
700 Function(&'a Function),
701 Struct,
702 Enum,
703 Union,
704 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
705 Trait(&'a ast::TraitDef),
706 TypeAlias,
707 Impl,
708}
diff --git a/crates/ra_hir_def/src/item_tree/tests.rs b/crates/ra_hir_def/src/item_tree/tests.rs
new file mode 100644
index 000000000..f26982985
--- /dev/null
+++ b/crates/ra_hir_def/src/item_tree/tests.rs
@@ -0,0 +1,439 @@
1use expect::{expect, Expect};
2use hir_expand::{db::AstDatabase, HirFileId, InFile};
3use ra_db::fixture::WithFixture;
4use ra_syntax::{ast, AstNode};
5use rustc_hash::FxHashSet;
6use std::sync::Arc;
7use stdx::format_to;
8
9use crate::{db::DefDatabase, test_db::TestDB};
10
11use super::{ItemTree, ModItem, ModKind};
12
13fn test_inner_items(ra_fixture: &str) {
14 let (db, file_id) = TestDB::with_single_file(ra_fixture);
15 let file_id = HirFileId::from(file_id);
16 let tree = db.item_tree(file_id);
17 let root = db.parse_or_expand(file_id).unwrap();
18 let ast_id_map = db.ast_id_map(file_id);
19
20 // Traverse the item tree and collect all module/impl/trait-level items as AST nodes.
21 let mut outer_items = FxHashSet::default();
22 let mut worklist = tree.top_level_items().to_vec();
23 while let Some(item) = worklist.pop() {
24 let node: ast::ModuleItem = match item {
25 ModItem::Import(it) => tree.source(&db, InFile::new(file_id, it)).into(),
26 ModItem::ExternCrate(it) => tree.source(&db, InFile::new(file_id, it)).into(),
27 ModItem::Function(it) => tree.source(&db, InFile::new(file_id, it)).into(),
28 ModItem::Struct(it) => tree.source(&db, InFile::new(file_id, it)).into(),
29 ModItem::Union(it) => tree.source(&db, InFile::new(file_id, it)).into(),
30 ModItem::Enum(it) => tree.source(&db, InFile::new(file_id, it)).into(),
31 ModItem::Const(it) => tree.source(&db, InFile::new(file_id, it)).into(),
32 ModItem::Static(it) => tree.source(&db, InFile::new(file_id, it)).into(),
33 ModItem::TypeAlias(it) => tree.source(&db, InFile::new(file_id, it)).into(),
34 ModItem::Mod(it) => {
35 if let ModKind::Inline { items } = &tree[it].kind {
36 worklist.extend(&**items);
37 }
38 tree.source(&db, InFile::new(file_id, it)).into()
39 }
40 ModItem::Trait(it) => {
41 worklist.extend(tree[it].items.iter().map(|item| ModItem::from(*item)));
42 tree.source(&db, InFile::new(file_id, it)).into()
43 }
44 ModItem::Impl(it) => {
45 worklist.extend(tree[it].items.iter().map(|item| ModItem::from(*item)));
46 tree.source(&db, InFile::new(file_id, it)).into()
47 }
48 ModItem::MacroCall(_) => continue,
49 };
50
51 outer_items.insert(node);
52 }
53
54 // Now descend the root node and check that all `ast::ModuleItem`s are either recorded above, or
55 // registered as inner items.
56 for item in root.descendants().skip(1).filter_map(ast::ModuleItem::cast) {
57 if outer_items.contains(&item) {
58 continue;
59 }
60
61 let ast_id = ast_id_map.ast_id(&item);
62 assert!(!tree.inner_items(ast_id).is_empty());
63 }
64}
65
66fn item_tree(ra_fixture: &str) -> Arc<ItemTree> {
67 let (db, file_id) = TestDB::with_single_file(ra_fixture);
68 db.item_tree(file_id.into())
69}
70
71fn print_item_tree(ra_fixture: &str) -> String {
72 let tree = item_tree(ra_fixture);
73 let mut out = String::new();
74
75 format_to!(out, "inner attrs: {:?}\n\n", tree.top_level_attrs());
76 format_to!(out, "top-level items:\n");
77 for item in tree.top_level_items() {
78 fmt_mod_item(&mut out, &tree, *item);
79 format_to!(out, "\n");
80 }
81
82 if !tree.inner_items.is_empty() {
83 format_to!(out, "\ninner items:\n\n");
84 for (ast_id, items) in &tree.inner_items {
85 format_to!(out, "for AST {:?}:\n", ast_id);
86 for inner in items {
87 fmt_mod_item(&mut out, &tree, *inner);
88 format_to!(out, "\n\n");
89 }
90 }
91 }
92
93 out
94}
95
96fn fmt_mod_item(out: &mut String, tree: &ItemTree, item: ModItem) {
97 let attrs = tree.attrs(item.into());
98 if !attrs.is_empty() {
99 format_to!(out, "#[{:?}]\n", attrs);
100 }
101
102 let mut children = String::new();
103 match item {
104 ModItem::ExternCrate(it) => {
105 format_to!(out, "{:?}", tree[it]);
106 }
107 ModItem::Import(it) => {
108 format_to!(out, "{:?}", tree[it]);
109 }
110 ModItem::Function(it) => {
111 format_to!(out, "{:?}", tree[it]);
112 }
113 ModItem::Struct(it) => {
114 format_to!(out, "{:?}", tree[it]);
115 }
116 ModItem::Union(it) => {
117 format_to!(out, "{:?}", tree[it]);
118 }
119 ModItem::Enum(it) => {
120 format_to!(out, "{:?}", tree[it]);
121 }
122 ModItem::Const(it) => {
123 format_to!(out, "{:?}", tree[it]);
124 }
125 ModItem::Static(it) => {
126 format_to!(out, "{:?}", tree[it]);
127 }
128 ModItem::Trait(it) => {
129 format_to!(out, "{:?}", tree[it]);
130 for item in &*tree[it].items {
131 fmt_mod_item(&mut children, tree, ModItem::from(*item));
132 format_to!(children, "\n");
133 }
134 }
135 ModItem::Impl(it) => {
136 format_to!(out, "{:?}", tree[it]);
137 for item in &*tree[it].items {
138 fmt_mod_item(&mut children, tree, ModItem::from(*item));
139 format_to!(children, "\n");
140 }
141 }
142 ModItem::TypeAlias(it) => {
143 format_to!(out, "{:?}", tree[it]);
144 }
145 ModItem::Mod(it) => {
146 format_to!(out, "{:?}", tree[it]);
147 match &tree[it].kind {
148 ModKind::Inline { items } => {
149 for item in &**items {
150 fmt_mod_item(&mut children, tree, *item);
151 format_to!(children, "\n");
152 }
153 }
154 ModKind::Outline {} => {}
155 }
156 }
157 ModItem::MacroCall(it) => {
158 format_to!(out, "{:?}", tree[it]);
159 }
160 }
161
162 for line in children.lines() {
163 format_to!(out, "\n> {}", line);
164 }
165}
166
167fn check(ra_fixture: &str, expect: Expect) {
168 let actual = print_item_tree(ra_fixture);
169 expect.assert_eq(&actual);
170}
171
172#[test]
173fn smoke() {
174 check(
175 r"
176 #![attr]
177
178 #[attr_on_use]
179 use {a, b::*};
180
181 #[ext_crate]
182 extern crate krate;
183
184 #[on_trait]
185 trait Tr<U> {
186 #[assoc_ty]
187 type AssocTy: Tr<()>;
188
189 #[assoc_const]
190 const CONST: u8;
191
192 #[assoc_method]
193 fn method(&self);
194
195 #[assoc_dfl_method]
196 fn dfl_method(&mut self) {}
197 }
198
199 #[struct0]
200 struct Struct0<T = ()>;
201
202 #[struct1]
203 struct Struct1<T>(#[struct1fld] u8);
204
205 #[struct2]
206 struct Struct2<T> {
207 #[struct2fld]
208 fld: (T, ),
209 }
210
211 #[en]
212 enum En {
213 #[enum_variant]
214 Variant {
215 #[enum_field]
216 field: u8,
217 },
218 }
219
220 #[un]
221 union Un {
222 #[union_fld]
223 fld: u16,
224 }
225 ",
226 expect![[r##"
227 inner attrs: Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr"))] }, input: None }]) }
228
229 top-level items:
230 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_on_use"))] }, input: None }]) }]
231 Import { path: ModPath { kind: Plain, segments: [Name(Text("a"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_glob: false, is_prelude: false, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UseItem>(0) }
232 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_on_use"))] }, input: None }]) }]
233 Import { path: ModPath { kind: Plain, segments: [Name(Text("b"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_glob: true, is_prelude: false, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UseItem>(0) }
234 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("ext_crate"))] }, input: None }]) }]
235 ExternCrate { path: ModPath { kind: Plain, segments: [Name(Text("krate"))] }, alias: None, visibility: RawVisibilityId("pub(self)"), is_macro_use: false, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::ExternCrateItem>(1) }
236 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("on_trait"))] }, input: None }]) }]
237 Trait { name: Name(Text("Tr")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(0), 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) }
238 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("assoc_ty"))] }, input: None }]) }]
239 > TypeAlias { name: Name(Text("AssocTy")), visibility: RawVisibilityId("pub(self)"), bounds: [Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("Tr"))] }, generic_args: [Some(GenericArgs { args: [Type(Tuple([]))], has_self_type: false, bindings: [] })] })], generic_params: GenericParamsId(4294967295), type_ref: None, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::TypeAliasDef>(8) }
240 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("assoc_const"))] }, input: None }]) }]
241 > Const { name: Some(Name(Text("CONST"))), visibility: RawVisibilityId("pub(self)"), type_ref: Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("u8"))] }, generic_args: [None] }), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::ConstDef>(9) }
242 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("assoc_method"))] }, input: None }]) }]
243 > Function { name: Name(Text("method")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: true, is_unsafe: false, params: [Reference(Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("Self"))] }, generic_args: [None] }), Shared)], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(10) }
244 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("assoc_dfl_method"))] }, input: None }]) }]
245 > Function { name: Name(Text("dfl_method")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: true, is_unsafe: false, params: [Reference(Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("Self"))] }, generic_args: [None] }), Mut)], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(11) }
246 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("struct0"))] }, input: None }]) }]
247 Struct { name: Name(Text("Struct0")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(1), fields: Unit, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(3), kind: Unit }
248 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("struct1"))] }, input: None }]) }]
249 Struct { name: Name(Text("Struct1")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(2), fields: Tuple(IdRange::<ra_hir_def::item_tree::Field>(0..1)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(4), kind: Tuple }
250 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("struct2"))] }, input: None }]) }]
251 Struct { name: Name(Text("Struct2")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(3), fields: Record(IdRange::<ra_hir_def::item_tree::Field>(1..2)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::StructDef>(5), kind: Record }
252 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("en"))] }, input: None }]) }]
253 Enum { name: Name(Text("En")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), variants: IdRange::<ra_hir_def::item_tree::Variant>(0..1), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::EnumDef>(6) }
254 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("un"))] }, input: None }]) }]
255 Union { name: Name(Text("Un")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), fields: Record(IdRange::<ra_hir_def::item_tree::Field>(3..4)), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::UnionDef>(7) }
256 "##]],
257 );
258}
259
260#[test]
261fn simple_inner_items() {
262 check(
263 r"
264 impl<T:A> D for Response<T> {
265 fn foo() {
266 end();
267 fn end<W: Write>() {
268 let _x: T = loop {};
269 }
270 }
271 }
272 ",
273 expect![[r#"
274 inner attrs: Attrs { entries: None }
275
276 top-level items:
277 Impl { generic_params: GenericParamsId(0), 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) }
278 > Function { name: Name(Text("foo")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(1) }
279
280 inner items:
281
282 for AST FileAstId::<ra_syntax::ast::generated::nodes::ModuleItem>(2):
283 Function { name: Name(Text("end")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(1), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(2) }
284
285 "#]],
286 );
287}
288
289#[test]
290fn extern_attrs() {
291 check(
292 r#"
293 #[block_attr]
294 extern "C" {
295 #[attr_a]
296 fn a() {}
297 #[attr_b]
298 fn b() {}
299 }
300 "#,
301 expect![[r##"
302 inner attrs: Attrs { entries: None }
303
304 top-level items:
305 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_a"))] }, input: None }, Attr { path: ModPath { kind: Plain, segments: [Name(Text("block_attr"))] }, input: None }]) }]
306 Function { name: Name(Text("a")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: true, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(1) }
307 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_b"))] }, input: None }, Attr { path: ModPath { kind: Plain, segments: [Name(Text("block_attr"))] }, input: None }]) }]
308 Function { name: Name(Text("b")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: true, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(2) }
309 "##]],
310 );
311}
312
313#[test]
314fn trait_attrs() {
315 check(
316 r#"
317 #[trait_attr]
318 trait Tr {
319 #[attr_a]
320 fn a() {}
321 #[attr_b]
322 fn b() {}
323 }
324 "#,
325 expect![[r##"
326 inner attrs: Attrs { entries: None }
327
328 top-level items:
329 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("trait_attr"))] }, input: None }]) }]
330 Trait { name: Name(Text("Tr")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(0), auto: false, items: [Function(Idx::<Function>(0)), Function(Idx::<Function>(1))], ast_id: FileAstId::<ra_syntax::ast::generated::nodes::TraitDef>(0) }
331 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_a"))] }, input: None }]) }]
332 > Function { name: Name(Text("a")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(1) }
333 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_b"))] }, input: None }]) }]
334 > Function { name: Name(Text("b")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(2) }
335 "##]],
336 );
337}
338
339#[test]
340fn impl_attrs() {
341 check(
342 r#"
343 #[impl_attr]
344 impl Ty {
345 #[attr_a]
346 fn a() {}
347 #[attr_b]
348 fn b() {}
349 }
350 "#,
351 expect![[r##"
352 inner attrs: Attrs { entries: None }
353
354 top-level items:
355 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("impl_attr"))] }, input: None }]) }]
356 Impl { generic_params: GenericParamsId(4294967295), target_trait: None, target_type: Path(Path { type_anchor: None, mod_path: ModPath { kind: Plain, segments: [Name(Text("Ty"))] }, generic_args: [None] }), is_negative: false, items: [Function(Idx::<Function>(0)), Function(Idx::<Function>(1))], ast_id: FileAstId::<ra_syntax::ast::generated::nodes::ImplDef>(0) }
357 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_a"))] }, input: None }]) }]
358 > Function { name: Name(Text("a")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(1) }
359 > #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("attr_b"))] }, input: None }]) }]
360 > Function { name: Name(Text("b")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(2) }
361 "##]],
362 );
363}
364
365#[test]
366fn cursed_inner_items() {
367 test_inner_items(
368 r"
369 struct S<T: Trait = [u8; { fn f() {} 0 }]>(T);
370
371 enum En {
372 Var1 {
373 t: [(); { trait Inner {} 0 }],
374 },
375
376 Var2([u16; { enum Inner {} 0 }]),
377 }
378
379 type Ty = [En; { struct Inner; 0 }];
380
381 impl En {
382 fn assoc() {
383 trait InnerTrait<T = [u8; { fn f() {} }]> {}
384 struct InnerStruct<T = [u8; { fn f() {} }]> {}
385 impl<T = [u8; { fn f() {} }]> InnerTrait for InnerStruct {}
386 }
387 }
388
389 trait Tr<T = [u8; { fn f() {} }]> {
390 type AssocTy = [u8; { fn f() {} }];
391
392 const AssocConst: [u8; { fn f() {} }];
393 }
394 ",
395 );
396}
397
398#[test]
399fn inner_item_attrs() {
400 check(
401 r"
402 fn foo() {
403 #[on_inner]
404 fn inner() {}
405 }
406 ",
407 expect![[r##"
408 inner attrs: Attrs { entries: None }
409
410 top-level items:
411 Function { name: Name(Text("foo")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(0) }
412
413 inner items:
414
415 for AST FileAstId::<ra_syntax::ast::generated::nodes::ModuleItem>(1):
416 #[Attrs { entries: Some([Attr { path: ModPath { kind: Plain, segments: [Name(Text("on_inner"))] }, input: None }]) }]
417 Function { name: Name(Text("inner")), visibility: RawVisibilityId("pub(self)"), generic_params: GenericParamsId(4294967295), has_self_param: false, is_unsafe: false, params: [], is_varargs: false, ret_type: Tuple([]), ast_id: FileAstId::<ra_syntax::ast::generated::nodes::FnDef>(1) }
418
419 "##]],
420 );
421}
422
423#[test]
424fn assoc_item_macros() {
425 check(
426 r"
427 impl S {
428 items!();
429 }
430 ",
431 expect![[r#"
432 inner attrs: Attrs { entries: None }
433
434 top-level items:
435 Impl { generic_params: GenericParamsId(4294967295), 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) }
436 > MacroCall { name: None, path: ModPath { kind: Plain, segments: [Name(Text("items"))] }, is_export: false, is_local_inner: false, is_builtin: false, ast_id: FileAstId::<ra_syntax::ast::generated::nodes::MacroCall>(1) }
437 "#]],
438 );
439}