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};
6 use smallvec::SmallVec;
8 ast::{self, ModuleItemOwner},
13 generics::{GenericParams, TypeParamData, TypeParamProvenance},
14 type_ref::LifetimeRef,
19 fn id<N: ItemTreeNode>(index: Idx<N>) -> FileItemTreeId<N> {
20 FileItemTreeId { index, _p: PhantomData }
23 struct ModItems(SmallVec<[ModItem; 1]>);
25 impl<T> From<T> for ModItems
29 fn from(t: T) -> Self {
30 ModItems(SmallVec::from_buf([t.into(); 1]))
34 pub(super) struct Ctx {
38 source_ast_id_map: Arc<AstIdMap>,
39 body_ctx: crate::body::LowerCtx,
40 forced_visibility: Option<RawVisibilityId>,
44 pub(super) fn new(db: &dyn DefDatabase, hygiene: Hygiene, file: HirFileId) -> Self {
46 tree: ItemTree::default(),
49 source_ast_id_map: db.ast_id_map(file),
50 body_ctx: crate::body::LowerCtx::new(db, file),
51 forced_visibility: None,
55 pub(super) fn lower_module_items(mut self, item_owner: &dyn ModuleItemOwner) -> ItemTree {
56 self.tree.top_level = item_owner
58 .flat_map(|item| self.lower_mod_item(&item, false))
59 .flat_map(|items| items.0)
64 pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
65 self.tree.top_level = stmts
67 .filter_map(|stmt| match stmt {
68 ast::Stmt::Item(item) => Some(item),
71 .flat_map(|item| self.lower_mod_item(&item, false))
72 .flat_map(|items| items.0)
75 // Non-items need to have their inner items collected.
76 for stmt in stmts.statements() {
78 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => {
79 self.collect_inner_items(stmt.syntax())
84 if let Some(expr) = stmts.expr() {
85 self.collect_inner_items(expr.syntax());
90 pub(super) fn lower_inner_items(mut self, within: &SyntaxNode) -> ItemTree {
91 self.collect_inner_items(within);
95 fn data(&mut self) -> &mut ItemTreeData {
99 fn lower_mod_item(&mut self, item: &ast::Item, inner: bool) -> Option<ModItems> {
100 // Collect inner items for 1-to-1-lowered items.
103 | ast::Item::Union(_)
106 | ast::Item::TypeAlias(_)
107 | ast::Item::Const(_)
108 | ast::Item::Static(_) => {
109 // Skip this if we're already collecting inner items. We'll descend into all nodes
112 self.collect_inner_items(item.syntax());
116 // These are handled in their respective `lower_X` method (since we can't just blindly
118 ast::Item::Trait(_) | ast::Item::Impl(_) | ast::Item::ExternBlock(_) => {}
120 // These don't have inner items.
122 | ast::Item::ExternCrate(_)
124 | ast::Item::MacroCall(_)
125 | ast::Item::MacroRules(_)
126 | ast::Item::MacroDef(_) => {}
129 let attrs = RawAttrs::new(item, &self.hygiene);
130 let items = match item {
131 ast::Item::Struct(ast) => self.lower_struct(ast).map(Into::into),
132 ast::Item::Union(ast) => self.lower_union(ast).map(Into::into),
133 ast::Item::Enum(ast) => self.lower_enum(ast).map(Into::into),
134 ast::Item::Fn(ast) => self.lower_function(ast).map(Into::into),
135 ast::Item::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
136 ast::Item::Static(ast) => self.lower_static(ast).map(Into::into),
137 ast::Item::Const(ast) => Some(self.lower_const(ast).into()),
138 ast::Item::Module(ast) => self.lower_module(ast).map(Into::into),
139 ast::Item::Trait(ast) => self.lower_trait(ast).map(Into::into),
140 ast::Item::Impl(ast) => self.lower_impl(ast).map(Into::into),
141 ast::Item::Use(ast) => Some(ModItems(
142 self.lower_use(ast).into_iter().map(Into::into).collect::<SmallVec<_>>(),
144 ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast).map(Into::into),
145 ast::Item::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
146 ast::Item::MacroRules(ast) => self.lower_macro_rules(ast).map(Into::into),
147 ast::Item::MacroDef(ast) => self.lower_macro_def(ast).map(Into::into),
148 ast::Item::ExternBlock(ast) => {
149 Some(ModItems(self.lower_extern_block(ast).into_iter().collect::<SmallVec<_>>()))
153 if !attrs.is_empty() {
154 for item in items.iter().flat_map(|items| &items.0) {
155 self.add_attrs((*item).into(), attrs.clone());
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);
167 Entry::Vacant(entry) => {
173 fn collect_inner_items(&mut self, container: &SyntaxNode) {
174 let forced_vis = self.forced_visibility.take();
176 let mut block_stack = Vec::new();
177 for event in container.preorder().skip(1) {
179 WalkEvent::Enter(node) => {
182 ast::BlockExpr(block) => {
183 block_stack.push(self.source_ast_id_map.ast_id(&block));
186 // FIXME: This triggers for macro calls in expression position
187 let mod_items = self.lower_mod_item(&item, true);
188 let current_block = block_stack.last();
189 if let (Some(mod_items), Some(block)) = (mod_items, current_block) {
190 if !mod_items.0.is_empty() {
191 self.data().inner_items.entry(*block).or_default().extend(mod_items.0.iter().copied());
199 WalkEvent::Leave(node) => {
200 if ast::BlockExpr::cast(node).is_some() {
207 self.forced_visibility = forced_vis;
210 fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
212 ast::AssocItem::Fn(ast) => self.lower_function(ast).map(Into::into),
213 ast::AssocItem::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
214 ast::AssocItem::Const(ast) => Some(self.lower_const(ast).into()),
215 ast::AssocItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
219 fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<FileItemTreeId<Struct>> {
220 let visibility = self.lower_visibility(strukt);
221 let name = strukt.name()?.as_name();
222 let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
223 let fields = self.lower_fields(&strukt.kind());
224 let ast_id = self.source_ast_id_map.ast_id(strukt);
225 let kind = match strukt.kind() {
226 ast::StructKind::Record(_) => StructDefKind::Record,
227 ast::StructKind::Tuple(_) => StructDefKind::Tuple,
228 ast::StructKind::Unit => StructDefKind::Unit,
230 let res = Struct { name, visibility, generic_params, fields, ast_id, kind };
231 Some(id(self.data().structs.alloc(res)))
234 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
236 ast::StructKind::Record(it) => {
237 let range = self.lower_record_fields(it);
238 Fields::Record(range)
240 ast::StructKind::Tuple(it) => {
241 let range = self.lower_tuple_fields(it);
244 ast::StructKind::Unit => Fields::Unit,
248 fn lower_record_fields(&mut self, fields: &ast::RecordFieldList) -> IdRange<Field> {
249 let start = self.next_field_idx();
250 for field in fields.fields() {
251 if let Some(data) = self.lower_record_field(&field) {
252 let idx = self.data().fields.alloc(data);
253 self.add_attrs(idx.into(), RawAttrs::new(&field, &self.hygiene));
256 let end = self.next_field_idx();
257 IdRange::new(start..end)
260 fn lower_record_field(&mut self, field: &ast::RecordField) -> Option<Field> {
261 let name = field.name()?.as_name();
262 let visibility = self.lower_visibility(field);
263 let type_ref = self.lower_type_ref_opt(field.ty());
264 let res = Field { name, type_ref, visibility };
268 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldList) -> IdRange<Field> {
269 let start = self.next_field_idx();
270 for (i, field) in fields.fields().enumerate() {
271 let data = self.lower_tuple_field(i, &field);
272 let idx = self.data().fields.alloc(data);
273 self.add_attrs(idx.into(), RawAttrs::new(&field, &self.hygiene));
275 let end = self.next_field_idx();
276 IdRange::new(start..end)
279 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field {
280 let name = Name::new_tuple_field(idx);
281 let visibility = self.lower_visibility(field);
282 let type_ref = self.lower_type_ref_opt(field.ty());
283 let res = Field { name, type_ref, visibility };
287 fn lower_union(&mut self, union: &ast::Union) -> Option<FileItemTreeId<Union>> {
288 let visibility = self.lower_visibility(union);
289 let name = union.name()?.as_name();
290 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
291 let fields = match union.record_field_list() {
292 Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)),
293 None => Fields::Record(IdRange::new(self.next_field_idx()..self.next_field_idx())),
295 let ast_id = self.source_ast_id_map.ast_id(union);
296 let res = Union { name, visibility, generic_params, fields, ast_id };
297 Some(id(self.data().unions.alloc(res)))
300 fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<FileItemTreeId<Enum>> {
301 let visibility = self.lower_visibility(enum_);
302 let name = enum_.name()?.as_name();
303 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
304 let variants = match &enum_.variant_list() {
305 Some(variant_list) => self.lower_variants(variant_list),
306 None => IdRange::new(self.next_variant_idx()..self.next_variant_idx()),
308 let ast_id = self.source_ast_id_map.ast_id(enum_);
309 let res = Enum { name, visibility, generic_params, variants, ast_id };
310 Some(id(self.data().enums.alloc(res)))
313 fn lower_variants(&mut self, variants: &ast::VariantList) -> IdRange<Variant> {
314 let start = self.next_variant_idx();
315 for variant in variants.variants() {
316 if let Some(data) = self.lower_variant(&variant) {
317 let idx = self.data().variants.alloc(data);
318 self.add_attrs(idx.into(), RawAttrs::new(&variant, &self.hygiene));
321 let end = self.next_variant_idx();
322 IdRange::new(start..end)
325 fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
326 let name = variant.name()?.as_name();
327 let fields = self.lower_fields(&variant.kind());
328 let res = Variant { name, fields };
332 fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
333 let visibility = self.lower_visibility(func);
334 let name = func.name()?.as_name();
336 let mut has_self_param = false;
337 let start_param = self.next_param_idx();
338 if let Some(param_list) = func.param_list() {
339 if let Some(self_param) = param_list.self_param() {
340 let self_type = match self_param.ty() {
341 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
343 let self_type = TypeRef::Path(name![Self].into());
344 match self_param.kind() {
345 ast::SelfParamKind::Owned => self_type,
346 ast::SelfParamKind::Ref => TypeRef::Reference(
348 self_param.lifetime().as_ref().map(LifetimeRef::new),
351 ast::SelfParamKind::MutRef => TypeRef::Reference(
353 self_param.lifetime().as_ref().map(LifetimeRef::new),
359 let ty = self.data().type_refs.intern(self_type);
360 let idx = self.data().params.alloc(Param::Normal(ty));
361 self.add_attrs(idx.into(), RawAttrs::new(&self_param, &self.hygiene));
362 has_self_param = true;
364 for param in param_list.params() {
365 let idx = match param.dotdotdot_token() {
366 Some(_) => self.data().params.alloc(Param::Varargs),
368 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
369 let ty = self.data().type_refs.intern(type_ref);
370 self.data().params.alloc(Param::Normal(ty))
373 self.add_attrs(idx.into(), RawAttrs::new(¶m, &self.hygiene));
376 let end_param = self.next_param_idx();
377 let params = IdRange::new(start_param..end_param);
379 let ret_type = match func.ret_type().and_then(|rt| rt.ty()) {
380 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
381 _ => TypeRef::unit(),
384 let ret_type = if func.async_token().is_some() {
385 let future_impl = desugar_future_path(ret_type);
386 let ty_bound = TypeBound::Path(future_impl);
387 TypeRef::ImplTrait(vec![ty_bound])
392 let ret_type = self.data().type_refs.intern(ret_type);
394 let has_body = func.body().is_some();
396 let ast_id = self.source_ast_id_map.ast_id(func);
397 let qualifier = FunctionQualifier {
398 is_default: func.default_token().is_some(),
399 is_const: func.const_token().is_some(),
400 is_async: func.async_token().is_some(),
401 is_unsafe: func.unsafe_token().is_some(),
402 abi: func.abi().map(|abi| {
403 // FIXME: Abi::abi() -> Option<SyntaxToken>?
404 match abi.syntax().last_token() {
405 Some(tok) if tok.kind() == SyntaxKind::STRING => {
406 // FIXME: Better way to unescape?
407 tok.text().trim_matches('"').into()
410 // `extern` default to be `extern "C"`.
416 let mut res = Function {
419 generic_params: GenericParamsId::EMPTY,
423 is_in_extern_block: false,
428 res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
430 Some(id(self.data().functions.alloc(res)))
435 type_alias: &ast::TypeAlias,
436 ) -> Option<FileItemTreeId<TypeAlias>> {
437 let name = type_alias.name()?.as_name();
438 let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
439 let visibility = self.lower_visibility(type_alias);
440 let bounds = self.lower_type_bounds(type_alias);
441 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
442 let ast_id = self.source_ast_id_map.ast_id(type_alias);
443 let res = TypeAlias {
446 bounds: bounds.into_boxed_slice(),
452 Some(id(self.data().type_aliases.alloc(res)))
455 fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
456 let name = static_.name()?.as_name();
457 let type_ref = self.lower_type_ref_opt(static_.ty());
458 let visibility = self.lower_visibility(static_);
459 let mutable = static_.mut_token().is_some();
460 let ast_id = self.source_ast_id_map.ast_id(static_);
461 let res = Static { name, visibility, mutable, type_ref, ast_id, is_extern: false };
462 Some(id(self.data().statics.alloc(res)))
465 fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
466 let name = konst.name().map(|it| it.as_name());
467 let type_ref = self.lower_type_ref_opt(konst.ty());
468 let visibility = self.lower_visibility(konst);
469 let ast_id = self.source_ast_id_map.ast_id(konst);
470 let res = Const { name, visibility, type_ref, ast_id };
471 id(self.data().consts.alloc(res))
474 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
475 let name = module.name()?.as_name();
476 let visibility = self.lower_visibility(module);
477 let kind = if module.semicolon_token().is_some() {
485 .flat_map(|item| self.lower_mod_item(&item, false))
486 .flat_map(|items| items.0)
490 cov_mark::hit!(name_res_works_for_broken_modules);
491 Box::new([]) as Box<[_]>
495 let ast_id = self.source_ast_id_map.ast_id(module);
496 let res = Mod { name, visibility, kind, ast_id };
497 Some(id(self.data().mods.alloc(res)))
500 fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
501 let name = trait_def.name()?.as_name();
502 let visibility = self.lower_visibility(trait_def);
504 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
505 let is_auto = trait_def.auto_token().is_some();
506 let is_unsafe = trait_def.unsafe_token().is_some();
507 let bounds = self.lower_type_bounds(trait_def);
508 let items = trait_def.assoc_item_list().map(|list| {
509 self.with_inherited_visibility(visibility, |this| {
512 let attrs = RawAttrs::new(&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);
522 let ast_id = self.source_ast_id_map.ast_id(trait_def);
529 bounds: bounds.into(),
530 items: items.unwrap_or_default(),
533 Some(id(self.data().traits.alloc(res)))
536 fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
538 self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
539 let target_trait = impl_def.trait_().map(|tr| self.lower_type_ref(&tr));
540 let target_type = self.lower_type_ref(&impl_def.self_ty()?);
541 let is_negative = impl_def.excl_token().is_some();
543 // We cannot use `assoc_items()` here as that does not include macro calls.
547 .flat_map(|it| it.assoc_items())
549 self.collect_inner_items(item.syntax());
550 let assoc = self.lower_assoc_item(&item)?;
551 let attrs = RawAttrs::new(&item, &self.hygiene);
552 self.add_attrs(ModItem::from(assoc).into(), attrs);
556 let ast_id = self.source_ast_id_map.ast_id(impl_def);
557 let res = Impl { generic_params, target_trait, target_type, is_negative, items, ast_id };
558 Some(id(self.data().impls.alloc(res)))
561 fn lower_use(&mut self, use_item: &ast::Use) -> Vec<FileItemTreeId<Import>> {
562 let visibility = self.lower_visibility(use_item);
563 let ast_id = self.source_ast_id_map.ast_id(use_item);
565 // Every use item can expand to many `Import`s.
566 let mut imports = Vec::new();
567 let tree = self.tree.data_mut();
568 ModPath::expand_use_item(
569 InFile::new(self.file, use_item.clone()),
571 |path, _use_tree, is_glob, alias| {
572 imports.push(id(tree.imports.alloc(Import {
578 index: imports.len(),
586 fn lower_extern_crate(
588 extern_crate: &ast::ExternCrate,
589 ) -> Option<FileItemTreeId<ExternCrate>> {
590 let name = extern_crate.name_ref()?.as_name();
591 let alias = extern_crate.rename().map(|a| {
592 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
594 let visibility = self.lower_visibility(extern_crate);
595 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
597 let res = ExternCrate { name, alias, visibility, ast_id };
598 Some(id(self.data().extern_crates.alloc(res)))
601 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
602 let path = ModPath::from_src(m.path()?, &self.hygiene)?;
603 let ast_id = self.source_ast_id_map.ast_id(m);
604 let res = MacroCall { path, ast_id };
605 Some(id(self.data().macro_calls.alloc(res)))
608 fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
609 let name = m.name().map(|it| it.as_name())?;
610 let ast_id = self.source_ast_id_map.ast_id(m);
612 let res = MacroRules { name, ast_id };
613 Some(id(self.data().macro_rules.alloc(res)))
616 fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
617 let name = m.name().map(|it| it.as_name())?;
619 let ast_id = self.source_ast_id_map.ast_id(m);
620 let visibility = self.lower_visibility(m);
622 let res = MacroDef { name, ast_id, visibility };
623 Some(id(self.data().macro_defs.alloc(res)))
626 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> Vec<ModItem> {
627 block.extern_item_list().map_or(Vec::new(), |list| {
630 self.collect_inner_items(item.syntax());
631 let attrs = RawAttrs::new(&item, &self.hygiene);
632 let id: ModItem = match item {
633 ast::ExternItem::Fn(ast) => {
634 let func_id = self.lower_function(&ast)?;
635 let func = &mut self.data().functions[func_id.index];
636 func.qualifier.is_unsafe = is_intrinsic_fn_unsafe(&func.name);
637 func.is_in_extern_block = true;
640 ast::ExternItem::Static(ast) => {
641 let statik = self.lower_static(&ast)?;
642 self.data().statics[statik.index].is_extern = true;
645 ast::ExternItem::TypeAlias(ty) => {
646 let foreign_ty = self.lower_type_alias(&ty)?;
647 self.data().type_aliases[foreign_ty.index].is_extern = true;
650 ast::ExternItem::MacroCall(_) => return None,
652 self.add_attrs(id.into(), attrs);
659 /// Lowers generics defined on `node` and collects inner items defined within.
660 fn lower_generic_params_and_inner_items(
662 owner: GenericsOwner<'_>,
663 node: &impl ast::GenericParamsOwner,
664 ) -> GenericParamsId {
665 // Generics are part of item headers and may contain inner items we need to collect.
666 if let Some(params) = node.generic_param_list() {
667 self.collect_inner_items(params.syntax());
669 if let Some(clause) = node.where_clause() {
670 self.collect_inner_items(clause.syntax());
673 self.lower_generic_params(owner, node)
676 fn lower_generic_params(
678 owner: GenericsOwner<'_>,
679 node: &impl ast::GenericParamsOwner,
680 ) -> GenericParamsId {
681 let mut sm = &mut Default::default();
682 let mut generics = GenericParams::default();
684 GenericsOwner::Function(func) => {
685 generics.fill(&self.body_ctx, sm, node);
686 // lower `impl Trait` in arguments
687 for id in func.params.clone() {
688 if let Param::Normal(ty) = self.data().params[id] {
689 let ty = self.data().type_refs.lookup(ty);
690 generics.fill_implicit_impl_trait_args(ty);
694 GenericsOwner::Struct
695 | GenericsOwner::Enum
696 | GenericsOwner::Union
697 | GenericsOwner::TypeAlias => {
698 generics.fill(&self.body_ctx, sm, node);
700 GenericsOwner::Trait(trait_def) => {
701 // traits get the Self type as an implicit first type parameter
702 let self_param_id = generics.types.alloc(TypeParamData {
703 name: Some(name![Self]),
705 provenance: TypeParamProvenance::TraitSelf,
707 sm.type_params.insert(self_param_id, Either::Left(trait_def.clone()));
708 // add super traits as bounds on Self
709 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
710 let self_param = TypeRef::Path(name![Self].into());
711 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
712 generics.fill(&self.body_ctx, &mut sm, node);
714 GenericsOwner::Impl => {
715 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
716 // type-parameter, but rather is a type-alias for impl's target
717 // type, so this is handled by the resolver.
718 generics.fill(&self.body_ctx, &mut sm, node);
722 self.data().generics.alloc(generics)
725 fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<TypeBound> {
726 match node.type_bound_list() {
727 Some(bound_list) => {
728 bound_list.bounds().map(|it| TypeBound::from_ast(&self.body_ctx, it)).collect()
734 fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
735 let vis = match self.forced_visibility {
736 Some(vis) => return vis,
737 None => RawVisibility::from_ast_with_hygiene(item.visibility(), &self.hygiene),
740 self.data().vis.alloc(vis)
743 fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Idx<TypeRef> {
744 let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
745 self.data().type_refs.intern(tyref)
747 fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Idx<TypeRef> {
748 match type_ref.map(|ty| self.lower_type_ref(&ty)) {
750 None => self.data().type_refs.intern(TypeRef::Error),
754 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
755 fn with_inherited_visibility<R>(
757 vis: RawVisibilityId,
758 f: impl FnOnce(&mut Self) -> R,
760 let old = mem::replace(&mut self.forced_visibility, Some(vis));
762 self.forced_visibility = old;
766 fn next_field_idx(&self) -> Idx<Field> {
767 Idx::from_raw(RawIdx::from(
768 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
771 fn next_variant_idx(&self) -> Idx<Variant> {
772 Idx::from_raw(RawIdx::from(
773 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
776 fn next_param_idx(&self) -> Idx<Param> {
777 Idx::from_raw(RawIdx::from(
778 self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
783 fn desugar_future_path(orig: TypeRef) -> Path {
784 let path = path![core::future::Future];
785 let mut generic_args: Vec<_> =
786 std::iter::repeat(None).take(path.segments().len() - 1).collect();
787 let mut last = GenericArgs::empty();
789 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
790 last.bindings.push(binding);
791 generic_args.push(Some(Arc::new(last)));
793 Path::from_known_path(path, generic_args)
796 enum GenericsOwner<'a> {
797 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
799 Function(&'a Function),
803 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
804 Trait(&'a ast::Trait),
809 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
810 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
811 // Should be kept in sync with https://github.com/rust-lang/rust/blob/c6e4db620a7d2f569f11dcab627430921ea8aacf/compiler/rustc_typeck/src/check/intrinsic.rs#L68
816 known::caller_location,
818 known::min_align_of_val,
819 known::add_with_overflow,
820 known::sub_with_overflow,
821 known::mul_with_overflow,
825 known::saturating_add,
826 known::saturating_sub,
834 known::discriminant_value,
838 known::ptr_guaranteed_eq,
839 known::ptr_guaranteed_ne,
846 known::variant_count,