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