]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_tree/lower.rs
hir_ty: use async ret type for inference inside async bodies
[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.clone());
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 = match &enum_.variant_list() {
280             Some(variant_list) => self.lower_variants(variant_list),
281             None => IdRange::new(self.next_variant_idx()..self.next_variant_idx()),
282         };
283         let ast_id = self.source_ast_id_map.ast_id(enum_);
284         let res = Enum { name, visibility, generic_params, variants, ast_id };
285         Some(id(self.data().enums.alloc(res)))
286     }
287
288     fn lower_variants(&mut self, variants: &ast::VariantList) -> IdRange<Variant> {
289         let start = self.next_variant_idx();
290         for variant in variants.variants() {
291             if let Some(data) = self.lower_variant(&variant) {
292                 let idx = self.data().variants.alloc(data);
293                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, &self.hygiene));
294             }
295         }
296         let end = self.next_variant_idx();
297         IdRange::new(start..end)
298     }
299
300     fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
301         let name = variant.name()?.as_name();
302         let fields = self.lower_fields(&variant.kind());
303         let res = Variant { name, fields };
304         Some(res)
305     }
306
307     fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
308         let visibility = self.lower_visibility(func);
309         let name = func.name()?.as_name();
310
311         let mut has_self_param = false;
312         let start_param = self.next_param_idx();
313         if let Some(param_list) = func.param_list() {
314             if let Some(self_param) = param_list.self_param() {
315                 let self_type = match self_param.ty() {
316                     Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
317                     None => {
318                         let self_type = TypeRef::Path(name![Self].into());
319                         match self_param.kind() {
320                             ast::SelfParamKind::Owned => self_type,
321                             ast::SelfParamKind::Ref => TypeRef::Reference(
322                                 Box::new(self_type),
323                                 self_param.lifetime().as_ref().map(LifetimeRef::new),
324                                 Mutability::Shared,
325                             ),
326                             ast::SelfParamKind::MutRef => TypeRef::Reference(
327                                 Box::new(self_type),
328                                 self_param.lifetime().as_ref().map(LifetimeRef::new),
329                                 Mutability::Mut,
330                             ),
331                         }
332                     }
333                 };
334                 let ty = Interned::new(self_type);
335                 let idx = self.data().params.alloc(Param::Normal(ty));
336                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, &self.hygiene));
337                 has_self_param = true;
338             }
339             for param in param_list.params() {
340                 let idx = match param.dotdotdot_token() {
341                     Some(_) => self.data().params.alloc(Param::Varargs),
342                     None => {
343                         let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
344                         let ty = Interned::new(type_ref);
345                         self.data().params.alloc(Param::Normal(ty))
346                     }
347                 };
348                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &param, &self.hygiene));
349             }
350         }
351         let end_param = self.next_param_idx();
352         let params = IdRange::new(start_param..end_param);
353
354         let ret_type = match func.ret_type().and_then(|rt| rt.ty()) {
355             Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
356             _ => TypeRef::unit(),
357         };
358
359         let (ret_type, async_ret_type) = if func.async_token().is_some() {
360             let async_ret_type = ret_type.clone();
361             let future_impl = desugar_future_path(ret_type);
362             let ty_bound = Interned::new(TypeBound::Path(future_impl));
363             (TypeRef::ImplTrait(vec![ty_bound]), Some(async_ret_type))
364         } else {
365             (ret_type, None)
366         };
367
368         let abi = func.abi().map(lower_abi);
369
370         let ast_id = self.source_ast_id_map.ast_id(func);
371
372         let mut flags = FnFlags::default();
373         if func.body().is_some() {
374             flags.bits |= FnFlags::HAS_BODY;
375         }
376         if has_self_param {
377             flags.bits |= FnFlags::HAS_SELF_PARAM;
378         }
379         if func.default_token().is_some() {
380             flags.bits |= FnFlags::IS_DEFAULT;
381         }
382         if func.const_token().is_some() {
383             flags.bits |= FnFlags::IS_CONST;
384         }
385         if func.async_token().is_some() {
386             flags.bits |= FnFlags::IS_ASYNC;
387         }
388         if func.unsafe_token().is_some() {
389             flags.bits |= FnFlags::IS_UNSAFE;
390         }
391
392         let mut res = Function {
393             name,
394             visibility,
395             generic_params: Interned::new(GenericParams::default()),
396             abi,
397             params,
398             ret_type: Interned::new(ret_type),
399             async_ret_type: async_ret_type.map(Interned::new),
400             ast_id,
401             flags,
402         };
403         res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
404
405         Some(id(self.data().functions.alloc(res)))
406     }
407
408     fn lower_type_alias(
409         &mut self,
410         type_alias: &ast::TypeAlias,
411     ) -> Option<FileItemTreeId<TypeAlias>> {
412         let name = type_alias.name()?.as_name();
413         let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
414         let visibility = self.lower_visibility(type_alias);
415         let bounds = self.lower_type_bounds(type_alias);
416         let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
417         let ast_id = self.source_ast_id_map.ast_id(type_alias);
418         let res = TypeAlias {
419             name,
420             visibility,
421             bounds: bounds.into_boxed_slice(),
422             generic_params,
423             type_ref,
424             ast_id,
425             is_extern: false,
426         };
427         Some(id(self.data().type_aliases.alloc(res)))
428     }
429
430     fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
431         let name = static_.name()?.as_name();
432         let type_ref = self.lower_type_ref_opt(static_.ty());
433         let visibility = self.lower_visibility(static_);
434         let mutable = static_.mut_token().is_some();
435         let ast_id = self.source_ast_id_map.ast_id(static_);
436         let res = Static { name, visibility, mutable, type_ref, ast_id, is_extern: false };
437         Some(id(self.data().statics.alloc(res)))
438     }
439
440     fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
441         let name = konst.name().map(|it| it.as_name());
442         let type_ref = self.lower_type_ref_opt(konst.ty());
443         let visibility = self.lower_visibility(konst);
444         let ast_id = self.source_ast_id_map.ast_id(konst);
445         let res = Const { name, visibility, type_ref, ast_id };
446         id(self.data().consts.alloc(res))
447     }
448
449     fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
450         let name = module.name()?.as_name();
451         let visibility = self.lower_visibility(module);
452         let kind = if module.semicolon_token().is_some() {
453             ModKind::Outline {}
454         } else {
455             ModKind::Inline {
456                 items: module
457                     .item_list()
458                     .map(|list| {
459                         list.items().flat_map(|item| self.lower_mod_item(&item, false)).collect()
460                     })
461                     .unwrap_or_else(|| {
462                         cov_mark::hit!(name_res_works_for_broken_modules);
463                         Box::new([]) as Box<[_]>
464                     }),
465             }
466         };
467         let ast_id = self.source_ast_id_map.ast_id(module);
468         let res = Mod { name, visibility, kind, ast_id };
469         Some(id(self.data().mods.alloc(res)))
470     }
471
472     fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
473         let name = trait_def.name()?.as_name();
474         let visibility = self.lower_visibility(trait_def);
475         let generic_params =
476             self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
477         let is_auto = trait_def.auto_token().is_some();
478         let is_unsafe = trait_def.unsafe_token().is_some();
479         let items = trait_def.assoc_item_list().map(|list| {
480             let db = self.db;
481             self.with_inherited_visibility(visibility, |this| {
482                 list.assoc_items()
483                     .filter_map(|item| {
484                         let attrs = RawAttrs::new(db, &item, &this.hygiene);
485                         this.collect_inner_items(item.syntax());
486                         this.lower_assoc_item(&item).map(|item| {
487                             this.add_attrs(ModItem::from(item).into(), attrs);
488                             item
489                         })
490                     })
491                     .collect()
492             })
493         });
494         let ast_id = self.source_ast_id_map.ast_id(trait_def);
495         let res = Trait {
496             name,
497             visibility,
498             generic_params,
499             is_auto,
500             is_unsafe,
501             items: items.unwrap_or_default(),
502             ast_id,
503         };
504         Some(id(self.data().traits.alloc(res)))
505     }
506
507     fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
508         let generic_params =
509             self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
510         // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
511         // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
512         // equals itself.
513         let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
514         let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
515         let is_negative = impl_def.excl_token().is_some();
516
517         // We cannot use `assoc_items()` here as that does not include macro calls.
518         let items = impl_def
519             .assoc_item_list()
520             .into_iter()
521             .flat_map(|it| it.assoc_items())
522             .filter_map(|item| {
523                 self.collect_inner_items(item.syntax());
524                 let assoc = self.lower_assoc_item(&item)?;
525                 let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
526                 self.add_attrs(ModItem::from(assoc).into(), attrs);
527                 Some(assoc)
528             })
529             .collect();
530         let ast_id = self.source_ast_id_map.ast_id(impl_def);
531         let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
532         Some(id(self.data().impls.alloc(res)))
533     }
534
535     fn lower_use(&mut self, use_item: &ast::Use) -> Option<FileItemTreeId<Import>> {
536         let visibility = self.lower_visibility(use_item);
537         let ast_id = self.source_ast_id_map.ast_id(use_item);
538         let (use_tree, _) = lower_use_tree(self.db, &self.hygiene, use_item.use_tree()?)?;
539
540         let res = Import { visibility, ast_id, use_tree };
541         Some(id(self.data().imports.alloc(res)))
542     }
543
544     fn lower_extern_crate(
545         &mut self,
546         extern_crate: &ast::ExternCrate,
547     ) -> Option<FileItemTreeId<ExternCrate>> {
548         let name = extern_crate.name_ref()?.as_name();
549         let alias = extern_crate.rename().map(|a| {
550             a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
551         });
552         let visibility = self.lower_visibility(extern_crate);
553         let ast_id = self.source_ast_id_map.ast_id(extern_crate);
554
555         let res = ExternCrate { name, alias, visibility, ast_id };
556         Some(id(self.data().extern_crates.alloc(res)))
557     }
558
559     fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
560         let path = Interned::new(ModPath::from_src(self.db, m.path()?, &self.hygiene)?);
561         let ast_id = self.source_ast_id_map.ast_id(m);
562         let fragment = hir_expand::to_fragment_kind(m);
563         let res = MacroCall { path, ast_id, fragment };
564         Some(id(self.data().macro_calls.alloc(res)))
565     }
566
567     fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
568         let name = m.name().map(|it| it.as_name())?;
569         let ast_id = self.source_ast_id_map.ast_id(m);
570
571         let res = MacroRules { name, ast_id };
572         Some(id(self.data().macro_rules.alloc(res)))
573     }
574
575     fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
576         let name = m.name().map(|it| it.as_name())?;
577
578         let ast_id = self.source_ast_id_map.ast_id(m);
579         let visibility = self.lower_visibility(m);
580
581         let res = MacroDef { name, ast_id, visibility };
582         Some(id(self.data().macro_defs.alloc(res)))
583     }
584
585     fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> FileItemTreeId<ExternBlock> {
586         let ast_id = self.source_ast_id_map.ast_id(block);
587         let abi = block.abi().map(lower_abi);
588         let children: Box<[_]> = block.extern_item_list().map_or(Box::new([]), |list| {
589             list.extern_items()
590                 .filter_map(|item| {
591                     self.collect_inner_items(item.syntax());
592                     let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
593                     let id: ModItem = match item {
594                         ast::ExternItem::Fn(ast) => {
595                             let func_id = self.lower_function(&ast)?;
596                             let func = &mut self.data().functions[func_id.index];
597                             if is_intrinsic_fn_unsafe(&func.name) {
598                                 func.flags.bits |= FnFlags::IS_UNSAFE;
599                             }
600                             func.flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
601                             func_id.into()
602                         }
603                         ast::ExternItem::Static(ast) => {
604                             let statik = self.lower_static(&ast)?;
605                             self.data().statics[statik.index].is_extern = true;
606                             statik.into()
607                         }
608                         ast::ExternItem::TypeAlias(ty) => {
609                             let foreign_ty = self.lower_type_alias(&ty)?;
610                             self.data().type_aliases[foreign_ty.index].is_extern = true;
611                             foreign_ty.into()
612                         }
613                         ast::ExternItem::MacroCall(call) => {
614                             // FIXME: we need some way of tracking that the macro call is in an
615                             // extern block
616                             self.lower_macro_call(&call)?.into()
617                         }
618                     };
619                     self.add_attrs(id.into(), attrs);
620                     Some(id)
621                 })
622                 .collect()
623         });
624
625         let res = ExternBlock { abi, ast_id, children };
626         id(self.data().extern_blocks.alloc(res))
627     }
628
629     /// Lowers generics defined on `node` and collects inner items defined within.
630     fn lower_generic_params_and_inner_items(
631         &mut self,
632         owner: GenericsOwner<'_>,
633         node: &impl ast::GenericParamsOwner,
634     ) -> Interned<GenericParams> {
635         // Generics are part of item headers and may contain inner items we need to collect.
636         if let Some(params) = node.generic_param_list() {
637             self.collect_inner_items(params.syntax());
638         }
639         if let Some(clause) = node.where_clause() {
640             self.collect_inner_items(clause.syntax());
641         }
642
643         self.lower_generic_params(owner, node)
644     }
645
646     fn lower_generic_params(
647         &mut self,
648         owner: GenericsOwner<'_>,
649         node: &impl ast::GenericParamsOwner,
650     ) -> Interned<GenericParams> {
651         let mut sm = &mut Default::default();
652         let mut generics = GenericParams::default();
653         match owner {
654             GenericsOwner::Function(func) => {
655                 generics.fill(&self.body_ctx, sm, node);
656                 // lower `impl Trait` in arguments
657                 for id in func.params.clone() {
658                     if let Param::Normal(ty) = &self.data().params[id] {
659                         generics.fill_implicit_impl_trait_args(ty);
660                     }
661                 }
662             }
663             GenericsOwner::Struct
664             | GenericsOwner::Enum
665             | GenericsOwner::Union
666             | GenericsOwner::TypeAlias => {
667                 generics.fill(&self.body_ctx, sm, node);
668             }
669             GenericsOwner::Trait(trait_def) => {
670                 // traits get the Self type as an implicit first type parameter
671                 let self_param_id = generics.types.alloc(TypeParamData {
672                     name: Some(name![Self]),
673                     default: None,
674                     provenance: TypeParamProvenance::TraitSelf,
675                 });
676                 sm.type_params.insert(self_param_id, Either::Left(trait_def.clone()));
677                 // add super traits as bounds on Self
678                 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
679                 let self_param = TypeRef::Path(name![Self].into());
680                 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
681                 generics.fill(&self.body_ctx, &mut sm, node);
682             }
683             GenericsOwner::Impl => {
684                 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
685                 // type-parameter, but rather is a type-alias for impl's target
686                 // type, so this is handled by the resolver.
687                 generics.fill(&self.body_ctx, &mut sm, node);
688             }
689         }
690
691         generics.shrink_to_fit();
692         Interned::new(generics)
693     }
694
695     fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<Interned<TypeBound>> {
696         match node.type_bound_list() {
697             Some(bound_list) => bound_list
698                 .bounds()
699                 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
700                 .collect(),
701             None => Vec::new(),
702         }
703     }
704
705     fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
706         let vis = match self.forced_visibility {
707             Some(vis) => return vis,
708             None => RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), &self.hygiene),
709         };
710
711         self.data().vis.alloc(vis)
712     }
713
714     fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
715         let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
716         Some(Interned::new(trait_ref))
717     }
718
719     fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
720         let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
721         Interned::new(tyref)
722     }
723
724     fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
725         match type_ref.map(|ty| self.lower_type_ref(&ty)) {
726             Some(it) => it,
727             None => Interned::new(TypeRef::Error),
728         }
729     }
730
731     /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
732     fn with_inherited_visibility<R>(
733         &mut self,
734         vis: RawVisibilityId,
735         f: impl FnOnce(&mut Self) -> R,
736     ) -> R {
737         let old = mem::replace(&mut self.forced_visibility, Some(vis));
738         let res = f(self);
739         self.forced_visibility = old;
740         res
741     }
742
743     fn next_field_idx(&self) -> Idx<Field> {
744         Idx::from_raw(RawIdx::from(
745             self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
746         ))
747     }
748     fn next_variant_idx(&self) -> Idx<Variant> {
749         Idx::from_raw(RawIdx::from(
750             self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
751         ))
752     }
753     fn next_param_idx(&self) -> Idx<Param> {
754         Idx::from_raw(RawIdx::from(
755             self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
756         ))
757     }
758 }
759
760 fn desugar_future_path(orig: TypeRef) -> Path {
761     let path = path![core::future::Future];
762     let mut generic_args: Vec<_> =
763         std::iter::repeat(None).take(path.segments().len() - 1).collect();
764     let mut last = GenericArgs::empty();
765     let binding =
766         AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
767     last.bindings.push(binding);
768     generic_args.push(Some(Interned::new(last)));
769
770     Path::from_known_path(path, generic_args)
771 }
772
773 enum GenericsOwner<'a> {
774     /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
775     /// position.
776     Function(&'a Function),
777     Struct,
778     Enum,
779     Union,
780     /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
781     Trait(&'a ast::Trait),
782     TypeAlias,
783     Impl,
784 }
785
786 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
787 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
788     // Should be kept in sync with https://github.com/rust-lang/rust/blob/c6e4db620a7d2f569f11dcab627430921ea8aacf/compiler/rustc_typeck/src/check/intrinsic.rs#L68
789     ![
790         known::abort,
791         known::min_align_of,
792         known::needs_drop,
793         known::caller_location,
794         known::size_of_val,
795         known::min_align_of_val,
796         known::add_with_overflow,
797         known::sub_with_overflow,
798         known::mul_with_overflow,
799         known::wrapping_add,
800         known::wrapping_sub,
801         known::wrapping_mul,
802         known::saturating_add,
803         known::saturating_sub,
804         known::rotate_left,
805         known::rotate_right,
806         known::ctpop,
807         known::ctlz,
808         known::cttz,
809         known::bswap,
810         known::bitreverse,
811         known::discriminant_value,
812         known::type_id,
813         known::likely,
814         known::unlikely,
815         known::ptr_guaranteed_eq,
816         known::ptr_guaranteed_ne,
817         known::minnumf32,
818         known::minnumf64,
819         known::maxnumf32,
820         known::rustc_peek,
821         known::maxnumf64,
822         known::type_name,
823         known::variant_count,
824     ]
825     .contains(&name)
826 }
827
828 fn lower_abi(abi: ast::Abi) -> Interned<str> {
829     // FIXME: Abi::abi() -> Option<SyntaxToken>?
830     match abi.syntax().last_token() {
831         Some(tok) if tok.kind() == SyntaxKind::STRING => {
832             // FIXME: Better way to unescape?
833             Interned::new_str(tok.text().trim_matches('"'))
834         }
835         _ => {
836             // `extern` default to be `extern "C"`.
837             Interned::new_str("C")
838         }
839     }
840 }
841
842 struct UseTreeLowering<'a> {
843     db: &'a dyn DefDatabase,
844     hygiene: &'a Hygiene,
845     mapping: Arena<ast::UseTree>,
846 }
847
848 impl UseTreeLowering<'_> {
849     fn lower_use_tree(&mut self, tree: ast::UseTree) -> Option<UseTree> {
850         if let Some(use_tree_list) = tree.use_tree_list() {
851             let prefix = match tree.path() {
852                 // E.g. use something::{{{inner}}};
853                 None => None,
854                 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
855                 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
856                 Some(path) => {
857                     match ModPath::from_src(self.db, path, &self.hygiene) {
858                         Some(it) => Some(it),
859                         None => return None, // FIXME: report errors somewhere
860                     }
861                 }
862             };
863
864             let list =
865                 use_tree_list.use_trees().filter_map(|tree| self.lower_use_tree(tree)).collect();
866
867             Some(
868                 self.use_tree(
869                     UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
870                     tree,
871                 ),
872             )
873         } else {
874             let is_glob = tree.star_token().is_some();
875             let path = match tree.path() {
876                 Some(path) => Some(ModPath::from_src(self.db, path, &self.hygiene)?),
877                 None => None,
878             };
879             let alias = tree.rename().map(|a| {
880                 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
881             });
882             if alias.is_some() && is_glob {
883                 return None;
884             }
885
886             match (path, alias, is_glob) {
887                 (path, None, true) => {
888                     if path.is_none() {
889                         cov_mark::hit!(glob_enum_group);
890                     }
891                     Some(self.use_tree(UseTreeKind::Glob { path: path.map(Interned::new) }, tree))
892                 }
893                 // Globs can't be renamed
894                 (_, Some(_), true) | (None, None, false) => None,
895                 // `bla::{ as Name}` is invalid
896                 (None, Some(_), false) => None,
897                 (Some(path), alias, false) => Some(
898                     self.use_tree(UseTreeKind::Single { path: Interned::new(path), alias }, tree),
899                 ),
900             }
901         }
902     }
903
904     fn use_tree(&mut self, kind: UseTreeKind, ast: ast::UseTree) -> UseTree {
905         let index = self.mapping.alloc(ast);
906         UseTree { index, kind }
907     }
908 }
909
910 pub(super) fn lower_use_tree(
911     db: &dyn DefDatabase,
912     hygiene: &Hygiene,
913     tree: ast::UseTree,
914 ) -> Option<(UseTree, Arena<ast::UseTree>)> {
915     let mut lowering = UseTreeLowering { db, hygiene, mapping: Arena::new() };
916     let tree = lowering.lower_use_tree(tree)?;
917     Some((tree, lowering.mapping))
918 }