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