]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_tree/lower.rs
Merge #9264
[rust.git] / crates / hir_def / src / item_tree / lower.rs
1 //! AST -> `ItemTree` lowering code.
2
3 use std::{collections::hash_map::Entry, mem, sync::Arc};
4
5 use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, name::known, HirFileId};
6 use syntax::{
7     ast::{self, ModuleItemOwner},
8     SyntaxNode, WalkEvent,
9 };
10
11 use crate::{
12     generics::{GenericParams, TypeParamData, TypeParamProvenance},
13     type_ref::{LifetimeRef, TraitRef},
14 };
15
16 use super::*;
17
18 fn id<N: ItemTreeNode>(index: Idx<N>) -> FileItemTreeId<N> {
19     FileItemTreeId { index, _p: PhantomData }
20 }
21
22 pub(super) struct Ctx<'a> {
23     db: &'a dyn DefDatabase,
24     tree: ItemTree,
25     hygiene: Hygiene,
26     source_ast_id_map: Arc<AstIdMap>,
27     body_ctx: crate::body::LowerCtx<'a>,
28     forced_visibility: Option<RawVisibilityId>,
29 }
30
31 impl<'a> Ctx<'a> {
32     pub(super) fn new(db: &'a dyn DefDatabase, hygiene: Hygiene, file: HirFileId) -> Self {
33         Self {
34             db,
35             tree: ItemTree::default(),
36             hygiene,
37             source_ast_id_map: db.ast_id_map(file),
38             body_ctx: crate::body::LowerCtx::new(db, file),
39             forced_visibility: None,
40         }
41     }
42
43     pub(super) fn lower_module_items(mut self, item_owner: &dyn ModuleItemOwner) -> ItemTree {
44         self.tree.top_level =
45             item_owner.items().flat_map(|item| self.lower_mod_item(&item, false)).collect();
46         self.tree
47     }
48
49     pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
50         self.tree.top_level = stmts
51             .statements()
52             .filter_map(|stmt| match stmt {
53                 ast::Stmt::Item(item) => Some(item),
54                 _ => None,
55             })
56             .flat_map(|item| self.lower_mod_item(&item, false))
57             .collect();
58
59         // Non-items need to have their inner items collected.
60         for stmt in stmts.statements() {
61             match stmt {
62                 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => {
63                     self.collect_inner_items(stmt.syntax())
64                 }
65                 _ => {}
66             }
67         }
68         if let Some(expr) = stmts.expr() {
69             self.collect_inner_items(expr.syntax());
70         }
71         self.tree
72     }
73
74     pub(super) fn lower_inner_items(mut self, within: &SyntaxNode) -> ItemTree {
75         self.collect_inner_items(within);
76         self.tree
77     }
78
79     fn data(&mut self) -> &mut ItemTreeData {
80         self.tree.data_mut()
81     }
82
83     fn lower_mod_item(&mut self, item: &ast::Item, inner: bool) -> Option<ModItem> {
84         // Collect inner items for 1-to-1-lowered items.
85         match item {
86             ast::Item::Struct(_)
87             | ast::Item::Union(_)
88             | ast::Item::Enum(_)
89             | ast::Item::Fn(_)
90             | ast::Item::TypeAlias(_)
91             | ast::Item::Const(_)
92             | ast::Item::Static(_) => {
93                 // Skip this if we're already collecting inner items. We'll descend into all nodes
94                 // already.
95                 if !inner {
96                     self.collect_inner_items(item.syntax());
97                 }
98             }
99
100             // These are handled in their respective `lower_X` method (since we can't just blindly
101             // walk them).
102             ast::Item::Trait(_) | ast::Item::Impl(_) | ast::Item::ExternBlock(_) => {}
103
104             // These don't have inner items.
105             ast::Item::Module(_)
106             | ast::Item::ExternCrate(_)
107             | ast::Item::Use(_)
108             | ast::Item::MacroCall(_)
109             | ast::Item::MacroRules(_)
110             | ast::Item::MacroDef(_) => {}
111         };
112
113         let attrs = RawAttrs::new(self.db, item, &self.hygiene);
114         let item: ModItem = match item {
115             ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
116             ast::Item::Union(ast) => self.lower_union(ast)?.into(),
117             ast::Item::Enum(ast) => self.lower_enum(ast)?.into(),
118             ast::Item::Fn(ast) => self.lower_function(ast)?.into(),
119             ast::Item::TypeAlias(ast) => self.lower_type_alias(ast)?.into(),
120             ast::Item::Static(ast) => self.lower_static(ast)?.into(),
121             ast::Item::Const(ast) => self.lower_const(ast).into(),
122             ast::Item::Module(ast) => self.lower_module(ast)?.into(),
123             ast::Item::Trait(ast) => self.lower_trait(ast)?.into(),
124             ast::Item::Impl(ast) => self.lower_impl(ast)?.into(),
125             ast::Item::Use(ast) => self.lower_use(ast)?.into(),
126             ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast)?.into(),
127             ast::Item::MacroCall(ast) => self.lower_macro_call(ast)?.into(),
128             ast::Item::MacroRules(ast) => self.lower_macro_rules(ast)?.into(),
129             ast::Item::MacroDef(ast) => self.lower_macro_def(ast)?.into(),
130             ast::Item::ExternBlock(ast) => self.lower_extern_block(ast).into(),
131         };
132
133         self.add_attrs(item.into(), attrs);
134
135         Some(item)
136     }
137
138     fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) {
139         match self.tree.attrs.entry(item) {
140             Entry::Occupied(mut entry) => {
141                 *entry.get_mut() = entry.get().merge(attrs);
142             }
143             Entry::Vacant(entry) => {
144                 entry.insert(attrs);
145             }
146         }
147     }
148
149     fn collect_inner_items(&mut self, container: &SyntaxNode) {
150         let forced_vis = self.forced_visibility.take();
151
152         let mut block_stack = Vec::new();
153
154         // if container itself is block, add it to the stack
155         if let Some(block) = ast::BlockExpr::cast(container.clone()) {
156             block_stack.push(self.source_ast_id_map.ast_id(&block));
157         }
158
159         for event in container.preorder().skip(1) {
160             match event {
161                 WalkEvent::Enter(node) => {
162                     match_ast! {
163                         match node {
164                             ast::BlockExpr(block) => {
165                                 block_stack.push(self.source_ast_id_map.ast_id(&block));
166                             },
167                             ast::Item(item) => {
168                                 // FIXME: This triggers for macro calls in expression/pattern/type position
169                                 let mod_item = self.lower_mod_item(&item, true);
170                                 let current_block = block_stack.last();
171                                 if let (Some(mod_item), Some(block)) = (mod_item, current_block) {
172                                         self.data().inner_items.entry(*block).or_default().push(mod_item);
173                                 }
174                             },
175                             _ => {}
176                         }
177                     }
178                 }
179                 WalkEvent::Leave(node) => {
180                     if ast::BlockExpr::cast(node).is_some() {
181                         block_stack.pop();
182                     }
183                 }
184             }
185         }
186
187         self.forced_visibility = forced_vis;
188     }
189
190     fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
191         match item {
192             ast::AssocItem::Fn(ast) => self.lower_function(ast).map(Into::into),
193             ast::AssocItem::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
194             ast::AssocItem::Const(ast) => Some(self.lower_const(ast).into()),
195             ast::AssocItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
196         }
197     }
198
199     fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<FileItemTreeId<Struct>> {
200         let visibility = self.lower_visibility(strukt);
201         let name = strukt.name()?.as_name();
202         let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
203         let fields = self.lower_fields(&strukt.kind());
204         let ast_id = self.source_ast_id_map.ast_id(strukt);
205         let res = Struct { name, visibility, generic_params, fields, ast_id };
206         Some(id(self.data().structs.alloc(res)))
207     }
208
209     fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
210         match strukt_kind {
211             ast::StructKind::Record(it) => {
212                 let range = self.lower_record_fields(it);
213                 Fields::Record(range)
214             }
215             ast::StructKind::Tuple(it) => {
216                 let range = self.lower_tuple_fields(it);
217                 Fields::Tuple(range)
218             }
219             ast::StructKind::Unit => Fields::Unit,
220         }
221     }
222
223     fn lower_record_fields(&mut self, fields: &ast::RecordFieldList) -> IdRange<Field> {
224         let start = self.next_field_idx();
225         for field in fields.fields() {
226             if let Some(data) = self.lower_record_field(&field) {
227                 let idx = self.data().fields.alloc(data);
228                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, &self.hygiene));
229             }
230         }
231         let end = self.next_field_idx();
232         IdRange::new(start..end)
233     }
234
235     fn lower_record_field(&mut self, field: &ast::RecordField) -> Option<Field> {
236         let name = field.name()?.as_name();
237         let visibility = self.lower_visibility(field);
238         let type_ref = self.lower_type_ref_opt(field.ty());
239         let res = Field { name, type_ref, visibility };
240         Some(res)
241     }
242
243     fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldList) -> IdRange<Field> {
244         let start = self.next_field_idx();
245         for (i, field) in fields.fields().enumerate() {
246             let data = self.lower_tuple_field(i, &field);
247             let idx = self.data().fields.alloc(data);
248             self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, &self.hygiene));
249         }
250         let end = self.next_field_idx();
251         IdRange::new(start..end)
252     }
253
254     fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field {
255         let name = Name::new_tuple_field(idx);
256         let visibility = self.lower_visibility(field);
257         let type_ref = self.lower_type_ref_opt(field.ty());
258         let res = Field { name, type_ref, visibility };
259         res
260     }
261
262     fn lower_union(&mut self, union: &ast::Union) -> Option<FileItemTreeId<Union>> {
263         let visibility = self.lower_visibility(union);
264         let name = union.name()?.as_name();
265         let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
266         let fields = match union.record_field_list() {
267             Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)),
268             None => Fields::Record(IdRange::new(self.next_field_idx()..self.next_field_idx())),
269         };
270         let ast_id = self.source_ast_id_map.ast_id(union);
271         let res = Union { name, visibility, generic_params, fields, ast_id };
272         Some(id(self.data().unions.alloc(res)))
273     }
274
275     fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<FileItemTreeId<Enum>> {
276         let visibility = self.lower_visibility(enum_);
277         let name = enum_.name()?.as_name();
278         let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
279         let variants =
280             self.with_inherited_visibility(visibility, |this| match &enum_.variant_list() {
281                 Some(variant_list) => this.lower_variants(variant_list),
282                 None => IdRange::new(this.next_variant_idx()..this.next_variant_idx()),
283             });
284         let ast_id = self.source_ast_id_map.ast_id(enum_);
285         let res = Enum { name, visibility, generic_params, variants, ast_id };
286         Some(id(self.data().enums.alloc(res)))
287     }
288
289     fn lower_variants(&mut self, variants: &ast::VariantList) -> IdRange<Variant> {
290         let start = self.next_variant_idx();
291         for variant in variants.variants() {
292             if let Some(data) = self.lower_variant(&variant) {
293                 let idx = self.data().variants.alloc(data);
294                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, &self.hygiene));
295             }
296         }
297         let end = self.next_variant_idx();
298         IdRange::new(start..end)
299     }
300
301     fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
302         let name = variant.name()?.as_name();
303         let fields = self.lower_fields(&variant.kind());
304         let res = Variant { name, fields };
305         Some(res)
306     }
307
308     fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
309         let visibility = self.lower_visibility(func);
310         let name = func.name()?.as_name();
311
312         let mut has_self_param = false;
313         let start_param = self.next_param_idx();
314         if let Some(param_list) = func.param_list() {
315             if let Some(self_param) = param_list.self_param() {
316                 let self_type = match self_param.ty() {
317                     Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
318                     None => {
319                         let self_type = TypeRef::Path(name![Self].into());
320                         match self_param.kind() {
321                             ast::SelfParamKind::Owned => self_type,
322                             ast::SelfParamKind::Ref => TypeRef::Reference(
323                                 Box::new(self_type),
324                                 self_param.lifetime().as_ref().map(LifetimeRef::new),
325                                 Mutability::Shared,
326                             ),
327                             ast::SelfParamKind::MutRef => TypeRef::Reference(
328                                 Box::new(self_type),
329                                 self_param.lifetime().as_ref().map(LifetimeRef::new),
330                                 Mutability::Mut,
331                             ),
332                         }
333                     }
334                 };
335                 let ty = Interned::new(self_type);
336                 let idx = self.data().params.alloc(Param::Normal(ty));
337                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, &self.hygiene));
338                 has_self_param = true;
339             }
340             for param in param_list.params() {
341                 let idx = match param.dotdotdot_token() {
342                     Some(_) => self.data().params.alloc(Param::Varargs),
343                     None => {
344                         let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
345                         let ty = Interned::new(type_ref);
346                         self.data().params.alloc(Param::Normal(ty))
347                     }
348                 };
349                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &param, &self.hygiene));
350             }
351         }
352         let end_param = self.next_param_idx();
353         let params = IdRange::new(start_param..end_param);
354
355         let ret_type = match func.ret_type().and_then(|rt| rt.ty()) {
356             Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
357             _ => TypeRef::unit(),
358         };
359
360         let (ret_type, async_ret_type) = if func.async_token().is_some() {
361             let async_ret_type = ret_type.clone();
362             let future_impl = desugar_future_path(ret_type);
363             let ty_bound = Interned::new(TypeBound::Path(future_impl));
364             (TypeRef::ImplTrait(vec![ty_bound]), Some(async_ret_type))
365         } else {
366             (ret_type, None)
367         };
368
369         let abi = func.abi().map(lower_abi);
370
371         let ast_id = self.source_ast_id_map.ast_id(func);
372
373         let mut flags = FnFlags::default();
374         if func.body().is_some() {
375             flags.bits |= FnFlags::HAS_BODY;
376         }
377         if has_self_param {
378             flags.bits |= FnFlags::HAS_SELF_PARAM;
379         }
380         if func.default_token().is_some() {
381             flags.bits |= FnFlags::IS_DEFAULT;
382         }
383         if func.const_token().is_some() {
384             flags.bits |= FnFlags::IS_CONST;
385         }
386         if func.async_token().is_some() {
387             flags.bits |= FnFlags::IS_ASYNC;
388         }
389         if func.unsafe_token().is_some() {
390             flags.bits |= FnFlags::IS_UNSAFE;
391         }
392
393         let mut res = Function {
394             name,
395             visibility,
396             generic_params: Interned::new(GenericParams::default()),
397             abi,
398             params,
399             ret_type: Interned::new(ret_type),
400             async_ret_type: async_ret_type.map(Interned::new),
401             ast_id,
402             flags,
403         };
404         res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
405
406         Some(id(self.data().functions.alloc(res)))
407     }
408
409     fn lower_type_alias(
410         &mut self,
411         type_alias: &ast::TypeAlias,
412     ) -> Option<FileItemTreeId<TypeAlias>> {
413         let name = type_alias.name()?.as_name();
414         let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
415         let visibility = self.lower_visibility(type_alias);
416         let bounds = self.lower_type_bounds(type_alias);
417         let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
418         let ast_id = self.source_ast_id_map.ast_id(type_alias);
419         let res = TypeAlias {
420             name,
421             visibility,
422             bounds: bounds.into_boxed_slice(),
423             generic_params,
424             type_ref,
425             ast_id,
426             is_extern: false,
427         };
428         Some(id(self.data().type_aliases.alloc(res)))
429     }
430
431     fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
432         let name = static_.name()?.as_name();
433         let type_ref = self.lower_type_ref_opt(static_.ty());
434         let visibility = self.lower_visibility(static_);
435         let mutable = static_.mut_token().is_some();
436         let ast_id = self.source_ast_id_map.ast_id(static_);
437         let res = Static { name, visibility, mutable, type_ref, ast_id, is_extern: false };
438         Some(id(self.data().statics.alloc(res)))
439     }
440
441     fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
442         let name = konst.name().map(|it| it.as_name());
443         let type_ref = self.lower_type_ref_opt(konst.ty());
444         let visibility = self.lower_visibility(konst);
445         let ast_id = self.source_ast_id_map.ast_id(konst);
446         let res = Const { name, visibility, type_ref, ast_id };
447         id(self.data().consts.alloc(res))
448     }
449
450     fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
451         let name = module.name()?.as_name();
452         let visibility = self.lower_visibility(module);
453         let kind = if module.semicolon_token().is_some() {
454             ModKind::Outline {}
455         } else {
456             ModKind::Inline {
457                 items: module
458                     .item_list()
459                     .map(|list| {
460                         list.items().flat_map(|item| self.lower_mod_item(&item, false)).collect()
461                     })
462                     .unwrap_or_else(|| {
463                         cov_mark::hit!(name_res_works_for_broken_modules);
464                         Box::new([]) as Box<[_]>
465                     }),
466             }
467         };
468         let ast_id = self.source_ast_id_map.ast_id(module);
469         let res = Mod { name, visibility, kind, ast_id };
470         Some(id(self.data().mods.alloc(res)))
471     }
472
473     fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
474         let name = trait_def.name()?.as_name();
475         let visibility = self.lower_visibility(trait_def);
476         let generic_params =
477             self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
478         let is_auto = trait_def.auto_token().is_some();
479         let is_unsafe = trait_def.unsafe_token().is_some();
480         let items = trait_def.assoc_item_list().map(|list| {
481             let db = self.db;
482             self.with_inherited_visibility(visibility, |this| {
483                 list.assoc_items()
484                     .filter_map(|item| {
485                         let attrs = RawAttrs::new(db, &item, &this.hygiene);
486                         this.collect_inner_items(item.syntax());
487                         this.lower_assoc_item(&item).map(|item| {
488                             this.add_attrs(ModItem::from(item).into(), attrs);
489                             item
490                         })
491                     })
492                     .collect()
493             })
494         });
495         let ast_id = self.source_ast_id_map.ast_id(trait_def);
496         let res = Trait {
497             name,
498             visibility,
499             generic_params,
500             is_auto,
501             is_unsafe,
502             items: items.unwrap_or_default(),
503             ast_id,
504         };
505         Some(id(self.data().traits.alloc(res)))
506     }
507
508     fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
509         let generic_params =
510             self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
511         // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
512         // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
513         // equals itself.
514         let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
515         let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
516         let is_negative = impl_def.excl_token().is_some();
517
518         // We cannot use `assoc_items()` here as that does not include macro calls.
519         let items = impl_def
520             .assoc_item_list()
521             .into_iter()
522             .flat_map(|it| it.assoc_items())
523             .filter_map(|item| {
524                 self.collect_inner_items(item.syntax());
525                 let assoc = self.lower_assoc_item(&item)?;
526                 let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
527                 self.add_attrs(ModItem::from(assoc).into(), attrs);
528                 Some(assoc)
529             })
530             .collect();
531         let ast_id = self.source_ast_id_map.ast_id(impl_def);
532         let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
533         Some(id(self.data().impls.alloc(res)))
534     }
535
536     fn lower_use(&mut self, use_item: &ast::Use) -> Option<FileItemTreeId<Import>> {
537         let visibility = self.lower_visibility(use_item);
538         let ast_id = self.source_ast_id_map.ast_id(use_item);
539         let (use_tree, _) = lower_use_tree(self.db, &self.hygiene, use_item.use_tree()?)?;
540
541         let res = Import { visibility, ast_id, use_tree };
542         Some(id(self.data().imports.alloc(res)))
543     }
544
545     fn lower_extern_crate(
546         &mut self,
547         extern_crate: &ast::ExternCrate,
548     ) -> Option<FileItemTreeId<ExternCrate>> {
549         let name = extern_crate.name_ref()?.as_name();
550         let alias = extern_crate.rename().map(|a| {
551             a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
552         });
553         let visibility = self.lower_visibility(extern_crate);
554         let ast_id = self.source_ast_id_map.ast_id(extern_crate);
555
556         let res = ExternCrate { name, alias, visibility, ast_id };
557         Some(id(self.data().extern_crates.alloc(res)))
558     }
559
560     fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
561         let path = Interned::new(ModPath::from_src(self.db, m.path()?, &self.hygiene)?);
562         let ast_id = self.source_ast_id_map.ast_id(m);
563         let fragment = hir_expand::to_fragment_kind(m);
564         let res = MacroCall { path, ast_id, fragment };
565         Some(id(self.data().macro_calls.alloc(res)))
566     }
567
568     fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
569         let name = m.name().map(|it| it.as_name())?;
570         let ast_id = self.source_ast_id_map.ast_id(m);
571
572         let res = MacroRules { name, ast_id };
573         Some(id(self.data().macro_rules.alloc(res)))
574     }
575
576     fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
577         let name = m.name().map(|it| it.as_name())?;
578
579         let ast_id = self.source_ast_id_map.ast_id(m);
580         let visibility = self.lower_visibility(m);
581
582         let res = MacroDef { name, ast_id, visibility };
583         Some(id(self.data().macro_defs.alloc(res)))
584     }
585
586     fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> FileItemTreeId<ExternBlock> {
587         let ast_id = self.source_ast_id_map.ast_id(block);
588         let abi = block.abi().map(lower_abi);
589         let children: Box<[_]> = block.extern_item_list().map_or(Box::new([]), |list| {
590             list.extern_items()
591                 .filter_map(|item| {
592                     self.collect_inner_items(item.syntax());
593                     let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
594                     let id: ModItem = match item {
595                         ast::ExternItem::Fn(ast) => {
596                             let func_id = self.lower_function(&ast)?;
597                             let func = &mut self.data().functions[func_id.index];
598                             if is_intrinsic_fn_unsafe(&func.name) {
599                                 func.flags.bits |= FnFlags::IS_UNSAFE;
600                             }
601                             func.flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
602                             func_id.into()
603                         }
604                         ast::ExternItem::Static(ast) => {
605                             let statik = self.lower_static(&ast)?;
606                             self.data().statics[statik.index].is_extern = true;
607                             statik.into()
608                         }
609                         ast::ExternItem::TypeAlias(ty) => {
610                             let foreign_ty = self.lower_type_alias(&ty)?;
611                             self.data().type_aliases[foreign_ty.index].is_extern = true;
612                             foreign_ty.into()
613                         }
614                         ast::ExternItem::MacroCall(call) => {
615                             // FIXME: we need some way of tracking that the macro call is in an
616                             // extern block
617                             self.lower_macro_call(&call)?.into()
618                         }
619                     };
620                     self.add_attrs(id.into(), attrs);
621                     Some(id)
622                 })
623                 .collect()
624         });
625
626         let res = ExternBlock { abi, ast_id, children };
627         id(self.data().extern_blocks.alloc(res))
628     }
629
630     /// Lowers generics defined on `node` and collects inner items defined within.
631     fn lower_generic_params_and_inner_items(
632         &mut self,
633         owner: GenericsOwner<'_>,
634         node: &impl ast::GenericParamsOwner,
635     ) -> Interned<GenericParams> {
636         // Generics are part of item headers and may contain inner items we need to collect.
637         if let Some(params) = node.generic_param_list() {
638             self.collect_inner_items(params.syntax());
639         }
640         if let Some(clause) = node.where_clause() {
641             self.collect_inner_items(clause.syntax());
642         }
643
644         self.lower_generic_params(owner, node)
645     }
646
647     fn lower_generic_params(
648         &mut self,
649         owner: GenericsOwner<'_>,
650         node: &impl ast::GenericParamsOwner,
651     ) -> Interned<GenericParams> {
652         let mut sm = &mut Default::default();
653         let mut generics = GenericParams::default();
654         match owner {
655             GenericsOwner::Function(func) => {
656                 generics.fill(&self.body_ctx, sm, node);
657                 // lower `impl Trait` in arguments
658                 for id in func.params.clone() {
659                     if let Param::Normal(ty) = &self.data().params[id] {
660                         generics.fill_implicit_impl_trait_args(ty);
661                     }
662                 }
663             }
664             GenericsOwner::Struct
665             | GenericsOwner::Enum
666             | GenericsOwner::Union
667             | GenericsOwner::TypeAlias => {
668                 generics.fill(&self.body_ctx, sm, node);
669             }
670             GenericsOwner::Trait(trait_def) => {
671                 // traits get the Self type as an implicit first type parameter
672                 let self_param_id = generics.types.alloc(TypeParamData {
673                     name: Some(name![Self]),
674                     default: None,
675                     provenance: TypeParamProvenance::TraitSelf,
676                 });
677                 sm.type_params.insert(self_param_id, Either::Right(trait_def.clone()));
678                 // add super traits as bounds on Self
679                 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
680                 let self_param = TypeRef::Path(name![Self].into());
681                 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
682                 generics.fill(&self.body_ctx, &mut sm, node);
683             }
684             GenericsOwner::Impl => {
685                 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
686                 // type-parameter, but rather is a type-alias for impl's target
687                 // type, so this is handled by the resolver.
688                 generics.fill(&self.body_ctx, &mut sm, node);
689             }
690         }
691
692         generics.shrink_to_fit();
693         Interned::new(generics)
694     }
695
696     fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<Interned<TypeBound>> {
697         match node.type_bound_list() {
698             Some(bound_list) => bound_list
699                 .bounds()
700                 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
701                 .collect(),
702             None => Vec::new(),
703         }
704     }
705
706     fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
707         let vis = match self.forced_visibility {
708             Some(vis) => return vis,
709             None => RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), &self.hygiene),
710         };
711
712         self.data().vis.alloc(vis)
713     }
714
715     fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
716         let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
717         Some(Interned::new(trait_ref))
718     }
719
720     fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
721         let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
722         Interned::new(tyref)
723     }
724
725     fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
726         match type_ref.map(|ty| self.lower_type_ref(&ty)) {
727             Some(it) => it,
728             None => Interned::new(TypeRef::Error),
729         }
730     }
731
732     /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
733     fn with_inherited_visibility<R>(
734         &mut self,
735         vis: RawVisibilityId,
736         f: impl FnOnce(&mut Self) -> R,
737     ) -> R {
738         let old = mem::replace(&mut self.forced_visibility, Some(vis));
739         let res = f(self);
740         self.forced_visibility = old;
741         res
742     }
743
744     fn next_field_idx(&self) -> Idx<Field> {
745         Idx::from_raw(RawIdx::from(
746             self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
747         ))
748     }
749     fn next_variant_idx(&self) -> Idx<Variant> {
750         Idx::from_raw(RawIdx::from(
751             self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
752         ))
753     }
754     fn next_param_idx(&self) -> Idx<Param> {
755         Idx::from_raw(RawIdx::from(
756             self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
757         ))
758     }
759 }
760
761 fn desugar_future_path(orig: TypeRef) -> Path {
762     let path = path![core::future::Future];
763     let mut generic_args: Vec<_> =
764         std::iter::repeat(None).take(path.segments().len() - 1).collect();
765     let mut last = GenericArgs::empty();
766     let binding =
767         AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
768     last.bindings.push(binding);
769     generic_args.push(Some(Interned::new(last)));
770
771     Path::from_known_path(path, generic_args)
772 }
773
774 enum GenericsOwner<'a> {
775     /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
776     /// position.
777     Function(&'a Function),
778     Struct,
779     Enum,
780     Union,
781     /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
782     Trait(&'a ast::Trait),
783     TypeAlias,
784     Impl,
785 }
786
787 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
788 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
789     // Should be kept in sync with https://github.com/rust-lang/rust/blob/c6e4db620a7d2f569f11dcab627430921ea8aacf/compiler/rustc_typeck/src/check/intrinsic.rs#L68
790     ![
791         known::abort,
792         known::min_align_of,
793         known::needs_drop,
794         known::caller_location,
795         known::size_of_val,
796         known::min_align_of_val,
797         known::add_with_overflow,
798         known::sub_with_overflow,
799         known::mul_with_overflow,
800         known::wrapping_add,
801         known::wrapping_sub,
802         known::wrapping_mul,
803         known::saturating_add,
804         known::saturating_sub,
805         known::rotate_left,
806         known::rotate_right,
807         known::ctpop,
808         known::ctlz,
809         known::cttz,
810         known::bswap,
811         known::bitreverse,
812         known::discriminant_value,
813         known::type_id,
814         known::likely,
815         known::unlikely,
816         known::ptr_guaranteed_eq,
817         known::ptr_guaranteed_ne,
818         known::minnumf32,
819         known::minnumf64,
820         known::maxnumf32,
821         known::rustc_peek,
822         known::maxnumf64,
823         known::type_name,
824         known::variant_count,
825     ]
826     .contains(name)
827 }
828
829 fn lower_abi(abi: ast::Abi) -> Interned<str> {
830     // FIXME: Abi::abi() -> Option<SyntaxToken>?
831     match abi.syntax().last_token() {
832         Some(tok) if tok.kind() == SyntaxKind::STRING => {
833             // FIXME: Better way to unescape?
834             Interned::new_str(tok.text().trim_matches('"'))
835         }
836         _ => {
837             // `extern` default to be `extern "C"`.
838             Interned::new_str("C")
839         }
840     }
841 }
842
843 struct UseTreeLowering<'a> {
844     db: &'a dyn DefDatabase,
845     hygiene: &'a Hygiene,
846     mapping: Arena<ast::UseTree>,
847 }
848
849 impl UseTreeLowering<'_> {
850     fn lower_use_tree(&mut self, tree: ast::UseTree) -> Option<UseTree> {
851         if let Some(use_tree_list) = tree.use_tree_list() {
852             let prefix = match tree.path() {
853                 // E.g. use something::{{{inner}}};
854                 None => None,
855                 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
856                 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
857                 Some(path) => {
858                     match ModPath::from_src(self.db, path, self.hygiene) {
859                         Some(it) => Some(it),
860                         None => return None, // FIXME: report errors somewhere
861                     }
862                 }
863             };
864
865             let list =
866                 use_tree_list.use_trees().filter_map(|tree| self.lower_use_tree(tree)).collect();
867
868             Some(
869                 self.use_tree(
870                     UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
871                     tree,
872                 ),
873             )
874         } else {
875             let is_glob = tree.star_token().is_some();
876             let path = match tree.path() {
877                 Some(path) => Some(ModPath::from_src(self.db, path, self.hygiene)?),
878                 None => None,
879             };
880             let alias = tree.rename().map(|a| {
881                 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
882             });
883             if alias.is_some() && is_glob {
884                 return None;
885             }
886
887             match (path, alias, is_glob) {
888                 (path, None, true) => {
889                     if path.is_none() {
890                         cov_mark::hit!(glob_enum_group);
891                     }
892                     Some(self.use_tree(UseTreeKind::Glob { path: path.map(Interned::new) }, tree))
893                 }
894                 // Globs can't be renamed
895                 (_, Some(_), true) | (None, None, false) => None,
896                 // `bla::{ as Name}` is invalid
897                 (None, Some(_), false) => None,
898                 (Some(path), alias, false) => Some(
899                     self.use_tree(UseTreeKind::Single { path: Interned::new(path), alias }, tree),
900                 ),
901             }
902         }
903     }
904
905     fn use_tree(&mut self, kind: UseTreeKind, ast: ast::UseTree) -> UseTree {
906         let index = self.mapping.alloc(ast);
907         UseTree { index, kind }
908     }
909 }
910
911 pub(super) fn lower_use_tree(
912     db: &dyn DefDatabase,
913     hygiene: &Hygiene,
914     tree: ast::UseTree,
915 ) -> Option<(UseTree, Arena<ast::UseTree>)> {
916     let mut lowering = UseTreeLowering { db, hygiene, mapping: Arena::new() };
917     let tree = lowering.lower_use_tree(tree)?;
918     Some((tree, lowering.mapping))
919 }