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, TraitRef},
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<'a> {
35 db: &'a dyn DefDatabase,
39 source_ast_id_map: Arc<AstIdMap>,
40 body_ctx: crate::body::LowerCtx<'a>,
41 forced_visibility: Option<RawVisibilityId>,
45 pub(super) fn new(db: &'a dyn DefDatabase, hygiene: Hygiene, file: HirFileId) -> Self {
48 tree: ItemTree::default(),
51 source_ast_id_map: db.ast_id_map(file),
52 body_ctx: crate::body::LowerCtx::new(db, file),
53 forced_visibility: None,
57 pub(super) fn lower_module_items(mut self, item_owner: &dyn ModuleItemOwner) -> ItemTree {
58 self.tree.top_level = item_owner
60 .flat_map(|item| self.lower_mod_item(&item, false))
61 .flat_map(|items| items.0)
66 pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
67 self.tree.top_level = stmts
69 .filter_map(|stmt| match stmt {
70 ast::Stmt::Item(item) => Some(item),
73 .flat_map(|item| self.lower_mod_item(&item, false))
74 .flat_map(|items| items.0)
77 // Non-items need to have their inner items collected.
78 for stmt in stmts.statements() {
80 ast::Stmt::ExprStmt(_) | ast::Stmt::LetStmt(_) => {
81 self.collect_inner_items(stmt.syntax())
86 if let Some(expr) = stmts.expr() {
87 self.collect_inner_items(expr.syntax());
92 pub(super) fn lower_inner_items(mut self, within: &SyntaxNode) -> ItemTree {
93 self.collect_inner_items(within);
97 fn data(&mut self) -> &mut ItemTreeData {
101 fn lower_mod_item(&mut self, item: &ast::Item, inner: bool) -> Option<ModItems> {
102 // Collect inner items for 1-to-1-lowered items.
105 | ast::Item::Union(_)
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
114 self.collect_inner_items(item.syntax());
118 // These are handled in their respective `lower_X` method (since we can't just blindly
120 ast::Item::Trait(_) | ast::Item::Impl(_) | ast::Item::ExternBlock(_) => {}
122 // These don't have inner items.
124 | ast::Item::ExternCrate(_)
126 | ast::Item::MacroCall(_)
127 | ast::Item::MacroRules(_)
128 | ast::Item::MacroDef(_) => {}
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<_>>(),
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()),
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();
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));
183 for event in container.preorder().skip(1) {
185 WalkEvent::Enter(node) => {
188 ast::BlockExpr(block) => {
189 block_stack.push(self.source_ast_id_map.ast_id(&block));
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());
205 WalkEvent::Leave(node) => {
206 if ast::BlockExpr::cast(node).is_some() {
213 self.forced_visibility = forced_vis;
216 fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
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),
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)))
235 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
237 ast::StructKind::Record(it) => {
238 let range = self.lower_record_fields(it);
239 Fields::Record(range)
241 ast::StructKind::Tuple(it) => {
242 let range = self.lower_tuple_fields(it);
245 ast::StructKind::Unit => Fields::Unit,
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));
257 let end = self.next_field_idx();
258 IdRange::new(start..end)
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 };
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));
276 let end = self.next_field_idx();
277 IdRange::new(start..end)
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 };
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())),
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)))
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()),
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)))
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));
322 let end = self.next_variant_idx();
323 IdRange::new(start..end)
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 };
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();
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),
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(
349 self_param.lifetime().as_ref().map(LifetimeRef::new),
352 ast::SelfParamKind::MutRef => TypeRef::Reference(
354 self_param.lifetime().as_ref().map(LifetimeRef::new),
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;
365 for param in param_list.params() {
366 let idx = match param.dotdotdot_token() {
367 Some(_) => self.data().params.alloc(Param::Varargs),
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))
374 self.add_attrs(idx.into(), RawAttrs::new(self.db, ¶m, &self.hygiene));
377 let end_param = self.next_param_idx();
378 let params = IdRange::new(start_param..end_param);
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(),
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])
393 let abi = func.abi().map(lower_abi);
395 let ast_id = self.source_ast_id_map.ast_id(func);
397 let mut flags = FnFlags::default();
398 if func.body().is_some() {
399 flags.bits |= FnFlags::HAS_BODY;
402 flags.bits |= FnFlags::HAS_SELF_PARAM;
404 if func.default_token().is_some() {
405 flags.bits |= FnFlags::IS_DEFAULT;
407 if func.const_token().is_some() {
408 flags.bits |= FnFlags::IS_CONST;
410 if func.async_token().is_some() {
411 flags.bits |= FnFlags::IS_ASYNC;
413 if func.unsafe_token().is_some() {
414 flags.bits |= FnFlags::IS_UNSAFE;
417 let mut res = Function {
420 generic_params: Interned::new(GenericParams::default()),
423 ret_type: Interned::new(ret_type),
427 res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
429 Some(id(self.data().functions.alloc(res)))
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 {
445 bounds: bounds.into_boxed_slice(),
451 Some(id(self.data().type_aliases.alloc(res)))
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)))
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))
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() {
484 .flat_map(|item| self.lower_mod_item(&item, false))
485 .flat_map(|items| items.0)
489 cov_mark::hit!(name_res_works_for_broken_modules);
490 Box::new([]) as Box<[_]>
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)))
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);
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| {
509 self.with_inherited_visibility(visibility, |this| {
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);
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 // 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
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();
546 // We cannot use `assoc_items()` here as that does not include macro calls.
550 .flat_map(|it| it.assoc_items())
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);
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)))
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);
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(
573 InFile::new(self.file, use_item.clone()),
575 |path, _use_tree, is_glob, alias| {
576 imports.push(id(tree.imports.alloc(Import {
577 path: Interned::new(path),
582 index: imports.len(),
590 fn lower_extern_crate(
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)
598 let visibility = self.lower_visibility(extern_crate);
599 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
601 let res = ExternCrate { name, alias, visibility, ast_id };
602 Some(id(self.data().extern_crates.alloc(res)))
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)))
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);
617 let res = MacroRules { name, ast_id };
618 Some(id(self.data().macro_rules.alloc(res)))
621 fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
622 let name = m.name().map(|it| it.as_name())?;
624 let ast_id = self.source_ast_id_map.ast_id(m);
625 let visibility = self.lower_visibility(m);
627 let res = MacroDef { name, ast_id, visibility };
628 Some(id(self.data().macro_defs.alloc(res)))
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| {
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;
646 func.flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
649 ast::ExternItem::Static(ast) => {
650 let statik = self.lower_static(&ast)?;
651 self.data().statics[statik.index].is_extern = true;
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;
659 ast::ExternItem::MacroCall(call) => {
660 // FIXME: we need some way of tracking that the macro call is in an
662 self.lower_macro_call(&call)?.into()
665 self.add_attrs(id.into(), attrs);
671 let res = ExternBlock { abi, ast_id, children };
672 id(self.data().extern_blocks.alloc(res))
675 /// Lowers generics defined on `node` and collects inner items defined within.
676 fn lower_generic_params_and_inner_items(
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());
685 if let Some(clause) = node.where_clause() {
686 self.collect_inner_items(clause.syntax());
689 self.lower_generic_params(owner, node)
692 fn lower_generic_params(
694 owner: GenericsOwner<'_>,
695 node: &impl ast::GenericParamsOwner,
696 ) -> Interned<GenericParams> {
697 let mut sm = &mut Default::default();
698 let mut generics = GenericParams::default();
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);
709 GenericsOwner::Struct
710 | GenericsOwner::Enum
711 | GenericsOwner::Union
712 | GenericsOwner::TypeAlias => {
713 generics.fill(&self.body_ctx, sm, node);
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]),
720 provenance: TypeParamProvenance::TraitSelf,
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);
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);
737 generics.shrink_to_fit();
738 Interned::new(generics)
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
745 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
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),
757 self.data().vis.alloc(vis)
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))
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());
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)) {
773 None => Interned::new(TypeRef::Error),
777 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
778 fn with_inherited_visibility<R>(
780 vis: RawVisibilityId,
781 f: impl FnOnce(&mut Self) -> R,
783 let old = mem::replace(&mut self.forced_visibility, Some(vis));
785 self.forced_visibility = old;
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),
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),
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),
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();
812 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
813 last.bindings.push(binding);
814 generic_args.push(Some(Arc::new(last)));
816 Path::from_known_path(path, generic_args)
819 enum GenericsOwner<'a> {
820 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
822 Function(&'a Function),
826 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
827 Trait(&'a ast::Trait),
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
839 known::caller_location,
841 known::min_align_of_val,
842 known::add_with_overflow,
843 known::sub_with_overflow,
844 known::mul_with_overflow,
848 known::saturating_add,
849 known::saturating_sub,
857 known::discriminant_value,
861 known::ptr_guaranteed_eq,
862 known::ptr_guaranteed_ne,
869 known::variant_count,
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('"'))
882 // `extern` default to be `extern "C"`.
883 Interned::new_str("C")