]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_tree/lower.rs
516a16bcf0de87e629d81bc13d91a92de7115168
[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.tocs.alloc(
586                     TypeParamData {
587                         name: Some(name![Self]),
588                         default: None,
589                         provenance: TypeParamProvenance::TraitSelf,
590                     }
591                     .into(),
592                 );
593                 // add super traits as bounds on Self
594                 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
595                 let self_param = TypeRef::Path(name![Self].into());
596                 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
597                 generics.fill(&self.body_ctx, node);
598             }
599             GenericsOwner::Impl => {
600                 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
601                 // type-parameter, but rather is a type-alias for impl's target
602                 // type, so this is handled by the resolver.
603                 generics.fill(&self.body_ctx, node);
604             }
605         }
606
607         generics.shrink_to_fit();
608         Interned::new(generics)
609     }
610
611     fn lower_type_bounds(&mut self, node: &dyn ast::HasTypeBounds) -> Vec<Interned<TypeBound>> {
612         match node.type_bound_list() {
613             Some(bound_list) => bound_list
614                 .bounds()
615                 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
616                 .collect(),
617             None => Vec::new(),
618         }
619     }
620
621     fn lower_visibility(&mut self, item: &dyn ast::HasVisibility) -> RawVisibilityId {
622         let vis = match self.forced_visibility {
623             Some(vis) => return vis,
624             None => {
625                 RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), self.hygiene())
626             }
627         };
628
629         self.data().vis.alloc(vis)
630     }
631
632     fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
633         let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
634         Some(Interned::new(trait_ref))
635     }
636
637     fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
638         let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
639         Interned::new(tyref)
640     }
641
642     fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
643         match type_ref.map(|ty| self.lower_type_ref(&ty)) {
644             Some(it) => it,
645             None => Interned::new(TypeRef::Error),
646         }
647     }
648
649     /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
650     fn with_inherited_visibility<R>(
651         &mut self,
652         vis: RawVisibilityId,
653         f: impl FnOnce(&mut Self) -> R,
654     ) -> R {
655         let old = mem::replace(&mut self.forced_visibility, Some(vis));
656         let res = f(self);
657         self.forced_visibility = old;
658         res
659     }
660
661     fn next_field_idx(&self) -> Idx<Field> {
662         Idx::from_raw(RawIdx::from(
663             self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
664         ))
665     }
666     fn next_variant_idx(&self) -> Idx<Variant> {
667         Idx::from_raw(RawIdx::from(
668             self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
669         ))
670     }
671     fn next_param_idx(&self) -> Idx<Param> {
672         Idx::from_raw(RawIdx::from(
673             self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
674         ))
675     }
676 }
677
678 fn desugar_future_path(orig: TypeRef) -> Path {
679     let path = path![core::future::Future];
680     let mut generic_args: Vec<_> =
681         std::iter::repeat(None).take(path.segments().len() - 1).collect();
682     let mut last = GenericArgs::empty();
683     let binding =
684         AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
685     last.bindings.push(binding);
686     generic_args.push(Some(Interned::new(last)));
687
688     Path::from_known_path(path, generic_args)
689 }
690
691 enum GenericsOwner<'a> {
692     /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
693     /// position.
694     Function(&'a Function),
695     Struct,
696     Enum,
697     Union,
698     /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
699     Trait(&'a ast::Trait),
700     TypeAlias,
701     Impl,
702 }
703
704 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
705 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
706     // Should be kept in sync with https://github.com/rust-lang/rust/blob/532d2b14c05f9bc20b2d27cbb5f4550d28343a36/compiler/rustc_typeck/src/check/intrinsic.rs#L72-L106
707     ![
708         known::abort,
709         known::add_with_overflow,
710         known::bitreverse,
711         known::black_box,
712         known::bswap,
713         known::caller_location,
714         known::ctlz,
715         known::ctpop,
716         known::cttz,
717         known::discriminant_value,
718         known::forget,
719         known::likely,
720         known::maxnumf32,
721         known::maxnumf64,
722         known::min_align_of,
723         known::minnumf32,
724         known::minnumf64,
725         known::mul_with_overflow,
726         known::needs_drop,
727         known::ptr_guaranteed_eq,
728         known::ptr_guaranteed_ne,
729         known::rotate_left,
730         known::rotate_right,
731         known::rustc_peek,
732         known::saturating_add,
733         known::saturating_sub,
734         known::size_of,
735         known::sub_with_overflow,
736         known::type_id,
737         known::type_name,
738         known::unlikely,
739         known::variant_count,
740         known::wrapping_add,
741         known::wrapping_mul,
742         known::wrapping_sub,
743     ]
744     .contains(name)
745 }
746
747 fn lower_abi(abi: ast::Abi) -> Interned<str> {
748     // FIXME: Abi::abi() -> Option<SyntaxToken>?
749     match abi.syntax().last_token() {
750         Some(tok) if tok.kind() == SyntaxKind::STRING => {
751             // FIXME: Better way to unescape?
752             Interned::new_str(tok.text().trim_matches('"'))
753         }
754         _ => {
755             // `extern` default to be `extern "C"`.
756             Interned::new_str("C")
757         }
758     }
759 }
760
761 struct UseTreeLowering<'a> {
762     db: &'a dyn DefDatabase,
763     hygiene: &'a Hygiene,
764     mapping: Arena<ast::UseTree>,
765 }
766
767 impl UseTreeLowering<'_> {
768     fn lower_use_tree(&mut self, tree: ast::UseTree) -> Option<UseTree> {
769         if let Some(use_tree_list) = tree.use_tree_list() {
770             let prefix = match tree.path() {
771                 // E.g. use something::{{{inner}}};
772                 None => None,
773                 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
774                 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
775                 Some(path) => {
776                     match ModPath::from_src(self.db.upcast(), path, self.hygiene) {
777                         Some(it) => Some(it),
778                         None => return None, // FIXME: report errors somewhere
779                     }
780                 }
781             };
782
783             let list =
784                 use_tree_list.use_trees().filter_map(|tree| self.lower_use_tree(tree)).collect();
785
786             Some(
787                 self.use_tree(
788                     UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
789                     tree,
790                 ),
791             )
792         } else {
793             let is_glob = tree.star_token().is_some();
794             let path = match tree.path() {
795                 Some(path) => Some(ModPath::from_src(self.db.upcast(), path, self.hygiene)?),
796                 None => None,
797             };
798             let alias = tree.rename().map(|a| {
799                 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
800             });
801             if alias.is_some() && is_glob {
802                 return None;
803             }
804
805             match (path, alias, is_glob) {
806                 (path, None, true) => {
807                     if path.is_none() {
808                         cov_mark::hit!(glob_enum_group);
809                     }
810                     Some(self.use_tree(UseTreeKind::Glob { path: path.map(Interned::new) }, tree))
811                 }
812                 // Globs can't be renamed
813                 (_, Some(_), true) | (None, None, false) => None,
814                 // `bla::{ as Name}` is invalid
815                 (None, Some(_), false) => None,
816                 (Some(path), alias, false) => Some(
817                     self.use_tree(UseTreeKind::Single { path: Interned::new(path), alias }, tree),
818                 ),
819             }
820         }
821     }
822
823     fn use_tree(&mut self, kind: UseTreeKind, ast: ast::UseTree) -> UseTree {
824         let index = self.mapping.alloc(ast);
825         UseTree { index, kind }
826     }
827 }
828
829 pub(super) fn lower_use_tree(
830     db: &dyn DefDatabase,
831     hygiene: &Hygiene,
832     tree: ast::UseTree,
833 ) -> Option<(UseTree, Arena<ast::UseTree>)> {
834     let mut lowering = UseTreeLowering { db, hygiene, mapping: Arena::new() };
835     let tree = lowering.lower_use_tree(tree)?;
836     Some((tree, lowering.mapping))
837 }