]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_tree/lower.rs
Merge #8398
[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, TraitRef},
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<'a> {
35     db: &'a dyn DefDatabase,
36     tree: ItemTree,
37     hygiene: Hygiene,
38     file: HirFileId,
39     source_ast_id_map: Arc<AstIdMap>,
40     body_ctx: crate::body::LowerCtx<'a>,
41     forced_visibility: Option<RawVisibilityId>,
42 }
43
44 impl<'a> Ctx<'a> {
45     pub(super) fn new(db: &'a dyn DefDatabase, hygiene: Hygiene, file: HirFileId) -> Self {
46         Self {
47             db,
48             tree: ItemTree::default(),
49             hygiene,
50             file,
51             source_ast_id_map: db.ast_id_map(file),
52             body_ctx: crate::body::LowerCtx::new(db, file),
53             forced_visibility: None,
54         }
55     }
56
57     pub(super) fn lower_module_items(mut self, item_owner: &dyn ModuleItemOwner) -> ItemTree {
58         self.tree.top_level = item_owner
59             .items()
60             .flat_map(|item| self.lower_mod_item(&item, false))
61             .flat_map(|items| items.0)
62             .collect();
63         self.tree
64     }
65
66     pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
67         self.tree.top_level = stmts
68             .statements()
69             .filter_map(|stmt| match stmt {
70                 ast::Stmt::Item(item) => Some(item),
71                 _ => None,
72             })
73             .flat_map(|item| self.lower_mod_item(&item, false))
74             .flat_map(|items| items.0)
75             .collect();
76
77         // Non-items need to have their inner items collected.
78         for stmt in stmts.statements() {
79             match stmt {
80                 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => {
81                     self.collect_inner_items(stmt.syntax())
82                 }
83                 _ => {}
84             }
85         }
86         if let Some(expr) = stmts.expr() {
87             self.collect_inner_items(expr.syntax());
88         }
89         self.tree
90     }
91
92     pub(super) fn lower_inner_items(mut self, within: &SyntaxNode) -> ItemTree {
93         self.collect_inner_items(within);
94         self.tree
95     }
96
97     fn data(&mut self) -> &mut ItemTreeData {
98         self.tree.data_mut()
99     }
100
101     fn lower_mod_item(&mut self, item: &ast::Item, inner: bool) -> Option<ModItems> {
102         // Collect inner items for 1-to-1-lowered items.
103         match item {
104             ast::Item::Struct(_)
105             | ast::Item::Union(_)
106             | ast::Item::Enum(_)
107             | ast::Item::Fn(_)
108             | ast::Item::TypeAlias(_)
109             | ast::Item::Const(_)
110             | ast::Item::Static(_) => {
111                 // Skip this if we're already collecting inner items. We'll descend into all nodes
112                 // already.
113                 if !inner {
114                     self.collect_inner_items(item.syntax());
115                 }
116             }
117
118             // These are handled in their respective `lower_X` method (since we can't just blindly
119             // walk them).
120             ast::Item::Trait(_) | ast::Item::Impl(_) | ast::Item::ExternBlock(_) => {}
121
122             // These don't have inner items.
123             ast::Item::Module(_)
124             | ast::Item::ExternCrate(_)
125             | ast::Item::Use(_)
126             | ast::Item::MacroCall(_)
127             | ast::Item::MacroRules(_)
128             | ast::Item::MacroDef(_) => {}
129         };
130
131         let attrs = RawAttrs::new(self.db, item, &self.hygiene);
132         let items = match item {
133             ast::Item::Struct(ast) => self.lower_struct(ast).map(Into::into),
134             ast::Item::Union(ast) => self.lower_union(ast).map(Into::into),
135             ast::Item::Enum(ast) => self.lower_enum(ast).map(Into::into),
136             ast::Item::Fn(ast) => self.lower_function(ast).map(Into::into),
137             ast::Item::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
138             ast::Item::Static(ast) => self.lower_static(ast).map(Into::into),
139             ast::Item::Const(ast) => Some(self.lower_const(ast).into()),
140             ast::Item::Module(ast) => self.lower_module(ast).map(Into::into),
141             ast::Item::Trait(ast) => self.lower_trait(ast).map(Into::into),
142             ast::Item::Impl(ast) => self.lower_impl(ast).map(Into::into),
143             ast::Item::Use(ast) => Some(ModItems(
144                 self.lower_use(ast).into_iter().map(Into::into).collect::<SmallVec<_>>(),
145             )),
146             ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast).map(Into::into),
147             ast::Item::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
148             ast::Item::MacroRules(ast) => self.lower_macro_rules(ast).map(Into::into),
149             ast::Item::MacroDef(ast) => self.lower_macro_def(ast).map(Into::into),
150             ast::Item::ExternBlock(ast) => {
151                 Some(ModItems(self.lower_extern_block(ast).into_iter().collect::<SmallVec<_>>()))
152             }
153         };
154
155         if !attrs.is_empty() {
156             for item in items.iter().flat_map(|items| &items.0) {
157                 self.add_attrs((*item).into(), attrs.clone());
158             }
159         }
160
161         items
162     }
163
164     fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) {
165         match self.tree.attrs.entry(item) {
166             Entry::Occupied(mut entry) => {
167                 *entry.get_mut() = entry.get().merge(attrs);
168             }
169             Entry::Vacant(entry) => {
170                 entry.insert(attrs);
171             }
172         }
173     }
174
175     fn collect_inner_items(&mut self, container: &SyntaxNode) {
176         let forced_vis = self.forced_visibility.take();
177
178         let mut block_stack = Vec::new();
179
180         // if container itself is block, add it to the stack
181         if let Some(block) = ast::BlockExpr::cast(container.clone()) {
182             block_stack.push(self.source_ast_id_map.ast_id(&block));
183         }
184
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/pattern/type 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(self.db, &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(self.db, &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(self.db, &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 = Interned::new(self_type);
368                 let idx = self.data().params.alloc(Param::Normal(ty));
369                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &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 = Interned::new(type_ref);
378                         self.data().params.alloc(Param::Normal(ty))
379                     }
380                 };
381                 self.add_attrs(idx.into(), RawAttrs::new(self.db, &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 abi = func.abi().map(|abi| {
401             // FIXME: Abi::abi() -> Option<SyntaxToken>?
402             match abi.syntax().last_token() {
403                 Some(tok) if tok.kind() == SyntaxKind::STRING => {
404                     // FIXME: Better way to unescape?
405                     Interned::new_str(tok.text().trim_matches('"'))
406                 }
407                 _ => {
408                     // `extern` default to be `extern "C"`.
409                     Interned::new_str("C")
410                 }
411             }
412         });
413
414         let ast_id = self.source_ast_id_map.ast_id(func);
415
416         let mut flags = FnFlags::default();
417         if func.body().is_some() {
418             flags.bits |= FnFlags::HAS_BODY;
419         }
420         if has_self_param {
421             flags.bits |= FnFlags::HAS_SELF_PARAM;
422         }
423         if func.default_token().is_some() {
424             flags.bits |= FnFlags::IS_DEFAULT;
425         }
426         if func.const_token().is_some() {
427             flags.bits |= FnFlags::IS_CONST;
428         }
429         if func.async_token().is_some() {
430             flags.bits |= FnFlags::IS_ASYNC;
431         }
432         if func.unsafe_token().is_some() {
433             flags.bits |= FnFlags::IS_UNSAFE;
434         }
435
436         let mut res = Function {
437             name,
438             visibility,
439             generic_params: Interned::new(GenericParams::default()),
440             abi,
441             params,
442             ret_type: Interned::new(ret_type),
443             ast_id,
444             flags,
445         };
446         res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
447
448         Some(id(self.data().functions.alloc(res)))
449     }
450
451     fn lower_type_alias(
452         &mut self,
453         type_alias: &ast::TypeAlias,
454     ) -> Option<FileItemTreeId<TypeAlias>> {
455         let name = type_alias.name()?.as_name();
456         let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
457         let visibility = self.lower_visibility(type_alias);
458         let bounds = self.lower_type_bounds(type_alias);
459         let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
460         let ast_id = self.source_ast_id_map.ast_id(type_alias);
461         let res = TypeAlias {
462             name,
463             visibility,
464             bounds: bounds.into_boxed_slice(),
465             generic_params,
466             type_ref,
467             ast_id,
468             is_extern: false,
469         };
470         Some(id(self.data().type_aliases.alloc(res)))
471     }
472
473     fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
474         let name = static_.name()?.as_name();
475         let type_ref = self.lower_type_ref_opt(static_.ty());
476         let visibility = self.lower_visibility(static_);
477         let mutable = static_.mut_token().is_some();
478         let ast_id = self.source_ast_id_map.ast_id(static_);
479         let res = Static { name, visibility, mutable, type_ref, ast_id, is_extern: false };
480         Some(id(self.data().statics.alloc(res)))
481     }
482
483     fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
484         let name = konst.name().map(|it| it.as_name());
485         let type_ref = self.lower_type_ref_opt(konst.ty());
486         let visibility = self.lower_visibility(konst);
487         let ast_id = self.source_ast_id_map.ast_id(konst);
488         let res = Const { name, visibility, type_ref, ast_id };
489         id(self.data().consts.alloc(res))
490     }
491
492     fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
493         let name = module.name()?.as_name();
494         let visibility = self.lower_visibility(module);
495         let kind = if module.semicolon_token().is_some() {
496             ModKind::Outline {}
497         } else {
498             ModKind::Inline {
499                 items: module
500                     .item_list()
501                     .map(|list| {
502                         list.items()
503                             .flat_map(|item| self.lower_mod_item(&item, false))
504                             .flat_map(|items| items.0)
505                             .collect()
506                     })
507                     .unwrap_or_else(|| {
508                         cov_mark::hit!(name_res_works_for_broken_modules);
509                         Box::new([]) as Box<[_]>
510                     }),
511             }
512         };
513         let ast_id = self.source_ast_id_map.ast_id(module);
514         let res = Mod { name, visibility, kind, ast_id };
515         Some(id(self.data().mods.alloc(res)))
516     }
517
518     fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
519         let name = trait_def.name()?.as_name();
520         let visibility = self.lower_visibility(trait_def);
521         let generic_params =
522             self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
523         let is_auto = trait_def.auto_token().is_some();
524         let is_unsafe = trait_def.unsafe_token().is_some();
525         let bounds = self.lower_type_bounds(trait_def);
526         let items = trait_def.assoc_item_list().map(|list| {
527             let db = self.db;
528             self.with_inherited_visibility(visibility, |this| {
529                 list.assoc_items()
530                     .filter_map(|item| {
531                         let attrs = RawAttrs::new(db, &item, &this.hygiene);
532                         this.collect_inner_items(item.syntax());
533                         this.lower_assoc_item(&item).map(|item| {
534                             this.add_attrs(ModItem::from(item).into(), attrs);
535                             item
536                         })
537                     })
538                     .collect()
539             })
540         });
541         let ast_id = self.source_ast_id_map.ast_id(trait_def);
542         let res = Trait {
543             name,
544             visibility,
545             generic_params,
546             is_auto,
547             is_unsafe,
548             bounds: bounds.into(),
549             items: items.unwrap_or_default(),
550             ast_id,
551         };
552         Some(id(self.data().traits.alloc(res)))
553     }
554
555     fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
556         let generic_params =
557             self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
558         // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
559         // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
560         // equals itself.
561         let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
562         let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
563         let is_negative = impl_def.excl_token().is_some();
564
565         // We cannot use `assoc_items()` here as that does not include macro calls.
566         let items = impl_def
567             .assoc_item_list()
568             .into_iter()
569             .flat_map(|it| it.assoc_items())
570             .filter_map(|item| {
571                 self.collect_inner_items(item.syntax());
572                 let assoc = self.lower_assoc_item(&item)?;
573                 let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
574                 self.add_attrs(ModItem::from(assoc).into(), attrs);
575                 Some(assoc)
576             })
577             .collect();
578         let ast_id = self.source_ast_id_map.ast_id(impl_def);
579         let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
580         Some(id(self.data().impls.alloc(res)))
581     }
582
583     fn lower_use(&mut self, use_item: &ast::Use) -> Vec<FileItemTreeId<Import>> {
584         let visibility = self.lower_visibility(use_item);
585         let ast_id = self.source_ast_id_map.ast_id(use_item);
586
587         // Every use item can expand to many `Import`s.
588         let mut imports = Vec::new();
589         let tree = self.tree.data_mut();
590         ModPath::expand_use_item(
591             self.db,
592             InFile::new(self.file, use_item.clone()),
593             &self.hygiene,
594             |path, _use_tree, is_glob, alias| {
595                 imports.push(id(tree.imports.alloc(Import {
596                     path: Interned::new(path),
597                     alias,
598                     visibility,
599                     is_glob,
600                     ast_id,
601                     index: imports.len(),
602                 })));
603             },
604         );
605
606         imports
607     }
608
609     fn lower_extern_crate(
610         &mut self,
611         extern_crate: &ast::ExternCrate,
612     ) -> Option<FileItemTreeId<ExternCrate>> {
613         let name = extern_crate.name_ref()?.as_name();
614         let alias = extern_crate.rename().map(|a| {
615             a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
616         });
617         let visibility = self.lower_visibility(extern_crate);
618         let ast_id = self.source_ast_id_map.ast_id(extern_crate);
619
620         let res = ExternCrate { name, alias, visibility, ast_id };
621         Some(id(self.data().extern_crates.alloc(res)))
622     }
623
624     fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
625         let path = Interned::new(ModPath::from_src(self.db, m.path()?, &self.hygiene)?);
626         let ast_id = self.source_ast_id_map.ast_id(m);
627         let fragment = hir_expand::to_fragment_kind(m);
628         let res = MacroCall { path, ast_id, fragment };
629         Some(id(self.data().macro_calls.alloc(res)))
630     }
631
632     fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
633         let name = m.name().map(|it| it.as_name())?;
634         let ast_id = self.source_ast_id_map.ast_id(m);
635
636         let res = MacroRules { name, ast_id };
637         Some(id(self.data().macro_rules.alloc(res)))
638     }
639
640     fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
641         let name = m.name().map(|it| it.as_name())?;
642
643         let ast_id = self.source_ast_id_map.ast_id(m);
644         let visibility = self.lower_visibility(m);
645
646         let res = MacroDef { name, ast_id, visibility };
647         Some(id(self.data().macro_defs.alloc(res)))
648     }
649
650     fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> Vec<ModItem> {
651         block.extern_item_list().map_or(Vec::new(), |list| {
652             list.extern_items()
653                 .filter_map(|item| {
654                     self.collect_inner_items(item.syntax());
655                     let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
656                     let id: ModItem = match item {
657                         ast::ExternItem::Fn(ast) => {
658                             let func_id = self.lower_function(&ast)?;
659                             let func = &mut self.data().functions[func_id.index];
660                             if is_intrinsic_fn_unsafe(&func.name) {
661                                 func.flags.bits |= FnFlags::IS_UNSAFE;
662                             }
663                             func.flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
664                             func_id.into()
665                         }
666                         ast::ExternItem::Static(ast) => {
667                             let statik = self.lower_static(&ast)?;
668                             self.data().statics[statik.index].is_extern = true;
669                             statik.into()
670                         }
671                         ast::ExternItem::TypeAlias(ty) => {
672                             let foreign_ty = self.lower_type_alias(&ty)?;
673                             self.data().type_aliases[foreign_ty.index].is_extern = true;
674                             foreign_ty.into()
675                         }
676                         ast::ExternItem::MacroCall(_) => return None,
677                     };
678                     self.add_attrs(id.into(), attrs);
679                     Some(id)
680                 })
681                 .collect()
682         })
683     }
684
685     /// Lowers generics defined on `node` and collects inner items defined within.
686     fn lower_generic_params_and_inner_items(
687         &mut self,
688         owner: GenericsOwner<'_>,
689         node: &impl ast::GenericParamsOwner,
690     ) -> Interned<GenericParams> {
691         // Generics are part of item headers and may contain inner items we need to collect.
692         if let Some(params) = node.generic_param_list() {
693             self.collect_inner_items(params.syntax());
694         }
695         if let Some(clause) = node.where_clause() {
696             self.collect_inner_items(clause.syntax());
697         }
698
699         self.lower_generic_params(owner, node)
700     }
701
702     fn lower_generic_params(
703         &mut self,
704         owner: GenericsOwner<'_>,
705         node: &impl ast::GenericParamsOwner,
706     ) -> Interned<GenericParams> {
707         let mut sm = &mut Default::default();
708         let mut generics = GenericParams::default();
709         match owner {
710             GenericsOwner::Function(func) => {
711                 generics.fill(&self.body_ctx, sm, node);
712                 // lower `impl Trait` in arguments
713                 for id in func.params.clone() {
714                     if let Param::Normal(ty) = &self.data().params[id] {
715                         generics.fill_implicit_impl_trait_args(ty);
716                     }
717                 }
718             }
719             GenericsOwner::Struct
720             | GenericsOwner::Enum
721             | GenericsOwner::Union
722             | GenericsOwner::TypeAlias => {
723                 generics.fill(&self.body_ctx, sm, node);
724             }
725             GenericsOwner::Trait(trait_def) => {
726                 // traits get the Self type as an implicit first type parameter
727                 let self_param_id = generics.types.alloc(TypeParamData {
728                     name: Some(name![Self]),
729                     default: None,
730                     provenance: TypeParamProvenance::TraitSelf,
731                 });
732                 sm.type_params.insert(self_param_id, Either::Left(trait_def.clone()));
733                 // add super traits as bounds on Self
734                 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
735                 let self_param = TypeRef::Path(name![Self].into());
736                 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
737                 generics.fill(&self.body_ctx, &mut sm, node);
738             }
739             GenericsOwner::Impl => {
740                 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
741                 // type-parameter, but rather is a type-alias for impl's target
742                 // type, so this is handled by the resolver.
743                 generics.fill(&self.body_ctx, &mut sm, node);
744             }
745         }
746
747         generics.shrink_to_fit();
748         Interned::new(generics)
749     }
750
751     fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<TypeBound> {
752         match node.type_bound_list() {
753             Some(bound_list) => {
754                 bound_list.bounds().map(|it| TypeBound::from_ast(&self.body_ctx, it)).collect()
755             }
756             None => Vec::new(),
757         }
758     }
759
760     fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
761         let vis = match self.forced_visibility {
762             Some(vis) => return vis,
763             None => RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), &self.hygiene),
764         };
765
766         self.data().vis.alloc(vis)
767     }
768
769     fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
770         let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
771         Some(Interned::new(trait_ref))
772     }
773
774     fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
775         let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
776         Interned::new(tyref)
777     }
778
779     fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
780         match type_ref.map(|ty| self.lower_type_ref(&ty)) {
781             Some(it) => it,
782             None => Interned::new(TypeRef::Error),
783         }
784     }
785
786     /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
787     fn with_inherited_visibility<R>(
788         &mut self,
789         vis: RawVisibilityId,
790         f: impl FnOnce(&mut Self) -> R,
791     ) -> R {
792         let old = mem::replace(&mut self.forced_visibility, Some(vis));
793         let res = f(self);
794         self.forced_visibility = old;
795         res
796     }
797
798     fn next_field_idx(&self) -> Idx<Field> {
799         Idx::from_raw(RawIdx::from(
800             self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
801         ))
802     }
803     fn next_variant_idx(&self) -> Idx<Variant> {
804         Idx::from_raw(RawIdx::from(
805             self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
806         ))
807     }
808     fn next_param_idx(&self) -> Idx<Param> {
809         Idx::from_raw(RawIdx::from(
810             self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
811         ))
812     }
813 }
814
815 fn desugar_future_path(orig: TypeRef) -> Path {
816     let path = path![core::future::Future];
817     let mut generic_args: Vec<_> =
818         std::iter::repeat(None).take(path.segments().len() - 1).collect();
819     let mut last = GenericArgs::empty();
820     let binding =
821         AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
822     last.bindings.push(binding);
823     generic_args.push(Some(Arc::new(last)));
824
825     Path::from_known_path(path, generic_args)
826 }
827
828 enum GenericsOwner<'a> {
829     /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
830     /// position.
831     Function(&'a Function),
832     Struct,
833     Enum,
834     Union,
835     /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
836     Trait(&'a ast::Trait),
837     TypeAlias,
838     Impl,
839 }
840
841 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
842 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
843     // Should be kept in sync with https://github.com/rust-lang/rust/blob/c6e4db620a7d2f569f11dcab627430921ea8aacf/compiler/rustc_typeck/src/check/intrinsic.rs#L68
844     ![
845         known::abort,
846         known::min_align_of,
847         known::needs_drop,
848         known::caller_location,
849         known::size_of_val,
850         known::min_align_of_val,
851         known::add_with_overflow,
852         known::sub_with_overflow,
853         known::mul_with_overflow,
854         known::wrapping_add,
855         known::wrapping_sub,
856         known::wrapping_mul,
857         known::saturating_add,
858         known::saturating_sub,
859         known::rotate_left,
860         known::rotate_right,
861         known::ctpop,
862         known::ctlz,
863         known::cttz,
864         known::bswap,
865         known::bitreverse,
866         known::discriminant_value,
867         known::type_id,
868         known::likely,
869         known::unlikely,
870         known::ptr_guaranteed_eq,
871         known::ptr_guaranteed_ne,
872         known::minnumf32,
873         known::minnumf64,
874         known::maxnumf32,
875         known::rustc_peek,
876         known::maxnumf64,
877         known::type_name,
878         known::variant_count,
879     ]
880     .contains(&name)
881 }