]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/item_tree/lower.rs
Rollup merge of #98801 - joshtriplett:file-create-new, r=thomcc
[rust.git] / src / tools / rust-analyzer / crates / hir-def / src / item_tree / lower.rs
1 //! AST -> `ItemTree` lowering code.
2
3 use std::{collections::hash_map::Entry, sync::Arc};
4
5 use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, HirFileId};
6 use syntax::ast::{self, HasModuleItem};
7
8 use crate::{
9     generics::{GenericParams, TypeParamData, TypeParamProvenance},
10     type_ref::{LifetimeRef, TraitBoundModifier, TraitRef},
11 };
12
13 use super::*;
14
15 fn id<N: ItemTreeNode>(index: Idx<N>) -> FileItemTreeId<N> {
16     FileItemTreeId { index, _p: PhantomData }
17 }
18
19 pub(super) struct Ctx<'a> {
20     db: &'a dyn DefDatabase,
21     tree: ItemTree,
22     source_ast_id_map: Arc<AstIdMap>,
23     body_ctx: crate::body::LowerCtx<'a>,
24 }
25
26 impl<'a> Ctx<'a> {
27     pub(super) fn new(db: &'a dyn DefDatabase, file: HirFileId) -> Self {
28         Self {
29             db,
30             tree: ItemTree::default(),
31             source_ast_id_map: db.ast_id_map(file),
32             body_ctx: crate::body::LowerCtx::new(db, file),
33         }
34     }
35
36     pub(super) fn hygiene(&self) -> &Hygiene {
37         self.body_ctx.hygiene()
38     }
39
40     pub(super) fn lower_module_items(mut self, item_owner: &dyn HasModuleItem) -> ItemTree {
41         self.tree.top_level =
42             item_owner.items().flat_map(|item| self.lower_mod_item(&item)).collect();
43         self.tree
44     }
45
46     pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
47         self.tree.top_level = stmts
48             .statements()
49             .filter_map(|stmt| {
50                 match stmt {
51                     ast::Stmt::Item(item) => Some(item),
52                     // Macro calls can be both items and expressions. The syntax library always treats
53                     // them as expressions here, so we undo that.
54                     ast::Stmt::ExprStmt(es) => match es.expr()? {
55                         ast::Expr::MacroExpr(expr) => {
56                             cov_mark::hit!(macro_call_in_macro_stmts_is_added_to_item_tree);
57                             Some(expr.macro_call()?.into())
58                         }
59                         _ => None,
60                     },
61                     _ => None,
62                 }
63             })
64             .flat_map(|item| self.lower_mod_item(&item))
65             .collect();
66
67         if let Some(ast::Expr::MacroExpr(tail_macro)) = stmts.expr() {
68             if let Some(call) = tail_macro.macro_call() {
69                 cov_mark::hit!(macro_stmt_with_trailing_macro_expr);
70                 if let Some(mod_item) = self.lower_mod_item(&call.into()) {
71                     self.tree.top_level.push(mod_item);
72                 }
73             }
74         }
75
76         self.tree
77     }
78
79     pub(super) fn lower_block(mut self, block: &ast::BlockExpr) -> ItemTree {
80         self.tree.top_level = block
81             .statements()
82             .filter_map(|stmt| match stmt {
83                 ast::Stmt::Item(item) => self.lower_mod_item(&item),
84                 // Macro calls can be both items and expressions. The syntax library always treats
85                 // them as expressions here, so we undo that.
86                 ast::Stmt::ExprStmt(es) => match es.expr()? {
87                     ast::Expr::MacroExpr(expr) => self.lower_mod_item(&expr.macro_call()?.into()),
88                     _ => None,
89                 },
90                 _ => None,
91             })
92             .collect();
93
94         self.tree
95     }
96
97     fn data(&mut self) -> &mut ItemTreeData {
98         self.tree.data_mut()
99     }
100
101     fn lower_mod_item(&mut self, item: &ast::Item) -> Option<ModItem> {
102         let attrs = RawAttrs::new(self.db, item, self.hygiene());
103         let item: ModItem = match item {
104             ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
105             ast::Item::Union(ast) => self.lower_union(ast)?.into(),
106             ast::Item::Enum(ast) => self.lower_enum(ast)?.into(),
107             ast::Item::Fn(ast) => self.lower_function(ast)?.into(),
108             ast::Item::TypeAlias(ast) => self.lower_type_alias(ast)?.into(),
109             ast::Item::Static(ast) => self.lower_static(ast)?.into(),
110             ast::Item::Const(ast) => self.lower_const(ast).into(),
111             ast::Item::Module(ast) => self.lower_module(ast)?.into(),
112             ast::Item::Trait(ast) => self.lower_trait(ast)?.into(),
113             ast::Item::Impl(ast) => self.lower_impl(ast)?.into(),
114             ast::Item::Use(ast) => self.lower_use(ast)?.into(),
115             ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast)?.into(),
116             ast::Item::MacroCall(ast) => self.lower_macro_call(ast)?.into(),
117             ast::Item::MacroRules(ast) => self.lower_macro_rules(ast)?.into(),
118             ast::Item::MacroDef(ast) => self.lower_macro_def(ast)?.into(),
119             ast::Item::ExternBlock(ast) => self.lower_extern_block(ast).into(),
120         };
121
122         self.add_attrs(item.into(), attrs);
123
124         Some(item)
125     }
126
127     fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) {
128         match self.tree.attrs.entry(item) {
129             Entry::Occupied(mut entry) => {
130                 *entry.get_mut() = entry.get().merge(attrs);
131             }
132             Entry::Vacant(entry) => {
133                 entry.insert(attrs);
134             }
135         }
136     }
137
138     fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
139         match item {
140             ast::AssocItem::Fn(ast) => self.lower_function(ast).map(Into::into),
141             ast::AssocItem::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
142             ast::AssocItem::Const(ast) => Some(self.lower_const(ast).into()),
143             ast::AssocItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
144         }
145     }
146
147     fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<FileItemTreeId<Struct>> {
148         let visibility = self.lower_visibility(strukt);
149         let name = strukt.name()?.as_name();
150         let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
151         let fields = self.lower_fields(&strukt.kind());
152         let ast_id = self.source_ast_id_map.ast_id(strukt);
153         let res = Struct { name, visibility, generic_params, fields, ast_id };
154         Some(id(self.data().structs.alloc(res)))
155     }
156
157     fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
158         match strukt_kind {
159             ast::StructKind::Record(it) => {
160                 let range = self.lower_record_fields(it);
161                 Fields::Record(range)
162             }
163             ast::StructKind::Tuple(it) => {
164                 let range = self.lower_tuple_fields(it);
165                 Fields::Tuple(range)
166             }
167             ast::StructKind::Unit => Fields::Unit,
168         }
169     }
170
171     fn lower_record_fields(&mut self, fields: &ast::RecordFieldList) -> IdxRange<Field> {
172         let start = self.next_field_idx();
173         for field in fields.fields() {
174             if let Some(data) = self.lower_record_field(&field) {
175                 let idx = self.data().fields.alloc(data);
176                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
177             }
178         }
179         let end = self.next_field_idx();
180         IdxRange::new(start..end)
181     }
182
183     fn lower_record_field(&mut self, field: &ast::RecordField) -> Option<Field> {
184         let name = field.name()?.as_name();
185         let visibility = self.lower_visibility(field);
186         let type_ref = self.lower_type_ref_opt(field.ty());
187         let res = Field { name, type_ref, visibility };
188         Some(res)
189     }
190
191     fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldList) -> IdxRange<Field> {
192         let start = self.next_field_idx();
193         for (i, field) in fields.fields().enumerate() {
194             let data = self.lower_tuple_field(i, &field);
195             let idx = self.data().fields.alloc(data);
196             self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
197         }
198         let end = self.next_field_idx();
199         IdxRange::new(start..end)
200     }
201
202     fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field {
203         let name = Name::new_tuple_field(idx);
204         let visibility = self.lower_visibility(field);
205         let type_ref = self.lower_type_ref_opt(field.ty());
206         Field { name, type_ref, visibility }
207     }
208
209     fn lower_union(&mut self, union: &ast::Union) -> Option<FileItemTreeId<Union>> {
210         let visibility = self.lower_visibility(union);
211         let name = union.name()?.as_name();
212         let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
213         let fields = match union.record_field_list() {
214             Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)),
215             None => Fields::Record(IdxRange::new(self.next_field_idx()..self.next_field_idx())),
216         };
217         let ast_id = self.source_ast_id_map.ast_id(union);
218         let res = Union { name, visibility, generic_params, fields, ast_id };
219         Some(id(self.data().unions.alloc(res)))
220     }
221
222     fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<FileItemTreeId<Enum>> {
223         let visibility = self.lower_visibility(enum_);
224         let name = enum_.name()?.as_name();
225         let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
226         let variants = match &enum_.variant_list() {
227             Some(variant_list) => self.lower_variants(variant_list),
228             None => IdxRange::new(self.next_variant_idx()..self.next_variant_idx()),
229         };
230         let ast_id = self.source_ast_id_map.ast_id(enum_);
231         let res = Enum { name, visibility, generic_params, variants, ast_id };
232         Some(id(self.data().enums.alloc(res)))
233     }
234
235     fn lower_variants(&mut self, variants: &ast::VariantList) -> IdxRange<Variant> {
236         let start = self.next_variant_idx();
237         for variant in variants.variants() {
238             if let Some(data) = self.lower_variant(&variant) {
239                 let idx = self.data().variants.alloc(data);
240                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, self.hygiene()));
241             }
242         }
243         let end = self.next_variant_idx();
244         IdxRange::new(start..end)
245     }
246
247     fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
248         let name = variant.name()?.as_name();
249         let fields = self.lower_fields(&variant.kind());
250         let res = Variant { name, fields };
251         Some(res)
252     }
253
254     fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
255         let visibility = self.lower_visibility(func);
256         let name = func.name()?.as_name();
257
258         let mut has_self_param = false;
259         let start_param = self.next_param_idx();
260         if let Some(param_list) = func.param_list() {
261             if let Some(self_param) = param_list.self_param() {
262                 let self_type = match self_param.ty() {
263                     Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
264                     None => {
265                         let self_type = TypeRef::Path(name![Self].into());
266                         match self_param.kind() {
267                             ast::SelfParamKind::Owned => self_type,
268                             ast::SelfParamKind::Ref => TypeRef::Reference(
269                                 Box::new(self_type),
270                                 self_param.lifetime().as_ref().map(LifetimeRef::new),
271                                 Mutability::Shared,
272                             ),
273                             ast::SelfParamKind::MutRef => TypeRef::Reference(
274                                 Box::new(self_type),
275                                 self_param.lifetime().as_ref().map(LifetimeRef::new),
276                                 Mutability::Mut,
277                             ),
278                         }
279                     }
280                 };
281                 let ty = Interned::new(self_type);
282                 let idx = self.data().params.alloc(Param::Normal(None, ty));
283                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, self.hygiene()));
284                 has_self_param = true;
285             }
286             for param in param_list.params() {
287                 let idx = match param.dotdotdot_token() {
288                     Some(_) => self.data().params.alloc(Param::Varargs),
289                     None => {
290                         let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
291                         let ty = Interned::new(type_ref);
292                         let mut pat = param.pat();
293                         // FIXME: This really shouldn't be here, in fact FunctionData/ItemTree's function shouldn't know about
294                         // pattern names at all
295                         let name = 'name: loop {
296                             match pat {
297                                 Some(ast::Pat::RefPat(ref_pat)) => pat = ref_pat.pat(),
298                                 Some(ast::Pat::IdentPat(ident)) => {
299                                     break 'name ident.name().map(|it| it.as_name())
300                                 }
301                                 _ => break 'name None,
302                             }
303                         };
304                         self.data().params.alloc(Param::Normal(name, ty))
305                     }
306                 };
307                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &param, self.hygiene()));
308             }
309         }
310         let end_param = self.next_param_idx();
311         let params = IdxRange::new(start_param..end_param);
312
313         let ret_type = match func.ret_type() {
314             Some(rt) => match rt.ty() {
315                 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
316                 None if rt.thin_arrow_token().is_some() => TypeRef::Error,
317                 None => TypeRef::unit(),
318             },
319             None => TypeRef::unit(),
320         };
321
322         let (ret_type, async_ret_type) = if func.async_token().is_some() {
323             let async_ret_type = ret_type.clone();
324             let future_impl = desugar_future_path(ret_type);
325             let ty_bound = Interned::new(TypeBound::Path(future_impl, TraitBoundModifier::None));
326             (TypeRef::ImplTrait(vec![ty_bound]), Some(async_ret_type))
327         } else {
328             (ret_type, None)
329         };
330
331         let abi = func.abi().map(lower_abi);
332
333         let ast_id = self.source_ast_id_map.ast_id(func);
334
335         let mut flags = FnFlags::default();
336         if func.body().is_some() {
337             flags |= FnFlags::HAS_BODY;
338         }
339         if has_self_param {
340             flags |= FnFlags::HAS_SELF_PARAM;
341         }
342         if func.default_token().is_some() {
343             flags |= FnFlags::HAS_DEFAULT_KW;
344         }
345         if func.const_token().is_some() {
346             flags |= FnFlags::HAS_CONST_KW;
347         }
348         if func.async_token().is_some() {
349             flags |= FnFlags::HAS_ASYNC_KW;
350         }
351         if func.unsafe_token().is_some() {
352             flags |= FnFlags::HAS_UNSAFE_KW;
353         }
354
355         let mut res = Function {
356             name,
357             visibility,
358             explicit_generic_params: Interned::new(GenericParams::default()),
359             abi,
360             params,
361             ret_type: Interned::new(ret_type),
362             async_ret_type: async_ret_type.map(Interned::new),
363             ast_id,
364             flags,
365         };
366         res.explicit_generic_params =
367             self.lower_generic_params(GenericsOwner::Function(&res), func);
368
369         Some(id(self.data().functions.alloc(res)))
370     }
371
372     fn lower_type_alias(
373         &mut self,
374         type_alias: &ast::TypeAlias,
375     ) -> Option<FileItemTreeId<TypeAlias>> {
376         let name = type_alias.name()?.as_name();
377         let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
378         let visibility = self.lower_visibility(type_alias);
379         let bounds = self.lower_type_bounds(type_alias);
380         let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
381         let ast_id = self.source_ast_id_map.ast_id(type_alias);
382         let res = TypeAlias {
383             name,
384             visibility,
385             bounds: bounds.into_boxed_slice(),
386             generic_params,
387             type_ref,
388             ast_id,
389         };
390         Some(id(self.data().type_aliases.alloc(res)))
391     }
392
393     fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
394         let name = static_.name()?.as_name();
395         let type_ref = self.lower_type_ref_opt(static_.ty());
396         let visibility = self.lower_visibility(static_);
397         let mutable = static_.mut_token().is_some();
398         let ast_id = self.source_ast_id_map.ast_id(static_);
399         let res = Static { name, visibility, mutable, type_ref, ast_id };
400         Some(id(self.data().statics.alloc(res)))
401     }
402
403     fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
404         let name = konst.name().map(|it| it.as_name());
405         let type_ref = self.lower_type_ref_opt(konst.ty());
406         let visibility = self.lower_visibility(konst);
407         let ast_id = self.source_ast_id_map.ast_id(konst);
408         let res = Const { name, visibility, type_ref, ast_id };
409         id(self.data().consts.alloc(res))
410     }
411
412     fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
413         let name = module.name()?.as_name();
414         let visibility = self.lower_visibility(module);
415         let kind = if module.semicolon_token().is_some() {
416             ModKind::Outline
417         } else {
418             ModKind::Inline {
419                 items: module
420                     .item_list()
421                     .map(|list| list.items().flat_map(|item| self.lower_mod_item(&item)).collect())
422                     .unwrap_or_else(|| {
423                         cov_mark::hit!(name_res_works_for_broken_modules);
424                         Box::new([]) as Box<[_]>
425                     }),
426             }
427         };
428         let ast_id = self.source_ast_id_map.ast_id(module);
429         let res = Mod { name, visibility, kind, ast_id };
430         Some(id(self.data().mods.alloc(res)))
431     }
432
433     fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
434         let name = trait_def.name()?.as_name();
435         let visibility = self.lower_visibility(trait_def);
436         let generic_params = self.lower_generic_params(GenericsOwner::Trait(trait_def), trait_def);
437         let is_auto = trait_def.auto_token().is_some();
438         let is_unsafe = trait_def.unsafe_token().is_some();
439         let items = trait_def.assoc_item_list().map(|list| {
440             list.assoc_items()
441                 .filter_map(|item| {
442                     let attrs = RawAttrs::new(self.db, &item, self.hygiene());
443                     self.lower_assoc_item(&item).map(|item| {
444                         self.add_attrs(ModItem::from(item).into(), attrs);
445                         item
446                     })
447                 })
448                 .collect()
449         });
450         let ast_id = self.source_ast_id_map.ast_id(trait_def);
451         let res = Trait {
452             name,
453             visibility,
454             generic_params,
455             is_auto,
456             is_unsafe,
457             items: items.unwrap_or_default(),
458             ast_id,
459         };
460         Some(id(self.data().traits.alloc(res)))
461     }
462
463     fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
464         let generic_params = self.lower_generic_params(GenericsOwner::Impl, impl_def);
465         // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
466         // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
467         // equals itself.
468         let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
469         let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
470         let is_negative = impl_def.excl_token().is_some();
471
472         // We cannot use `assoc_items()` here as that does not include macro calls.
473         let items = impl_def
474             .assoc_item_list()
475             .into_iter()
476             .flat_map(|it| it.assoc_items())
477             .filter_map(|item| {
478                 let assoc = self.lower_assoc_item(&item)?;
479                 let attrs = RawAttrs::new(self.db, &item, self.hygiene());
480                 self.add_attrs(ModItem::from(assoc).into(), attrs);
481                 Some(assoc)
482             })
483             .collect();
484         let ast_id = self.source_ast_id_map.ast_id(impl_def);
485         let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
486         Some(id(self.data().impls.alloc(res)))
487     }
488
489     fn lower_use(&mut self, use_item: &ast::Use) -> Option<FileItemTreeId<Import>> {
490         let visibility = self.lower_visibility(use_item);
491         let ast_id = self.source_ast_id_map.ast_id(use_item);
492         let (use_tree, _) = lower_use_tree(self.db, self.hygiene(), use_item.use_tree()?)?;
493
494         let res = Import { visibility, ast_id, use_tree };
495         Some(id(self.data().imports.alloc(res)))
496     }
497
498     fn lower_extern_crate(
499         &mut self,
500         extern_crate: &ast::ExternCrate,
501     ) -> Option<FileItemTreeId<ExternCrate>> {
502         let name = extern_crate.name_ref()?.as_name();
503         let alias = extern_crate.rename().map(|a| {
504             a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
505         });
506         let visibility = self.lower_visibility(extern_crate);
507         let ast_id = self.source_ast_id_map.ast_id(extern_crate);
508
509         let res = ExternCrate { name, alias, visibility, ast_id };
510         Some(id(self.data().extern_crates.alloc(res)))
511     }
512
513     fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
514         let path = Interned::new(ModPath::from_src(self.db.upcast(), m.path()?, self.hygiene())?);
515         let ast_id = self.source_ast_id_map.ast_id(m);
516         let expand_to = hir_expand::ExpandTo::from_call_site(m);
517         let res = MacroCall { path, ast_id, expand_to };
518         Some(id(self.data().macro_calls.alloc(res)))
519     }
520
521     fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
522         let name = m.name().map(|it| it.as_name())?;
523         let ast_id = self.source_ast_id_map.ast_id(m);
524
525         let res = MacroRules { name, ast_id };
526         Some(id(self.data().macro_rules.alloc(res)))
527     }
528
529     fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
530         let name = m.name().map(|it| it.as_name())?;
531
532         let ast_id = self.source_ast_id_map.ast_id(m);
533         let visibility = self.lower_visibility(m);
534
535         let res = MacroDef { name, ast_id, visibility };
536         Some(id(self.data().macro_defs.alloc(res)))
537     }
538
539     fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> FileItemTreeId<ExternBlock> {
540         let ast_id = self.source_ast_id_map.ast_id(block);
541         let abi = block.abi().map(lower_abi);
542         let children: Box<[_]> = block.extern_item_list().map_or(Box::new([]), |list| {
543             list.extern_items()
544                 .filter_map(|item| {
545                     // Note: All items in an `extern` block need to be lowered as if they're outside of one
546                     // (in other words, the knowledge that they're in an extern block must not be used).
547                     // This is because an extern block can contain macros whose ItemTree's top-level items
548                     // should be considered to be in an extern block too.
549                     let attrs = RawAttrs::new(self.db, &item, self.hygiene());
550                     let id: ModItem = match item {
551                         ast::ExternItem::Fn(ast) => self.lower_function(&ast)?.into(),
552                         ast::ExternItem::Static(ast) => self.lower_static(&ast)?.into(),
553                         ast::ExternItem::TypeAlias(ty) => self.lower_type_alias(&ty)?.into(),
554                         ast::ExternItem::MacroCall(call) => self.lower_macro_call(&call)?.into(),
555                     };
556                     self.add_attrs(id.into(), attrs);
557                     Some(id)
558                 })
559                 .collect()
560         });
561
562         let res = ExternBlock { abi, ast_id, children };
563         id(self.data().extern_blocks.alloc(res))
564     }
565
566     fn lower_generic_params(
567         &mut self,
568         owner: GenericsOwner<'_>,
569         node: &dyn ast::HasGenericParams,
570     ) -> Interned<GenericParams> {
571         let mut generics = GenericParams::default();
572         match owner {
573             GenericsOwner::Function(_)
574             | GenericsOwner::Struct
575             | GenericsOwner::Enum
576             | GenericsOwner::Union
577             | GenericsOwner::TypeAlias => {
578                 generics.fill(&self.body_ctx, node);
579             }
580             GenericsOwner::Trait(trait_def) => {
581                 // traits get the Self type as an implicit first type parameter
582                 generics.type_or_consts.alloc(
583                     TypeParamData {
584                         name: Some(name![Self]),
585                         default: None,
586                         provenance: TypeParamProvenance::TraitSelf,
587                     }
588                     .into(),
589                 );
590                 // add super traits as bounds on Self
591                 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
592                 let self_param = TypeRef::Path(name![Self].into());
593                 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
594                 generics.fill(&self.body_ctx, node);
595             }
596             GenericsOwner::Impl => {
597                 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
598                 // type-parameter, but rather is a type-alias for impl's target
599                 // type, so this is handled by the resolver.
600                 generics.fill(&self.body_ctx, node);
601             }
602         }
603
604         generics.shrink_to_fit();
605         Interned::new(generics)
606     }
607
608     fn lower_type_bounds(&mut self, node: &dyn ast::HasTypeBounds) -> Vec<Interned<TypeBound>> {
609         match node.type_bound_list() {
610             Some(bound_list) => bound_list
611                 .bounds()
612                 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
613                 .collect(),
614             None => Vec::new(),
615         }
616     }
617
618     fn lower_visibility(&mut self, item: &dyn ast::HasVisibility) -> RawVisibilityId {
619         let vis = RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), self.hygiene());
620         self.data().vis.alloc(vis)
621     }
622
623     fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
624         let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
625         Some(Interned::new(trait_ref))
626     }
627
628     fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
629         let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
630         Interned::new(tyref)
631     }
632
633     fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
634         match type_ref.map(|ty| self.lower_type_ref(&ty)) {
635             Some(it) => it,
636             None => Interned::new(TypeRef::Error),
637         }
638     }
639
640     fn next_field_idx(&self) -> Idx<Field> {
641         Idx::from_raw(RawIdx::from(
642             self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
643         ))
644     }
645     fn next_variant_idx(&self) -> Idx<Variant> {
646         Idx::from_raw(RawIdx::from(
647             self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
648         ))
649     }
650     fn next_param_idx(&self) -> Idx<Param> {
651         Idx::from_raw(RawIdx::from(
652             self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
653         ))
654     }
655 }
656
657 fn desugar_future_path(orig: TypeRef) -> Path {
658     let path = path![core::future::Future];
659     let mut generic_args: Vec<_> =
660         std::iter::repeat(None).take(path.segments().len() - 1).collect();
661     let mut last = GenericArgs::empty();
662     let binding =
663         AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
664     last.bindings.push(binding);
665     generic_args.push(Some(Interned::new(last)));
666
667     Path::from_known_path(path, generic_args)
668 }
669
670 enum GenericsOwner<'a> {
671     /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
672     /// position.
673     Function(&'a Function),
674     Struct,
675     Enum,
676     Union,
677     /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
678     Trait(&'a ast::Trait),
679     TypeAlias,
680     Impl,
681 }
682
683 fn lower_abi(abi: ast::Abi) -> Interned<str> {
684     // FIXME: Abi::abi() -> Option<SyntaxToken>?
685     match abi.syntax().last_token() {
686         Some(tok) if tok.kind() == SyntaxKind::STRING => {
687             // FIXME: Better way to unescape?
688             Interned::new_str(tok.text().trim_matches('"'))
689         }
690         _ => {
691             // `extern` default to be `extern "C"`.
692             Interned::new_str("C")
693         }
694     }
695 }
696
697 struct UseTreeLowering<'a> {
698     db: &'a dyn DefDatabase,
699     hygiene: &'a Hygiene,
700     mapping: Arena<ast::UseTree>,
701 }
702
703 impl UseTreeLowering<'_> {
704     fn lower_use_tree(&mut self, tree: ast::UseTree) -> Option<UseTree> {
705         if let Some(use_tree_list) = tree.use_tree_list() {
706             let prefix = match tree.path() {
707                 // E.g. use something::{{{inner}}};
708                 None => None,
709                 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
710                 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
711                 Some(path) => {
712                     match ModPath::from_src(self.db.upcast(), path, self.hygiene) {
713                         Some(it) => Some(it),
714                         None => return None, // FIXME: report errors somewhere
715                     }
716                 }
717             };
718
719             let list =
720                 use_tree_list.use_trees().filter_map(|tree| self.lower_use_tree(tree)).collect();
721
722             Some(
723                 self.use_tree(
724                     UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
725                     tree,
726                 ),
727             )
728         } else {
729             let is_glob = tree.star_token().is_some();
730             let path = match tree.path() {
731                 Some(path) => Some(ModPath::from_src(self.db.upcast(), path, self.hygiene)?),
732                 None => None,
733             };
734             let alias = tree.rename().map(|a| {
735                 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
736             });
737             if alias.is_some() && is_glob {
738                 return None;
739             }
740
741             match (path, alias, is_glob) {
742                 (path, None, true) => {
743                     if path.is_none() {
744                         cov_mark::hit!(glob_enum_group);
745                     }
746                     Some(self.use_tree(UseTreeKind::Glob { path: path.map(Interned::new) }, tree))
747                 }
748                 // Globs can't be renamed
749                 (_, Some(_), true) | (None, None, false) => None,
750                 // `bla::{ as Name}` is invalid
751                 (None, Some(_), false) => None,
752                 (Some(path), alias, false) => Some(
753                     self.use_tree(UseTreeKind::Single { path: Interned::new(path), alias }, tree),
754                 ),
755             }
756         }
757     }
758
759     fn use_tree(&mut self, kind: UseTreeKind, ast: ast::UseTree) -> UseTree {
760         let index = self.mapping.alloc(ast);
761         UseTree { index, kind }
762     }
763 }
764
765 pub(super) fn lower_use_tree(
766     db: &dyn DefDatabase,
767     hygiene: &Hygiene,
768     tree: ast::UseTree,
769 ) -> Option<(UseTree, Arena<ast::UseTree>)> {
770     let mut lowering = UseTreeLowering { db, hygiene, mapping: Arena::new() };
771     let tree = lowering.lower_use_tree(tree)?;
772     Some((tree, lowering.mapping))
773 }