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.rs695
-rw-r--r--crates/ra_hir_def/src/item_tree/tests.rs435
2 files changed, 1130 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..f10ad25f7
--- /dev/null
+++ b/crates/ra_hir_def/src/item_tree/lower.rs
@@ -0,0 +1,695 @@
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, attrs.clone());
130 }
131 }
132
133 items
134 }
135
136 fn add_attrs(&mut self, item: ModItem, attrs: Attrs) {
137 match self.tree.attrs.entry(AttrOwner::ModItem(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) -> Range<Idx<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 self.data().fields.alloc(data);
204 }
205 }
206 let end = self.next_field_idx();
207 start..end
208 }
209
210 fn lower_record_field(&mut self, field: &ast::RecordFieldDef) -> Option<Field> {
211 let name = field.name()?.as_name();
212 let visibility = self.lower_visibility(field);
213 let type_ref = self.lower_type_ref(&field.ascribed_type()?);
214 let res = Field { name, type_ref, visibility };
215 Some(res)
216 }
217
218 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldDefList) -> Range<Idx<Field>> {
219 let start = self.next_field_idx();
220 for (i, field) in fields.fields().enumerate() {
221 if let Some(data) = self.lower_tuple_field(i, &field) {
222 self.data().fields.alloc(data);
223 }
224 }
225 let end = self.next_field_idx();
226 start..end
227 }
228
229 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleFieldDef) -> Option<Field> {
230 let name = Name::new_tuple_field(idx);
231 let visibility = self.lower_visibility(field);
232 let type_ref = self.lower_type_ref(&field.type_ref()?);
233 let res = Field { name, type_ref, visibility };
234 Some(res)
235 }
236
237 fn lower_union(&mut self, union: &ast::UnionDef) -> Option<FileItemTreeId<Union>> {
238 let visibility = self.lower_visibility(union);
239 let name = union.name()?.as_name();
240 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
241 let fields = match union.record_field_def_list() {
242 Some(record_field_def_list) => {
243 self.lower_fields(&StructKind::Record(record_field_def_list))
244 }
245 None => Fields::Record(self.next_field_idx()..self.next_field_idx()),
246 };
247 let ast_id = self.source_ast_id_map.ast_id(union);
248 let res = Union { name, visibility, generic_params, fields, ast_id };
249 Some(id(self.data().unions.alloc(res)))
250 }
251
252 fn lower_enum(&mut self, enum_: &ast::EnumDef) -> Option<FileItemTreeId<Enum>> {
253 let visibility = self.lower_visibility(enum_);
254 let name = enum_.name()?.as_name();
255 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
256 let variants = match &enum_.variant_list() {
257 Some(variant_list) => self.lower_variants(variant_list),
258 None => self.next_variant_idx()..self.next_variant_idx(),
259 };
260 let ast_id = self.source_ast_id_map.ast_id(enum_);
261 let res = Enum { name, visibility, generic_params, variants, ast_id };
262 Some(id(self.data().enums.alloc(res)))
263 }
264
265 fn lower_variants(&mut self, variants: &ast::EnumVariantList) -> Range<Idx<Variant>> {
266 let start = self.next_variant_idx();
267 for variant in variants.variants() {
268 if let Some(data) = self.lower_variant(&variant) {
269 self.data().variants.alloc(data);
270 }
271 }
272 let end = self.next_variant_idx();
273 start..end
274 }
275
276 fn lower_variant(&mut self, variant: &ast::EnumVariant) -> Option<Variant> {
277 let name = variant.name()?.as_name();
278 let fields = self.lower_fields(&variant.kind());
279 let res = Variant { name, fields };
280 Some(res)
281 }
282
283 fn lower_function(&mut self, func: &ast::FnDef) -> Option<FileItemTreeId<Function>> {
284 let visibility = self.lower_visibility(func);
285 let name = func.name()?.as_name();
286
287 let mut params = Vec::new();
288 let mut has_self_param = false;
289 if let Some(param_list) = func.param_list() {
290 if let Some(self_param) = param_list.self_param() {
291 let self_type = match self_param.ascribed_type() {
292 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
293 None => {
294 let self_type = TypeRef::Path(name![Self].into());
295 match self_param.kind() {
296 ast::SelfParamKind::Owned => self_type,
297 ast::SelfParamKind::Ref => {
298 TypeRef::Reference(Box::new(self_type), Mutability::Shared)
299 }
300 ast::SelfParamKind::MutRef => {
301 TypeRef::Reference(Box::new(self_type), Mutability::Mut)
302 }
303 }
304 }
305 };
306 params.push(self_type);
307 has_self_param = true;
308 }
309 for param in param_list.params() {
310 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ascribed_type());
311 params.push(type_ref);
312 }
313 }
314 let ret_type = match func.ret_type().and_then(|rt| rt.type_ref()) {
315 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
316 _ => TypeRef::unit(),
317 };
318
319 let ret_type = if func.async_token().is_some() {
320 let future_impl = desugar_future_path(ret_type);
321 let ty_bound = TypeBound::Path(future_impl);
322 TypeRef::ImplTrait(vec![ty_bound])
323 } else {
324 ret_type
325 };
326
327 let ast_id = self.source_ast_id_map.ast_id(func);
328 let mut res = Function {
329 name,
330 visibility,
331 generic_params: GenericParamsId::EMPTY,
332 has_self_param,
333 is_unsafe: func.unsafe_token().is_some(),
334 params: params.into_boxed_slice(),
335 ret_type,
336 ast_id,
337 };
338 res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
339
340 Some(id(self.data().functions.alloc(res)))
341 }
342
343 fn lower_type_alias(
344 &mut self,
345 type_alias: &ast::TypeAliasDef,
346 ) -> Option<FileItemTreeId<TypeAlias>> {
347 let name = type_alias.name()?.as_name();
348 let type_ref = type_alias.type_ref().map(|it| self.lower_type_ref(&it));
349 let visibility = self.lower_visibility(type_alias);
350 let bounds = self.lower_type_bounds(type_alias);
351 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
352 let ast_id = self.source_ast_id_map.ast_id(type_alias);
353 let res = TypeAlias {
354 name,
355 visibility,
356 bounds: bounds.into_boxed_slice(),
357 generic_params,
358 type_ref,
359 ast_id,
360 };
361 Some(id(self.data().type_aliases.alloc(res)))
362 }
363
364 fn lower_static(&mut self, static_: &ast::StaticDef) -> Option<FileItemTreeId<Static>> {
365 let name = static_.name()?.as_name();
366 let type_ref = self.lower_type_ref_opt(static_.ascribed_type());
367 let visibility = self.lower_visibility(static_);
368 let mutable = static_.mut_token().is_some();
369 let ast_id = self.source_ast_id_map.ast_id(static_);
370 let res = Static { name, visibility, mutable, type_ref, ast_id };
371 Some(id(self.data().statics.alloc(res)))
372 }
373
374 fn lower_const(&mut self, konst: &ast::ConstDef) -> FileItemTreeId<Const> {
375 let name = konst.name().map(|it| it.as_name());
376 let type_ref = self.lower_type_ref_opt(konst.ascribed_type());
377 let visibility = self.lower_visibility(konst);
378 let ast_id = self.source_ast_id_map.ast_id(konst);
379 let res = Const { name, visibility, type_ref, ast_id };
380 id(self.data().consts.alloc(res))
381 }
382
383 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
384 let name = module.name()?.as_name();
385 let visibility = self.lower_visibility(module);
386 let kind = if module.semicolon_token().is_some() {
387 ModKind::Outline {}
388 } else {
389 ModKind::Inline {
390 items: module
391 .item_list()
392 .map(|list| {
393 list.items()
394 .flat_map(|item| self.lower_mod_item(&item, false))
395 .flat_map(|items| items.0)
396 .collect()
397 })
398 .unwrap_or_else(|| {
399 mark::hit!(name_res_works_for_broken_modules);
400 Box::new([]) as Box<[_]>
401 }),
402 }
403 };
404 let ast_id = self.source_ast_id_map.ast_id(module);
405 let res = Mod { name, visibility, kind, ast_id };
406 Some(id(self.data().mods.alloc(res)))
407 }
408
409 fn lower_trait(&mut self, trait_def: &ast::TraitDef) -> Option<FileItemTreeId<Trait>> {
410 let name = trait_def.name()?.as_name();
411 let visibility = self.lower_visibility(trait_def);
412 let generic_params =
413 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
414 let auto = trait_def.auto_token().is_some();
415 let items = trait_def.item_list().map(|list| {
416 self.with_inherited_visibility(visibility, |this| {
417 list.items()
418 .filter_map(|item| {
419 let attrs = Attrs::new(&item, &this.hygiene);
420 this.collect_inner_items(item.syntax());
421 this.lower_assoc_item(&item).map(|item| {
422 this.add_attrs(item.into(), attrs);
423 item
424 })
425 })
426 .collect()
427 })
428 });
429 let ast_id = self.source_ast_id_map.ast_id(trait_def);
430 let res = Trait {
431 name,
432 visibility,
433 generic_params,
434 auto,
435 items: items.unwrap_or_default(),
436 ast_id,
437 };
438 Some(id(self.data().traits.alloc(res)))
439 }
440
441 fn lower_impl(&mut self, impl_def: &ast::ImplDef) -> Option<FileItemTreeId<Impl>> {
442 let generic_params =
443 self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
444 let target_trait = impl_def.target_trait().map(|tr| self.lower_type_ref(&tr));
445 let target_type = self.lower_type_ref(&impl_def.target_type()?);
446 let is_negative = impl_def.excl_token().is_some();
447
448 // We cannot use `assoc_items()` here as that does not include macro calls.
449 let items = impl_def
450 .item_list()?
451 .items()
452 .filter_map(|item| {
453 self.collect_inner_items(item.syntax());
454 let assoc = self.lower_assoc_item(&item)?;
455 let attrs = Attrs::new(&item, &self.hygiene);
456 self.add_attrs(assoc.into(), attrs);
457 Some(assoc)
458 })
459 .collect();
460 let ast_id = self.source_ast_id_map.ast_id(impl_def);
461 let res = Impl { generic_params, target_trait, target_type, is_negative, items, ast_id };
462 Some(id(self.data().impls.alloc(res)))
463 }
464
465 fn lower_use(&mut self, use_item: &ast::UseItem) -> Vec<FileItemTreeId<Import>> {
466 // FIXME: cfg_attr
467 let is_prelude = use_item.has_atom_attr("prelude_import");
468 let visibility = self.lower_visibility(use_item);
469 let ast_id = self.source_ast_id_map.ast_id(use_item);
470
471 // Every use item can expand to many `Import`s.
472 let mut imports = Vec::new();
473 let tree = self.tree.data_mut();
474 ModPath::expand_use_item(
475 InFile::new(self.file, use_item.clone()),
476 &self.hygiene,
477 |path, _tree, is_glob, alias| {
478 imports.push(id(tree.imports.alloc(Import {
479 path,
480 alias,
481 visibility,
482 is_glob,
483 is_prelude,
484 ast_id,
485 })));
486 },
487 );
488
489 imports
490 }
491
492 fn lower_extern_crate(
493 &mut self,
494 extern_crate: &ast::ExternCrateItem,
495 ) -> Option<FileItemTreeId<ExternCrate>> {
496 let path = ModPath::from_name_ref(&extern_crate.name_ref()?);
497 let alias = extern_crate.alias().map(|a| {
498 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
499 });
500 let visibility = self.lower_visibility(extern_crate);
501 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
502 // FIXME: cfg_attr
503 let is_macro_use = extern_crate.has_atom_attr("macro_use");
504
505 let res = ExternCrate { path, alias, visibility, is_macro_use, ast_id };
506 Some(id(self.data().extern_crates.alloc(res)))
507 }
508
509 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
510 let name = m.name().map(|it| it.as_name());
511 let attrs = Attrs::new(m, &self.hygiene);
512 let path = ModPath::from_src(m.path()?, &self.hygiene)?;
513
514 let ast_id = self.source_ast_id_map.ast_id(m);
515
516 // FIXME: cfg_attr
517 let export_attr = attrs.by_key("macro_export");
518
519 let is_export = export_attr.exists();
520 let is_local_inner = if is_export {
521 export_attr.tt_values().map(|it| &it.token_trees).flatten().any(|it| match it {
522 tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
523 ident.text.contains("local_inner_macros")
524 }
525 _ => false,
526 })
527 } else {
528 false
529 };
530
531 let is_builtin = attrs.by_key("rustc_builtin_macro").exists();
532 let res = MacroCall { name, path, is_export, is_builtin, is_local_inner, ast_id };
533 Some(id(self.data().macro_calls.alloc(res)))
534 }
535
536 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> Vec<ModItem> {
537 block.extern_item_list().map_or(Vec::new(), |list| {
538 list.extern_items()
539 .filter_map(|item| {
540 self.collect_inner_items(item.syntax());
541 let attrs = Attrs::new(&item, &self.hygiene);
542 let id = match item {
543 ast::ExternItem::FnDef(ast) => {
544 let func = self.lower_function(&ast)?;
545 func.into()
546 }
547 ast::ExternItem::StaticDef(ast) => {
548 let statik = self.lower_static(&ast)?;
549 statik.into()
550 }
551 };
552 self.add_attrs(id, attrs);
553 Some(id)
554 })
555 .collect()
556 })
557 }
558
559 /// Lowers generics defined on `node` and collects inner items defined within.
560 fn lower_generic_params_and_inner_items(
561 &mut self,
562 owner: GenericsOwner<'_>,
563 node: &impl ast::TypeParamsOwner,
564 ) -> GenericParamsId {
565 // Generics are part of item headers and may contain inner items we need to collect.
566 if let Some(params) = node.type_param_list() {
567 self.collect_inner_items(params.syntax());
568 }
569 if let Some(clause) = node.where_clause() {
570 self.collect_inner_items(clause.syntax());
571 }
572
573 self.lower_generic_params(owner, node)
574 }
575
576 fn lower_generic_params(
577 &mut self,
578 owner: GenericsOwner<'_>,
579 node: &impl ast::TypeParamsOwner,
580 ) -> GenericParamsId {
581 let mut sm = &mut ArenaMap::default();
582 let mut generics = GenericParams::default();
583 match owner {
584 GenericsOwner::Function(func) => {
585 generics.fill(&self.body_ctx, sm, node);
586 // lower `impl Trait` in arguments
587 for param in &*func.params {
588 generics.fill_implicit_impl_trait_args(param);
589 }
590 }
591 GenericsOwner::Struct
592 | GenericsOwner::Enum
593 | GenericsOwner::Union
594 | GenericsOwner::TypeAlias => {
595 generics.fill(&self.body_ctx, sm, node);
596 }
597 GenericsOwner::Trait(trait_def) => {
598 // traits get the Self type as an implicit first type parameter
599 let self_param_id = generics.types.alloc(TypeParamData {
600 name: Some(name![Self]),
601 default: None,
602 provenance: TypeParamProvenance::TraitSelf,
603 });
604 sm.insert(self_param_id, Either::Left(trait_def.clone()));
605 // add super traits as bounds on Self
606 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
607 let self_param = TypeRef::Path(name![Self].into());
608 generics.fill_bounds(&self.body_ctx, trait_def, self_param);
609
610 generics.fill(&self.body_ctx, &mut sm, node);
611 }
612 GenericsOwner::Impl => {
613 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
614 // type-parameter, but rather is a type-alias for impl's target
615 // type, so this is handled by the resolver.
616 generics.fill(&self.body_ctx, &mut sm, node);
617 }
618 }
619
620 self.data().generics.alloc(generics)
621 }
622
623 fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<TypeBound> {
624 match node.type_bound_list() {
625 Some(bound_list) => {
626 bound_list.bounds().map(|it| TypeBound::from_ast(&self.body_ctx, it)).collect()
627 }
628 None => Vec::new(),
629 }
630 }
631
632 fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
633 let vis = match self.forced_visibility {
634 Some(vis) => return vis,
635 None => RawVisibility::from_ast_with_hygiene(item.visibility(), &self.hygiene),
636 };
637
638 self.data().vis.alloc(vis)
639 }
640
641 fn lower_type_ref(&self, type_ref: &ast::TypeRef) -> TypeRef {
642 TypeRef::from_ast(&self.body_ctx, type_ref.clone())
643 }
644 fn lower_type_ref_opt(&self, type_ref: Option<ast::TypeRef>) -> TypeRef {
645 type_ref.map(|ty| self.lower_type_ref(&ty)).unwrap_or(TypeRef::Error)
646 }
647
648 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
649 fn with_inherited_visibility<R>(
650 &mut self,
651 vis: RawVisibilityId,
652 f: impl FnOnce(&mut Self) -> R,
653 ) -> R {
654 let old = mem::replace(&mut self.forced_visibility, Some(vis));
655 let res = f(self);
656 self.forced_visibility = old;
657 res
658 }
659
660 fn next_field_idx(&self) -> Idx<Field> {
661 Idx::from_raw(RawId::from(
662 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
663 ))
664 }
665 fn next_variant_idx(&self) -> Idx<Variant> {
666 Idx::from_raw(RawId::from(
667 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
668 ))
669 }
670}
671
672fn desugar_future_path(orig: TypeRef) -> Path {
673 let path = path![core::future::Future];
674 let mut generic_args: Vec<_> = std::iter::repeat(None).take(path.segments.len() - 1).collect();
675 let mut last = GenericArgs::empty();
676 let binding =
677 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
678 last.bindings.push(binding);
679 generic_args.push(Some(Arc::new(last)));
680
681 Path::from_known_path(path, generic_args)
682}
683
684enum GenericsOwner<'a> {
685 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
686 /// position.
687 Function(&'a Function),
688 Struct,
689 Enum,
690 Union,
691 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
692 Trait(&'a ast::TraitDef),
693 TypeAlias,
694 Impl,
695}
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..dc035d809
--- /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);
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(Idx::<Field>(0)..Idx::<Field>(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(Idx::<Field>(1)..Idx::<Field>(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: Idx::<Variant>(0)..Idx::<Variant>(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(Idx::<Field>(3)..Idx::<Field>(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}