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