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