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) => {
151 Some(ModItems(self.lower_extern_block(ast).into_iter().collect::<SmallVec<_>>()))
155 if !attrs.is_empty() {
156 for item in items.iter().flat_map(|items| &items.0) {
157 self.add_attrs((*item).into(), attrs.clone());
164 fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) {
165 match self.tree.attrs.entry(item) {
166 Entry::Occupied(mut entry) => {
167 *entry.get_mut() = entry.get().merge(attrs);
169 Entry::Vacant(entry) => {
175 fn collect_inner_items(&mut self, container: &SyntaxNode) {
176 let forced_vis = self.forced_visibility.take();
178 let mut block_stack = Vec::new();
180 // if container itself is block, add it to the stack
181 if let Some(block) = ast::BlockExpr::cast(container.clone()) {
182 block_stack.push(self.source_ast_id_map.ast_id(&block));
185 for event in container.preorder().skip(1) {
187 WalkEvent::Enter(node) => {
190 ast::BlockExpr(block) => {
191 block_stack.push(self.source_ast_id_map.ast_id(&block));
194 // FIXME: This triggers for macro calls in expression/pattern/type position
195 let mod_items = self.lower_mod_item(&item, true);
196 let current_block = block_stack.last();
197 if let (Some(mod_items), Some(block)) = (mod_items, current_block) {
198 if !mod_items.0.is_empty() {
199 self.data().inner_items.entry(*block).or_default().extend(mod_items.0.iter().copied());
207 WalkEvent::Leave(node) => {
208 if ast::BlockExpr::cast(node).is_some() {
215 self.forced_visibility = forced_vis;
218 fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
220 ast::AssocItem::Fn(ast) => self.lower_function(ast).map(Into::into),
221 ast::AssocItem::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
222 ast::AssocItem::Const(ast) => Some(self.lower_const(ast).into()),
223 ast::AssocItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
227 fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<FileItemTreeId<Struct>> {
228 let visibility = self.lower_visibility(strukt);
229 let name = strukt.name()?.as_name();
230 let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
231 let fields = self.lower_fields(&strukt.kind());
232 let ast_id = self.source_ast_id_map.ast_id(strukt);
233 let kind = match strukt.kind() {
234 ast::StructKind::Record(_) => StructDefKind::Record,
235 ast::StructKind::Tuple(_) => StructDefKind::Tuple,
236 ast::StructKind::Unit => StructDefKind::Unit,
238 let res = Struct { name, visibility, generic_params, fields, ast_id, kind };
239 Some(id(self.data().structs.alloc(res)))
242 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
244 ast::StructKind::Record(it) => {
245 let range = self.lower_record_fields(it);
246 Fields::Record(range)
248 ast::StructKind::Tuple(it) => {
249 let range = self.lower_tuple_fields(it);
252 ast::StructKind::Unit => Fields::Unit,
256 fn lower_record_fields(&mut self, fields: &ast::RecordFieldList) -> IdRange<Field> {
257 let start = self.next_field_idx();
258 for field in fields.fields() {
259 if let Some(data) = self.lower_record_field(&field) {
260 let idx = self.data().fields.alloc(data);
261 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, &self.hygiene));
264 let end = self.next_field_idx();
265 IdRange::new(start..end)
268 fn lower_record_field(&mut self, field: &ast::RecordField) -> Option<Field> {
269 let name = field.name()?.as_name();
270 let visibility = self.lower_visibility(field);
271 let type_ref = self.lower_type_ref_opt(field.ty());
272 let res = Field { name, type_ref, visibility };
276 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldList) -> IdRange<Field> {
277 let start = self.next_field_idx();
278 for (i, field) in fields.fields().enumerate() {
279 let data = self.lower_tuple_field(i, &field);
280 let idx = self.data().fields.alloc(data);
281 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, &self.hygiene));
283 let end = self.next_field_idx();
284 IdRange::new(start..end)
287 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field {
288 let name = Name::new_tuple_field(idx);
289 let visibility = self.lower_visibility(field);
290 let type_ref = self.lower_type_ref_opt(field.ty());
291 let res = Field { name, type_ref, visibility };
295 fn lower_union(&mut self, union: &ast::Union) -> Option<FileItemTreeId<Union>> {
296 let visibility = self.lower_visibility(union);
297 let name = union.name()?.as_name();
298 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
299 let fields = match union.record_field_list() {
300 Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)),
301 None => Fields::Record(IdRange::new(self.next_field_idx()..self.next_field_idx())),
303 let ast_id = self.source_ast_id_map.ast_id(union);
304 let res = Union { name, visibility, generic_params, fields, ast_id };
305 Some(id(self.data().unions.alloc(res)))
308 fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<FileItemTreeId<Enum>> {
309 let visibility = self.lower_visibility(enum_);
310 let name = enum_.name()?.as_name();
311 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
312 let variants = match &enum_.variant_list() {
313 Some(variant_list) => self.lower_variants(variant_list),
314 None => IdRange::new(self.next_variant_idx()..self.next_variant_idx()),
316 let ast_id = self.source_ast_id_map.ast_id(enum_);
317 let res = Enum { name, visibility, generic_params, variants, ast_id };
318 Some(id(self.data().enums.alloc(res)))
321 fn lower_variants(&mut self, variants: &ast::VariantList) -> IdRange<Variant> {
322 let start = self.next_variant_idx();
323 for variant in variants.variants() {
324 if let Some(data) = self.lower_variant(&variant) {
325 let idx = self.data().variants.alloc(data);
326 self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, &self.hygiene));
329 let end = self.next_variant_idx();
330 IdRange::new(start..end)
333 fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
334 let name = variant.name()?.as_name();
335 let fields = self.lower_fields(&variant.kind());
336 let res = Variant { name, fields };
340 fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
341 let visibility = self.lower_visibility(func);
342 let name = func.name()?.as_name();
344 let mut has_self_param = false;
345 let start_param = self.next_param_idx();
346 if let Some(param_list) = func.param_list() {
347 if let Some(self_param) = param_list.self_param() {
348 let self_type = match self_param.ty() {
349 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
351 let self_type = TypeRef::Path(name![Self].into());
352 match self_param.kind() {
353 ast::SelfParamKind::Owned => self_type,
354 ast::SelfParamKind::Ref => TypeRef::Reference(
356 self_param.lifetime().as_ref().map(LifetimeRef::new),
359 ast::SelfParamKind::MutRef => TypeRef::Reference(
361 self_param.lifetime().as_ref().map(LifetimeRef::new),
367 let ty = Interned::new(self_type);
368 let idx = self.data().params.alloc(Param::Normal(ty));
369 self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, &self.hygiene));
370 has_self_param = true;
372 for param in param_list.params() {
373 let idx = match param.dotdotdot_token() {
374 Some(_) => self.data().params.alloc(Param::Varargs),
376 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
377 let ty = Interned::new(type_ref);
378 self.data().params.alloc(Param::Normal(ty))
381 self.add_attrs(idx.into(), RawAttrs::new(self.db, ¶m, &self.hygiene));
384 let end_param = self.next_param_idx();
385 let params = IdRange::new(start_param..end_param);
387 let ret_type = match func.ret_type().and_then(|rt| rt.ty()) {
388 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
389 _ => TypeRef::unit(),
392 let ret_type = if func.async_token().is_some() {
393 let future_impl = desugar_future_path(ret_type);
394 let ty_bound = TypeBound::Path(future_impl);
395 TypeRef::ImplTrait(vec![ty_bound])
400 let abi = func.abi().map(|abi| {
401 // FIXME: Abi::abi() -> Option<SyntaxToken>?
402 match abi.syntax().last_token() {
403 Some(tok) if tok.kind() == SyntaxKind::STRING => {
404 // FIXME: Better way to unescape?
405 Interned::new_str(tok.text().trim_matches('"'))
408 // `extern` default to be `extern "C"`.
409 Interned::new_str("C")
414 let ast_id = self.source_ast_id_map.ast_id(func);
416 let mut flags = FnFlags::default();
417 if func.body().is_some() {
418 flags.bits |= FnFlags::HAS_BODY;
421 flags.bits |= FnFlags::HAS_SELF_PARAM;
423 if func.default_token().is_some() {
424 flags.bits |= FnFlags::IS_DEFAULT;
426 if func.const_token().is_some() {
427 flags.bits |= FnFlags::IS_CONST;
429 if func.async_token().is_some() {
430 flags.bits |= FnFlags::IS_ASYNC;
432 if func.unsafe_token().is_some() {
433 flags.bits |= FnFlags::IS_UNSAFE;
436 let mut res = Function {
439 generic_params: Interned::new(GenericParams::default()),
442 ret_type: Interned::new(ret_type),
446 res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
448 Some(id(self.data().functions.alloc(res)))
453 type_alias: &ast::TypeAlias,
454 ) -> Option<FileItemTreeId<TypeAlias>> {
455 let name = type_alias.name()?.as_name();
456 let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
457 let visibility = self.lower_visibility(type_alias);
458 let bounds = self.lower_type_bounds(type_alias);
459 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
460 let ast_id = self.source_ast_id_map.ast_id(type_alias);
461 let res = TypeAlias {
464 bounds: bounds.into_boxed_slice(),
470 Some(id(self.data().type_aliases.alloc(res)))
473 fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
474 let name = static_.name()?.as_name();
475 let type_ref = self.lower_type_ref_opt(static_.ty());
476 let visibility = self.lower_visibility(static_);
477 let mutable = static_.mut_token().is_some();
478 let ast_id = self.source_ast_id_map.ast_id(static_);
479 let res = Static { name, visibility, mutable, type_ref, ast_id, is_extern: false };
480 Some(id(self.data().statics.alloc(res)))
483 fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
484 let name = konst.name().map(|it| it.as_name());
485 let type_ref = self.lower_type_ref_opt(konst.ty());
486 let visibility = self.lower_visibility(konst);
487 let ast_id = self.source_ast_id_map.ast_id(konst);
488 let res = Const { name, visibility, type_ref, ast_id };
489 id(self.data().consts.alloc(res))
492 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
493 let name = module.name()?.as_name();
494 let visibility = self.lower_visibility(module);
495 let kind = if module.semicolon_token().is_some() {
503 .flat_map(|item| self.lower_mod_item(&item, false))
504 .flat_map(|items| items.0)
508 cov_mark::hit!(name_res_works_for_broken_modules);
509 Box::new([]) as Box<[_]>
513 let ast_id = self.source_ast_id_map.ast_id(module);
514 let res = Mod { name, visibility, kind, ast_id };
515 Some(id(self.data().mods.alloc(res)))
518 fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
519 let name = trait_def.name()?.as_name();
520 let visibility = self.lower_visibility(trait_def);
522 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
523 let is_auto = trait_def.auto_token().is_some();
524 let is_unsafe = trait_def.unsafe_token().is_some();
525 let bounds = self.lower_type_bounds(trait_def);
526 let items = trait_def.assoc_item_list().map(|list| {
528 self.with_inherited_visibility(visibility, |this| {
531 let attrs = RawAttrs::new(db, &item, &this.hygiene);
532 this.collect_inner_items(item.syntax());
533 this.lower_assoc_item(&item).map(|item| {
534 this.add_attrs(ModItem::from(item).into(), attrs);
541 let ast_id = self.source_ast_id_map.ast_id(trait_def);
548 bounds: bounds.into(),
549 items: items.unwrap_or_default(),
552 Some(id(self.data().traits.alloc(res)))
555 fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
557 self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
558 // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
559 // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
561 let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
562 let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
563 let is_negative = impl_def.excl_token().is_some();
565 // We cannot use `assoc_items()` here as that does not include macro calls.
569 .flat_map(|it| it.assoc_items())
571 self.collect_inner_items(item.syntax());
572 let assoc = self.lower_assoc_item(&item)?;
573 let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
574 self.add_attrs(ModItem::from(assoc).into(), attrs);
578 let ast_id = self.source_ast_id_map.ast_id(impl_def);
579 let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
580 Some(id(self.data().impls.alloc(res)))
583 fn lower_use(&mut self, use_item: &ast::Use) -> Vec<FileItemTreeId<Import>> {
584 let visibility = self.lower_visibility(use_item);
585 let ast_id = self.source_ast_id_map.ast_id(use_item);
587 // Every use item can expand to many `Import`s.
588 let mut imports = Vec::new();
589 let tree = self.tree.data_mut();
590 ModPath::expand_use_item(
592 InFile::new(self.file, use_item.clone()),
594 |path, _use_tree, is_glob, alias| {
595 imports.push(id(tree.imports.alloc(Import {
596 path: Interned::new(path),
601 index: imports.len(),
609 fn lower_extern_crate(
611 extern_crate: &ast::ExternCrate,
612 ) -> Option<FileItemTreeId<ExternCrate>> {
613 let name = extern_crate.name_ref()?.as_name();
614 let alias = extern_crate.rename().map(|a| {
615 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
617 let visibility = self.lower_visibility(extern_crate);
618 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
620 let res = ExternCrate { name, alias, visibility, ast_id };
621 Some(id(self.data().extern_crates.alloc(res)))
624 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
625 let path = Interned::new(ModPath::from_src(self.db, m.path()?, &self.hygiene)?);
626 let ast_id = self.source_ast_id_map.ast_id(m);
627 let fragment = hir_expand::to_fragment_kind(m);
628 let res = MacroCall { path, ast_id, fragment };
629 Some(id(self.data().macro_calls.alloc(res)))
632 fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
633 let name = m.name().map(|it| it.as_name())?;
634 let ast_id = self.source_ast_id_map.ast_id(m);
636 let res = MacroRules { name, ast_id };
637 Some(id(self.data().macro_rules.alloc(res)))
640 fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
641 let name = m.name().map(|it| it.as_name())?;
643 let ast_id = self.source_ast_id_map.ast_id(m);
644 let visibility = self.lower_visibility(m);
646 let res = MacroDef { name, ast_id, visibility };
647 Some(id(self.data().macro_defs.alloc(res)))
650 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> Vec<ModItem> {
651 block.extern_item_list().map_or(Vec::new(), |list| {
654 self.collect_inner_items(item.syntax());
655 let attrs = RawAttrs::new(self.db, &item, &self.hygiene);
656 let id: ModItem = match item {
657 ast::ExternItem::Fn(ast) => {
658 let func_id = self.lower_function(&ast)?;
659 let func = &mut self.data().functions[func_id.index];
660 if is_intrinsic_fn_unsafe(&func.name) {
661 func.flags.bits |= FnFlags::IS_UNSAFE;
663 func.flags.bits |= FnFlags::IS_IN_EXTERN_BLOCK;
666 ast::ExternItem::Static(ast) => {
667 let statik = self.lower_static(&ast)?;
668 self.data().statics[statik.index].is_extern = true;
671 ast::ExternItem::TypeAlias(ty) => {
672 let foreign_ty = self.lower_type_alias(&ty)?;
673 self.data().type_aliases[foreign_ty.index].is_extern = true;
676 ast::ExternItem::MacroCall(_) => return None,
678 self.add_attrs(id.into(), attrs);
685 /// Lowers generics defined on `node` and collects inner items defined within.
686 fn lower_generic_params_and_inner_items(
688 owner: GenericsOwner<'_>,
689 node: &impl ast::GenericParamsOwner,
690 ) -> Interned<GenericParams> {
691 // Generics are part of item headers and may contain inner items we need to collect.
692 if let Some(params) = node.generic_param_list() {
693 self.collect_inner_items(params.syntax());
695 if let Some(clause) = node.where_clause() {
696 self.collect_inner_items(clause.syntax());
699 self.lower_generic_params(owner, node)
702 fn lower_generic_params(
704 owner: GenericsOwner<'_>,
705 node: &impl ast::GenericParamsOwner,
706 ) -> Interned<GenericParams> {
707 let mut sm = &mut Default::default();
708 let mut generics = GenericParams::default();
710 GenericsOwner::Function(func) => {
711 generics.fill(&self.body_ctx, sm, node);
712 // lower `impl Trait` in arguments
713 for id in func.params.clone() {
714 if let Param::Normal(ty) = &self.data().params[id] {
715 generics.fill_implicit_impl_trait_args(ty);
719 GenericsOwner::Struct
720 | GenericsOwner::Enum
721 | GenericsOwner::Union
722 | GenericsOwner::TypeAlias => {
723 generics.fill(&self.body_ctx, sm, node);
725 GenericsOwner::Trait(trait_def) => {
726 // traits get the Self type as an implicit first type parameter
727 let self_param_id = generics.types.alloc(TypeParamData {
728 name: Some(name![Self]),
730 provenance: TypeParamProvenance::TraitSelf,
732 sm.type_params.insert(self_param_id, Either::Left(trait_def.clone()));
733 // add super traits as bounds on Self
734 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
735 let self_param = TypeRef::Path(name![Self].into());
736 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
737 generics.fill(&self.body_ctx, &mut sm, node);
739 GenericsOwner::Impl => {
740 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
741 // type-parameter, but rather is a type-alias for impl's target
742 // type, so this is handled by the resolver.
743 generics.fill(&self.body_ctx, &mut sm, node);
747 generics.shrink_to_fit();
748 Interned::new(generics)
751 fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<TypeBound> {
752 match node.type_bound_list() {
753 Some(bound_list) => {
754 bound_list.bounds().map(|it| TypeBound::from_ast(&self.body_ctx, it)).collect()
760 fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
761 let vis = match self.forced_visibility {
762 Some(vis) => return vis,
763 None => RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), &self.hygiene),
766 self.data().vis.alloc(vis)
769 fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
770 let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
771 Some(Interned::new(trait_ref))
774 fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
775 let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
779 fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
780 match type_ref.map(|ty| self.lower_type_ref(&ty)) {
782 None => Interned::new(TypeRef::Error),
786 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
787 fn with_inherited_visibility<R>(
789 vis: RawVisibilityId,
790 f: impl FnOnce(&mut Self) -> R,
792 let old = mem::replace(&mut self.forced_visibility, Some(vis));
794 self.forced_visibility = old;
798 fn next_field_idx(&self) -> Idx<Field> {
799 Idx::from_raw(RawIdx::from(
800 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
803 fn next_variant_idx(&self) -> Idx<Variant> {
804 Idx::from_raw(RawIdx::from(
805 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
808 fn next_param_idx(&self) -> Idx<Param> {
809 Idx::from_raw(RawIdx::from(
810 self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
815 fn desugar_future_path(orig: TypeRef) -> Path {
816 let path = path![core::future::Future];
817 let mut generic_args: Vec<_> =
818 std::iter::repeat(None).take(path.segments().len() - 1).collect();
819 let mut last = GenericArgs::empty();
821 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
822 last.bindings.push(binding);
823 generic_args.push(Some(Arc::new(last)));
825 Path::from_known_path(path, generic_args)
828 enum GenericsOwner<'a> {
829 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
831 Function(&'a Function),
835 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
836 Trait(&'a ast::Trait),
841 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
842 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
843 // Should be kept in sync with https://github.com/rust-lang/rust/blob/c6e4db620a7d2f569f11dcab627430921ea8aacf/compiler/rustc_typeck/src/check/intrinsic.rs#L68
848 known::caller_location,
850 known::min_align_of_val,
851 known::add_with_overflow,
852 known::sub_with_overflow,
853 known::mul_with_overflow,
857 known::saturating_add,
858 known::saturating_sub,
866 known::discriminant_value,
870 known::ptr_guaranteed_eq,
871 known::ptr_guaranteed_ne,
878 known::variant_count,