1 //! AST -> `ItemTree` lowering code.
3 use std::{collections::hash_map::Entry, mem, sync::Arc};
5 use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, name::known, HirFileId};
7 ast::{self, ModuleItemOwner},
12 generics::{GenericParams, TypeParamData, TypeParamProvenance},
13 type_ref::{LifetimeRef, TraitRef},
18 fn id<N: ItemTreeNode>(index: Idx<N>) -> FileItemTreeId<N> {
19 FileItemTreeId { index, _p: PhantomData }
22 pub(super) struct Ctx<'a> {
23 db: &'a dyn DefDatabase,
26 source_ast_id_map: Arc<AstIdMap>,
27 body_ctx: crate::body::LowerCtx<'a>,
28 forced_visibility: Option<RawVisibilityId>,
32 pub(super) fn new(db: &'a dyn DefDatabase, hygiene: Hygiene, file: HirFileId) -> Self {
35 tree: ItemTree::default(),
37 source_ast_id_map: db.ast_id_map(file),
38 body_ctx: crate::body::LowerCtx::new(db, file),
39 forced_visibility: None,
43 pub(super) fn lower_module_items(mut self, item_owner: &dyn ModuleItemOwner) -> ItemTree {
45 item_owner.items().flat_map(|item| self.lower_mod_item(&item, false)).collect();
49 pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
50 self.tree.top_level = stmts
52 .filter_map(|stmt| match stmt {
53 ast::Stmt::Item(item) => Some(item),
56 .flat_map(|item| self.lower_mod_item(&item, false))
59 // Non-items need to have their inner items collected.
60 for stmt in stmts.statements() {
62 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => {
63 self.collect_inner_items(stmt.syntax())
68 if let Some(expr) = stmts.expr() {
69 self.collect_inner_items(expr.syntax());
74 pub(super) fn lower_inner_items(mut self, within: &SyntaxNode) -> ItemTree {
75 self.collect_inner_items(within);
79 fn data(&mut self) -> &mut ItemTreeData {
83 fn lower_mod_item(&mut self, item: &ast::Item, inner: bool) -> Option<ModItem> {
84 // Collect inner items for 1-to-1-lowered items.
90 | ast::Item::TypeAlias(_)
92 | ast::Item::Static(_) => {
93 // Skip this if we're already collecting inner items. We'll descend into all nodes
96 self.collect_inner_items(item.syntax());
100 // These are handled in their respective `lower_X` method (since we can't just blindly
102 ast::Item::Trait(_) | ast::Item::Impl(_) | ast::Item::ExternBlock(_) => {}
104 // These don't have inner items.
106 | ast::Item::ExternCrate(_)
108 | ast::Item::MacroCall(_)
109 | ast::Item::MacroRules(_)
110 | ast::Item::MacroDef(_) => {}
113 let attrs = RawAttrs::new(self.db, item, &self.hygiene);
114 let item: ModItem = match item {
115 ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
116 ast::Item::Union(ast) => self.lower_union(ast)?.into(),
117 ast::Item::Enum(ast) => self.lower_enum(ast)?.into(),
118 ast::Item::Fn(ast) => self.lower_function(ast)?.into(),
119 ast::Item::TypeAlias(ast) => self.lower_type_alias(ast)?.into(),
120 ast::Item::Static(ast) => self.lower_static(ast)?.into(),
121 ast::Item::Const(ast) => self.lower_const(ast).into(),
122 ast::Item::Module(ast) => self.lower_module(ast)?.into(),
123 ast::Item::Trait(ast) => self.lower_trait(ast)?.into(),
124 ast::Item::Impl(ast) => self.lower_impl(ast)?.into(),
125 ast::Item::Use(ast) => self.lower_use(ast)?.into(),
126 ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast)?.into(),
127 ast::Item::MacroCall(ast) => self.lower_macro_call(ast)?.into(),
128 ast::Item::MacroRules(ast) => self.lower_macro_rules(ast)?.into(),
129 ast::Item::MacroDef(ast) => self.lower_macro_def(ast)?.into(),
130 ast::Item::ExternBlock(ast) => self.lower_extern_block(ast).into(),
133 self.add_attrs(item.into(), attrs);
138 fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) {
139 match self.tree.attrs.entry(item) {
140 Entry::Occupied(mut entry) => {
141 *entry.get_mut() = entry.get().merge(attrs);
143 Entry::Vacant(entry) => {
149 fn collect_inner_items(&mut self, container: &SyntaxNode) {
150 let forced_vis = self.forced_visibility.take();
152 let mut block_stack = Vec::new();
154 // if container itself is block, add it to the stack
155 if let Some(block) = ast::BlockExpr::cast(container.clone()) {
156 block_stack.push(self.source_ast_id_map.ast_id(&block));
159 for event in container.preorder().skip(1) {
161 WalkEvent::Enter(node) => {
164 ast::BlockExpr(block) => {
165 block_stack.push(self.source_ast_id_map.ast_id(&block));
168 // FIXME: This triggers for macro calls in expression/pattern/type position
169 let mod_item = self.lower_mod_item(&item, true);
170 let current_block = block_stack.last();
171 if let (Some(mod_item), Some(block)) = (mod_item, current_block) {
172 self.data().inner_items.entry(*block).or_default().push(mod_item);
179 WalkEvent::Leave(node) => {
180 if ast::BlockExpr::cast(node).is_some() {
187 self.forced_visibility = forced_vis;
190 fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
192 ast::AssocItem::Fn(ast) => self.lower_function(ast).map(Into::into),
193 ast::AssocItem::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
194 ast::AssocItem::Const(ast) => Some(self.lower_const(ast).into()),
195 ast::AssocItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
199 fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<FileItemTreeId<Struct>> {
200 let visibility = self.lower_visibility(strukt);
201 let name = strukt.name()?.as_name();
202 let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
203 let fields = self.lower_fields(&strukt.kind());
204 let ast_id = self.source_ast_id_map.ast_id(strukt);
205 let res = Struct { name, visibility, generic_params, fields, ast_id };
206 Some(id(self.data().structs.alloc(res)))
209 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
211 ast::StructKind::Record(it) => {
212 let range = self.lower_record_fields(it);
213 Fields::Record(range)
215 ast::StructKind::Tuple(it) => {
216 let range = self.lower_tuple_fields(it);
219 ast::StructKind::Unit => Fields::Unit,
223 fn lower_record_fields(&mut self, fields: &ast::RecordFieldList) -> IdRange<Field> {
224 let start = self.next_field_idx();
225 for field in fields.fields() {
226 if let Some(data) = self.lower_record_field(&field) {
227 let idx = self.data().fields.alloc(data);
228 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, &self.hygiene));
231 let end = self.next_field_idx();
232 IdRange::new(start..end)
235 fn lower_record_field(&mut self, field: &ast::RecordField) -> Option<Field> {
236 let name = field.name()?.as_name();
237 let visibility = self.lower_visibility(field);
238 let type_ref = self.lower_type_ref_opt(field.ty());
239 let res = Field { name, type_ref, visibility };
243 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldList) -> IdRange<Field> {
244 let start = self.next_field_idx();
245 for (i, field) in fields.fields().enumerate() {
246 let data = self.lower_tuple_field(i, &field);
247 let idx = self.data().fields.alloc(data);
248 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, &self.hygiene));
250 let end = self.next_field_idx();
251 IdRange::new(start..end)
254 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field {
255 let name = Name::new_tuple_field(idx);
256 let visibility = self.lower_visibility(field);
257 let type_ref = self.lower_type_ref_opt(field.ty());
258 let res = Field { name, type_ref, visibility };
262 fn lower_union(&mut self, union: &ast::Union) -> Option<FileItemTreeId<Union>> {
263 let visibility = self.lower_visibility(union);
264 let name = union.name()?.as_name();
265 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
266 let fields = match union.record_field_list() {
267 Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)),
268 None => Fields::Record(IdRange::new(self.next_field_idx()..self.next_field_idx())),
270 let ast_id = self.source_ast_id_map.ast_id(union);
271 let res = Union { name, visibility, generic_params, fields, ast_id };
272 Some(id(self.data().unions.alloc(res)))
275 fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<FileItemTreeId<Enum>> {
276 let visibility = self.lower_visibility(enum_);
277 let name = enum_.name()?.as_name();
278 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
280 self.with_inherited_visibility(visibility, |this| match &enum_.variant_list() {
281 Some(variant_list) => this.lower_variants(variant_list),
282 None => IdRange::new(this.next_variant_idx()..this.next_variant_idx()),
284 let ast_id = self.source_ast_id_map.ast_id(enum_);
285 let res = Enum { name, visibility, generic_params, variants, ast_id };
286 Some(id(self.data().enums.alloc(res)))
289 fn lower_variants(&mut self, variants: &ast::VariantList) -> IdRange<Variant> {
290 let start = self.next_variant_idx();
291 for variant in variants.variants() {
292 if let Some(data) = self.lower_variant(&variant) {
293 let idx = self.data().variants.alloc(data);
294 self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, &self.hygiene));
297 let end = self.next_variant_idx();
298 IdRange::new(start..end)
301 fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
302 let name = variant.name()?.as_name();
303 let fields = self.lower_fields(&variant.kind());
304 let res = Variant { name, fields };
308 fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
309 let visibility = self.lower_visibility(func);
310 let name = func.name()?.as_name();
312 let mut has_self_param = false;
313 let start_param = self.next_param_idx();
314 if let Some(param_list) = func.param_list() {
315 if let Some(self_param) = param_list.self_param() {
316 let self_type = match self_param.ty() {
317 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
319 let self_type = TypeRef::Path(name![Self].into());
320 match self_param.kind() {
321 ast::SelfParamKind::Owned => self_type,
322 ast::SelfParamKind::Ref => TypeRef::Reference(
324 self_param.lifetime().as_ref().map(LifetimeRef::new),
327 ast::SelfParamKind::MutRef => TypeRef::Reference(
329 self_param.lifetime().as_ref().map(LifetimeRef::new),
335 let ty = Interned::new(self_type);
336 let idx = self.data().params.alloc(Param::Normal(ty));
337 self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, &self.hygiene));
338 has_self_param = true;
340 for param in param_list.params() {
341 let idx = match param.dotdotdot_token() {
342 Some(_) => self.data().params.alloc(Param::Varargs),
344 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
345 let ty = Interned::new(type_ref);
346 self.data().params.alloc(Param::Normal(ty))
349 self.add_attrs(idx.into(), RawAttrs::new(self.db, ¶m, &self.hygiene));
352 let end_param = self.next_param_idx();
353 let params = IdRange::new(start_param..end_param);
355 let ret_type = match func.ret_type().and_then(|rt| rt.ty()) {
356 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
357 _ => TypeRef::unit(),
360 let (ret_type, async_ret_type) = if func.async_token().is_some() {
361 let async_ret_type = ret_type.clone();
362 let future_impl = desugar_future_path(ret_type);
363 let ty_bound = Interned::new(TypeBound::Path(future_impl));
364 (TypeRef::ImplTrait(vec![ty_bound]), Some(async_ret_type))
369 let abi = func.abi().map(lower_abi);
371 let ast_id = self.source_ast_id_map.ast_id(func);
373 let mut flags = FnFlags::default();
374 if func.body().is_some() {
375 flags.bits |= FnFlags::HAS_BODY;
378 flags.bits |= FnFlags::HAS_SELF_PARAM;
380 if func.default_token().is_some() {
381 flags.bits |= FnFlags::IS_DEFAULT;
383 if func.const_token().is_some() {
384 flags.bits |= FnFlags::IS_CONST;
386 if func.async_token().is_some() {
387 flags.bits |= FnFlags::IS_ASYNC;
389 if func.unsafe_token().is_some() {
390 flags.bits |= FnFlags::IS_UNSAFE;
393 let mut res = Function {
396 generic_params: Interned::new(GenericParams::default()),
399 ret_type: Interned::new(ret_type),
400 async_ret_type: async_ret_type.map(Interned::new),
404 res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
406 Some(id(self.data().functions.alloc(res)))
411 type_alias: &ast::TypeAlias,
412 ) -> Option<FileItemTreeId<TypeAlias>> {
413 let name = type_alias.name()?.as_name();
414 let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
415 let visibility = self.lower_visibility(type_alias);
416 let bounds = self.lower_type_bounds(type_alias);
417 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
418 let ast_id = self.source_ast_id_map.ast_id(type_alias);
419 let res = TypeAlias {
422 bounds: bounds.into_boxed_slice(),
428 Some(id(self.data().type_aliases.alloc(res)))
431 fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
432 let name = static_.name()?.as_name();
433 let type_ref = self.lower_type_ref_opt(static_.ty());
434 let visibility = self.lower_visibility(static_);
435 let mutable = static_.mut_token().is_some();
436 let ast_id = self.source_ast_id_map.ast_id(static_);
437 let res = Static { name, visibility, mutable, type_ref, ast_id, is_extern: false };
438 Some(id(self.data().statics.alloc(res)))
441 fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
442 let name = konst.name().map(|it| it.as_name());
443 let type_ref = self.lower_type_ref_opt(konst.ty());
444 let visibility = self.lower_visibility(konst);
445 let ast_id = self.source_ast_id_map.ast_id(konst);
446 let res = Const { name, visibility, type_ref, ast_id };
447 id(self.data().consts.alloc(res))
450 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
451 let name = module.name()?.as_name();
452 let visibility = self.lower_visibility(module);
453 let kind = if module.semicolon_token().is_some() {
460 list.items().flat_map(|item| self.lower_mod_item(&item, false)).collect()
463 cov_mark::hit!(name_res_works_for_broken_modules);
464 Box::new([]) as Box<[_]>
468 let ast_id = self.source_ast_id_map.ast_id(module);
469 let res = Mod { name, visibility, kind, ast_id };
470 Some(id(self.data().mods.alloc(res)))
473 fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
474 let name = trait_def.name()?.as_name();
475 let visibility = self.lower_visibility(trait_def);
477 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
478 let is_auto = trait_def.auto_token().is_some();
479 let is_unsafe = trait_def.unsafe_token().is_some();
480 let items = trait_def.assoc_item_list().map(|list| {
482 self.with_inherited_visibility(visibility, |this| {
485 let attrs = RawAttrs::new(db, &item, &this.hygiene);
486 this.collect_inner_items(item.syntax());
487 this.lower_assoc_item(&item).map(|item| {
488 this.add_attrs(ModItem::from(item).into(), attrs);
495 let ast_id = self.source_ast_id_map.ast_id(trait_def);
502 items: items.unwrap_or_default(),
505 Some(id(self.data().traits.alloc(res)))
508 fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
510 self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
511 // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
512 // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
514 let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
515 let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
516 let is_negative = impl_def.excl_token().is_some();
518 // We cannot use `assoc_items()` here as that does not include macro calls.
522 .flat_map(|it| it.assoc_items())
524 self.collect_inner_items(item.syntax());
525 let assoc = self.lower_assoc_item(&item)?;
526 let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
527 self.add_attrs(ModItem::from(assoc).into(), attrs);
531 let ast_id = self.source_ast_id_map.ast_id(impl_def);
532 let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
533 Some(id(self.data().impls.alloc(res)))
536 fn lower_use(&mut self, use_item: &ast::Use) -> Option<FileItemTreeId<Import>> {
537 let visibility = self.lower_visibility(use_item);
538 let ast_id = self.source_ast_id_map.ast_id(use_item);
539 let (use_tree, _) = lower_use_tree(self.db, &self.hygiene, use_item.use_tree()?)?;
541 let res = Import { visibility, ast_id, use_tree };
542 Some(id(self.data().imports.alloc(res)))
545 fn lower_extern_crate(
547 extern_crate: &ast::ExternCrate,
548 ) -> Option<FileItemTreeId<ExternCrate>> {
549 let name = extern_crate.name_ref()?.as_name();
550 let alias = extern_crate.rename().map(|a| {
551 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
553 let visibility = self.lower_visibility(extern_crate);
554 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
556 let res = ExternCrate { name, alias, visibility, ast_id };
557 Some(id(self.data().extern_crates.alloc(res)))
560 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
561 let path = Interned::new(ModPath::from_src(self.db, m.path()?, &self.hygiene)?);
562 let ast_id = self.source_ast_id_map.ast_id(m);
563 let fragment = hir_expand::to_fragment_kind(m);
564 let res = MacroCall { path, ast_id, fragment };
565 Some(id(self.data().macro_calls.alloc(res)))
568 fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
569 let name = m.name().map(|it| it.as_name())?;
570 let ast_id = self.source_ast_id_map.ast_id(m);
572 let res = MacroRules { name, ast_id };
573 Some(id(self.data().macro_rules.alloc(res)))
576 fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
577 let name = m.name().map(|it| it.as_name())?;
579 let ast_id = self.source_ast_id_map.ast_id(m);
580 let visibility = self.lower_visibility(m);
582 let res = MacroDef { name, ast_id, visibility };
583 Some(id(self.data().macro_defs.alloc(res)))
586 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> FileItemTreeId<ExternBlock> {
587 let ast_id = self.source_ast_id_map.ast_id(block);
588 let abi = block.abi().map(lower_abi);
589 let children: Box<[_]> = block.extern_item_list().map_or(Box::new([]), |list| {
592 self.collect_inner_items(item.syntax());
593 let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
594 let id: ModItem = match item {
595 ast::ExternItem::Fn(ast) => {
596 let func_id = self.lower_function(&ast)?;
597 let func = &mut self.data().functions[func_id.index];
598 if is_intrinsic_fn_unsafe(&func.name) {
599 func.flags.bits |= FnFlags::IS_UNSAFE;
601 func.flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
604 ast::ExternItem::Static(ast) => {
605 let statik = self.lower_static(&ast)?;
606 self.data().statics[statik.index].is_extern = true;
609 ast::ExternItem::TypeAlias(ty) => {
610 let foreign_ty = self.lower_type_alias(&ty)?;
611 self.data().type_aliases[foreign_ty.index].is_extern = true;
614 ast::ExternItem::MacroCall(call) => {
615 // FIXME: we need some way of tracking that the macro call is in an
617 self.lower_macro_call(&call)?.into()
620 self.add_attrs(id.into(), attrs);
626 let res = ExternBlock { abi, ast_id, children };
627 id(self.data().extern_blocks.alloc(res))
630 /// Lowers generics defined on `node` and collects inner items defined within.
631 fn lower_generic_params_and_inner_items(
633 owner: GenericsOwner<'_>,
634 node: &impl ast::GenericParamsOwner,
635 ) -> Interned<GenericParams> {
636 // Generics are part of item headers and may contain inner items we need to collect.
637 if let Some(params) = node.generic_param_list() {
638 self.collect_inner_items(params.syntax());
640 if let Some(clause) = node.where_clause() {
641 self.collect_inner_items(clause.syntax());
644 self.lower_generic_params(owner, node)
647 fn lower_generic_params(
649 owner: GenericsOwner<'_>,
650 node: &impl ast::GenericParamsOwner,
651 ) -> Interned<GenericParams> {
652 let mut sm = &mut Default::default();
653 let mut generics = GenericParams::default();
655 GenericsOwner::Function(func) => {
656 generics.fill(&self.body_ctx, sm, node);
657 // lower `impl Trait` in arguments
658 for id in func.params.clone() {
659 if let Param::Normal(ty) = &self.data().params[id] {
660 generics.fill_implicit_impl_trait_args(ty);
664 GenericsOwner::Struct
665 | GenericsOwner::Enum
666 | GenericsOwner::Union
667 | GenericsOwner::TypeAlias => {
668 generics.fill(&self.body_ctx, sm, node);
670 GenericsOwner::Trait(trait_def) => {
671 // traits get the Self type as an implicit first type parameter
672 let self_param_id = generics.types.alloc(TypeParamData {
673 name: Some(name![Self]),
675 provenance: TypeParamProvenance::TraitSelf,
677 sm.type_params.insert(self_param_id, Either::Left(trait_def.clone()));
678 // add super traits as bounds on Self
679 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
680 let self_param = TypeRef::Path(name![Self].into());
681 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
682 generics.fill(&self.body_ctx, &mut sm, node);
684 GenericsOwner::Impl => {
685 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
686 // type-parameter, but rather is a type-alias for impl's target
687 // type, so this is handled by the resolver.
688 generics.fill(&self.body_ctx, &mut sm, node);
692 generics.shrink_to_fit();
693 Interned::new(generics)
696 fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<Interned<TypeBound>> {
697 match node.type_bound_list() {
698 Some(bound_list) => bound_list
700 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
706 fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
707 let vis = match self.forced_visibility {
708 Some(vis) => return vis,
709 None => RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), &self.hygiene),
712 self.data().vis.alloc(vis)
715 fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
716 let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
717 Some(Interned::new(trait_ref))
720 fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
721 let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
725 fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
726 match type_ref.map(|ty| self.lower_type_ref(&ty)) {
728 None => Interned::new(TypeRef::Error),
732 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
733 fn with_inherited_visibility<R>(
735 vis: RawVisibilityId,
736 f: impl FnOnce(&mut Self) -> R,
738 let old = mem::replace(&mut self.forced_visibility, Some(vis));
740 self.forced_visibility = old;
744 fn next_field_idx(&self) -> Idx<Field> {
745 Idx::from_raw(RawIdx::from(
746 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
749 fn next_variant_idx(&self) -> Idx<Variant> {
750 Idx::from_raw(RawIdx::from(
751 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
754 fn next_param_idx(&self) -> Idx<Param> {
755 Idx::from_raw(RawIdx::from(
756 self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
761 fn desugar_future_path(orig: TypeRef) -> Path {
762 let path = path![core::future::Future];
763 let mut generic_args: Vec<_> =
764 std::iter::repeat(None).take(path.segments().len() - 1).collect();
765 let mut last = GenericArgs::empty();
767 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
768 last.bindings.push(binding);
769 generic_args.push(Some(Interned::new(last)));
771 Path::from_known_path(path, generic_args)
774 enum GenericsOwner<'a> {
775 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
777 Function(&'a Function),
781 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
782 Trait(&'a ast::Trait),
787 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
788 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
789 // Should be kept in sync with https://github.com/rust-lang/rust/blob/c6e4db620a7d2f569f11dcab627430921ea8aacf/compiler/rustc_typeck/src/check/intrinsic.rs#L68
794 known::caller_location,
796 known::min_align_of_val,
797 known::add_with_overflow,
798 known::sub_with_overflow,
799 known::mul_with_overflow,
803 known::saturating_add,
804 known::saturating_sub,
812 known::discriminant_value,
816 known::ptr_guaranteed_eq,
817 known::ptr_guaranteed_ne,
824 known::variant_count,
829 fn lower_abi(abi: ast::Abi) -> Interned<str> {
830 // FIXME: Abi::abi() -> Option<SyntaxToken>?
831 match abi.syntax().last_token() {
832 Some(tok) if tok.kind() == SyntaxKind::STRING => {
833 // FIXME: Better way to unescape?
834 Interned::new_str(tok.text().trim_matches('"'))
837 // `extern` default to be `extern "C"`.
838 Interned::new_str("C")
843 struct UseTreeLowering<'a> {
844 db: &'a dyn DefDatabase,
845 hygiene: &'a Hygiene,
846 mapping: Arena<ast::UseTree>,
849 impl UseTreeLowering<'_> {
850 fn lower_use_tree(&mut self, tree: ast::UseTree) -> Option<UseTree> {
851 if let Some(use_tree_list) = tree.use_tree_list() {
852 let prefix = match tree.path() {
853 // E.g. use something::{{{inner}}};
855 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
856 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
858 match ModPath::from_src(self.db, path, self.hygiene) {
859 Some(it) => Some(it),
860 None => return None, // FIXME: report errors somewhere
866 use_tree_list.use_trees().filter_map(|tree| self.lower_use_tree(tree)).collect();
870 UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
875 let is_glob = tree.star_token().is_some();
876 let path = match tree.path() {
877 Some(path) => Some(ModPath::from_src(self.db, path, self.hygiene)?),
880 let alias = tree.rename().map(|a| {
881 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
883 if alias.is_some() && is_glob {
887 match (path, alias, is_glob) {
888 (path, None, true) => {
890 cov_mark::hit!(glob_enum_group);
892 Some(self.use_tree(UseTreeKind::Glob { path: path.map(Interned::new) }, tree))
894 // Globs can't be renamed
895 (_, Some(_), true) | (None, None, false) => None,
896 // `bla::{ as Name}` is invalid
897 (None, Some(_), false) => None,
898 (Some(path), alias, false) => Some(
899 self.use_tree(UseTreeKind::Single { path: Interned::new(path), alias }, tree),
905 fn use_tree(&mut self, kind: UseTreeKind, ast: ast::UseTree) -> UseTree {
906 let index = self.mapping.alloc(ast);
907 UseTree { index, kind }
911 pub(super) fn lower_use_tree(
912 db: &dyn DefDatabase,
915 ) -> Option<(UseTree, Arena<ast::UseTree>)> {
916 let mut lowering = UseTreeLowering { db, hygiene, mapping: Arena::new() };
917 let tree = lowering.lower_use_tree(tree)?;
918 Some((tree, lowering.mapping))