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