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 syntax::ast::{self, HasModuleItem};
9 generics::{GenericParams, TypeParamData, TypeParamProvenance},
10 type_ref::{LifetimeRef, TraitBoundModifier, TraitRef},
15 fn id<N: ItemTreeNode>(index: Idx<N>) -> FileItemTreeId<N> {
16 FileItemTreeId { index, _p: PhantomData }
19 pub(super) struct Ctx<'a> {
20 db: &'a dyn DefDatabase,
22 source_ast_id_map: Arc<AstIdMap>,
23 body_ctx: crate::body::LowerCtx<'a>,
24 forced_visibility: Option<RawVisibilityId>,
28 pub(super) fn new(db: &'a dyn DefDatabase, file: HirFileId) -> Self {
31 tree: ItemTree::default(),
32 source_ast_id_map: db.ast_id_map(file),
33 body_ctx: crate::body::LowerCtx::new(db, file),
34 forced_visibility: None,
38 pub(super) fn hygiene(&self) -> &Hygiene {
39 self.body_ctx.hygiene()
42 pub(super) fn lower_module_items(mut self, item_owner: &dyn HasModuleItem) -> ItemTree {
44 item_owner.items().flat_map(|item| self.lower_mod_item(&item)).collect();
48 pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
49 self.tree.top_level = stmts
51 .filter_map(|stmt| match stmt {
52 ast::Stmt::Item(item) => Some(item),
53 // Macro calls can be both items and expressions. The syntax library always treats
54 // them as expressions here, so we undo that.
55 ast::Stmt::ExprStmt(es) => match es.expr()? {
56 ast::Expr::MacroCall(call) => {
57 cov_mark::hit!(macro_call_in_macro_stmts_is_added_to_item_tree);
64 .flat_map(|item| self.lower_mod_item(&item))
70 pub(super) fn lower_block(mut self, block: &ast::BlockExpr) -> ItemTree {
71 self.tree.top_level = block
73 .filter_map(|stmt| match stmt {
74 ast::Stmt::Item(item) => self.lower_mod_item(&item),
75 // Macro calls can be both items and expressions. The syntax library always treats
76 // them as expressions here, so we undo that.
77 ast::Stmt::ExprStmt(es) => match es.expr()? {
78 ast::Expr::MacroCall(call) => self.lower_mod_item(&call.into()),
88 fn data(&mut self) -> &mut ItemTreeData {
92 fn lower_mod_item(&mut self, item: &ast::Item) -> Option<ModItem> {
93 let attrs = RawAttrs::new(self.db, item, self.hygiene());
94 let item: ModItem = match item {
95 ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
96 ast::Item::Union(ast) => self.lower_union(ast)?.into(),
97 ast::Item::Enum(ast) => self.lower_enum(ast)?.into(),
98 ast::Item::Fn(ast) => self.lower_function(ast)?.into(),
99 ast::Item::TypeAlias(ast) => self.lower_type_alias(ast)?.into(),
100 ast::Item::Static(ast) => self.lower_static(ast)?.into(),
101 ast::Item::Const(ast) => self.lower_const(ast).into(),
102 ast::Item::Module(ast) => self.lower_module(ast)?.into(),
103 ast::Item::Trait(ast) => self.lower_trait(ast)?.into(),
104 ast::Item::Impl(ast) => self.lower_impl(ast)?.into(),
105 ast::Item::Use(ast) => self.lower_use(ast)?.into(),
106 ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast)?.into(),
107 ast::Item::MacroCall(ast) => self.lower_macro_call(ast)?.into(),
108 ast::Item::MacroRules(ast) => self.lower_macro_rules(ast)?.into(),
109 ast::Item::MacroDef(ast) => self.lower_macro_def(ast)?.into(),
110 ast::Item::ExternBlock(ast) => self.lower_extern_block(ast).into(),
113 self.add_attrs(item.into(), attrs);
118 fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) {
119 match self.tree.attrs.entry(item) {
120 Entry::Occupied(mut entry) => {
121 *entry.get_mut() = entry.get().merge(attrs);
123 Entry::Vacant(entry) => {
129 fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
131 ast::AssocItem::Fn(ast) => self.lower_function(ast).map(Into::into),
132 ast::AssocItem::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
133 ast::AssocItem::Const(ast) => Some(self.lower_const(ast).into()),
134 ast::AssocItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
138 fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<FileItemTreeId<Struct>> {
139 let visibility = self.lower_visibility(strukt);
140 let name = strukt.name()?.as_name();
141 let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
142 let fields = self.lower_fields(&strukt.kind());
143 let ast_id = self.source_ast_id_map.ast_id(strukt);
144 let res = Struct { name, visibility, generic_params, fields, ast_id };
145 Some(id(self.data().structs.alloc(res)))
148 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
150 ast::StructKind::Record(it) => {
151 let range = self.lower_record_fields(it);
152 Fields::Record(range)
154 ast::StructKind::Tuple(it) => {
155 let range = self.lower_tuple_fields(it);
158 ast::StructKind::Unit => Fields::Unit,
162 fn lower_record_fields(&mut self, fields: &ast::RecordFieldList) -> IdxRange<Field> {
163 let start = self.next_field_idx();
164 for field in fields.fields() {
165 if let Some(data) = self.lower_record_field(&field) {
166 let idx = self.data().fields.alloc(data);
167 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
170 let end = self.next_field_idx();
171 IdxRange::new(start..end)
174 fn lower_record_field(&mut self, field: &ast::RecordField) -> Option<Field> {
175 let name = field.name()?.as_name();
176 let visibility = self.lower_visibility(field);
177 let type_ref = self.lower_type_ref_opt(field.ty());
178 let res = Field { name, type_ref, visibility };
182 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldList) -> IdxRange<Field> {
183 let start = self.next_field_idx();
184 for (i, field) in fields.fields().enumerate() {
185 let data = self.lower_tuple_field(i, &field);
186 let idx = self.data().fields.alloc(data);
187 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
189 let end = self.next_field_idx();
190 IdxRange::new(start..end)
193 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field {
194 let name = Name::new_tuple_field(idx);
195 let visibility = self.lower_visibility(field);
196 let type_ref = self.lower_type_ref_opt(field.ty());
197 Field { name, type_ref, visibility }
200 fn lower_union(&mut self, union: &ast::Union) -> Option<FileItemTreeId<Union>> {
201 let visibility = self.lower_visibility(union);
202 let name = union.name()?.as_name();
203 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
204 let fields = match union.record_field_list() {
205 Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)),
206 None => Fields::Record(IdxRange::new(self.next_field_idx()..self.next_field_idx())),
208 let ast_id = self.source_ast_id_map.ast_id(union);
209 let res = Union { name, visibility, generic_params, fields, ast_id };
210 Some(id(self.data().unions.alloc(res)))
213 fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<FileItemTreeId<Enum>> {
214 let visibility = self.lower_visibility(enum_);
215 let name = enum_.name()?.as_name();
216 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
218 self.with_inherited_visibility(visibility, |this| match &enum_.variant_list() {
219 Some(variant_list) => this.lower_variants(variant_list),
220 None => IdxRange::new(this.next_variant_idx()..this.next_variant_idx()),
222 let ast_id = self.source_ast_id_map.ast_id(enum_);
223 let res = Enum { name, visibility, generic_params, variants, ast_id };
224 Some(id(self.data().enums.alloc(res)))
227 fn lower_variants(&mut self, variants: &ast::VariantList) -> IdxRange<Variant> {
228 let start = self.next_variant_idx();
229 for variant in variants.variants() {
230 if let Some(data) = self.lower_variant(&variant) {
231 let idx = self.data().variants.alloc(data);
232 self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, self.hygiene()));
235 let end = self.next_variant_idx();
236 IdxRange::new(start..end)
239 fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
240 let name = variant.name()?.as_name();
241 let fields = self.lower_fields(&variant.kind());
242 let res = Variant { name, fields };
246 fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
247 let visibility = self.lower_visibility(func);
248 let name = func.name()?.as_name();
250 let mut has_self_param = false;
251 let start_param = self.next_param_idx();
252 if let Some(param_list) = func.param_list() {
253 if let Some(self_param) = param_list.self_param() {
254 let self_type = match self_param.ty() {
255 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
257 let self_type = TypeRef::Path(name![Self].into());
258 match self_param.kind() {
259 ast::SelfParamKind::Owned => self_type,
260 ast::SelfParamKind::Ref => TypeRef::Reference(
262 self_param.lifetime().as_ref().map(LifetimeRef::new),
265 ast::SelfParamKind::MutRef => TypeRef::Reference(
267 self_param.lifetime().as_ref().map(LifetimeRef::new),
273 let ty = Interned::new(self_type);
274 let idx = self.data().params.alloc(Param::Normal(None, ty));
275 self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, self.hygiene()));
276 has_self_param = true;
278 for param in param_list.params() {
279 let idx = match param.dotdotdot_token() {
280 Some(_) => self.data().params.alloc(Param::Varargs),
282 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
283 let ty = Interned::new(type_ref);
284 let mut pat = param.pat();
285 // FIXME: This really shouldn't be here, in fact FunctionData/ItemTree's function shouldn't know about
286 // pattern names at all
289 Some(ast::Pat::RefPat(ref_pat)) => pat = ref_pat.pat(),
290 Some(ast::Pat::IdentPat(ident)) => {
291 break ident.name().map(|it| it.as_name())
296 self.data().params.alloc(Param::Normal(name, ty))
299 self.add_attrs(idx.into(), RawAttrs::new(self.db, ¶m, self.hygiene()));
302 let end_param = self.next_param_idx();
303 let params = IdxRange::new(start_param..end_param);
305 let ret_type = match func.ret_type().and_then(|rt| rt.ty()) {
306 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
307 _ => TypeRef::unit(),
310 let (ret_type, async_ret_type) = if func.async_token().is_some() {
311 let async_ret_type = ret_type.clone();
312 let future_impl = desugar_future_path(ret_type);
313 let ty_bound = Interned::new(TypeBound::Path(future_impl, TraitBoundModifier::None));
314 (TypeRef::ImplTrait(vec![ty_bound]), Some(async_ret_type))
319 let abi = func.abi().map(lower_abi);
321 let ast_id = self.source_ast_id_map.ast_id(func);
323 let mut flags = FnFlags::default();
324 if func.body().is_some() {
325 flags.bits |= FnFlags::HAS_BODY;
328 flags.bits |= FnFlags::HAS_SELF_PARAM;
330 if func.default_token().is_some() {
331 flags.bits |= FnFlags::IS_DEFAULT;
333 if func.const_token().is_some() {
334 flags.bits |= FnFlags::IS_CONST;
336 if func.async_token().is_some() {
337 flags.bits |= FnFlags::IS_ASYNC;
339 if func.unsafe_token().is_some() {
340 flags.bits |= FnFlags::IS_UNSAFE;
343 let mut res = Function {
346 explicit_generic_params: Interned::new(GenericParams::default()),
349 ret_type: Interned::new(ret_type),
350 async_ret_type: async_ret_type.map(Interned::new),
354 res.explicit_generic_params =
355 self.lower_generic_params(GenericsOwner::Function(&res), func);
357 Some(id(self.data().functions.alloc(res)))
362 type_alias: &ast::TypeAlias,
363 ) -> Option<FileItemTreeId<TypeAlias>> {
364 let name = type_alias.name()?.as_name();
365 let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
366 let visibility = self.lower_visibility(type_alias);
367 let bounds = self.lower_type_bounds(type_alias);
368 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
369 let ast_id = self.source_ast_id_map.ast_id(type_alias);
370 let res = TypeAlias {
373 bounds: bounds.into_boxed_slice(),
378 Some(id(self.data().type_aliases.alloc(res)))
381 fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
382 let name = static_.name()?.as_name();
383 let type_ref = self.lower_type_ref_opt(static_.ty());
384 let visibility = self.lower_visibility(static_);
385 let mutable = static_.mut_token().is_some();
386 let ast_id = self.source_ast_id_map.ast_id(static_);
387 let res = Static { name, visibility, mutable, type_ref, ast_id };
388 Some(id(self.data().statics.alloc(res)))
391 fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
392 let name = konst.name().map(|it| it.as_name());
393 let type_ref = self.lower_type_ref_opt(konst.ty());
394 let visibility = self.lower_visibility(konst);
395 let ast_id = self.source_ast_id_map.ast_id(konst);
396 let res = Const { name, visibility, type_ref, ast_id };
397 id(self.data().consts.alloc(res))
400 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
401 let name = module.name()?.as_name();
402 let visibility = self.lower_visibility(module);
403 let kind = if module.semicolon_token().is_some() {
409 .map(|list| list.items().flat_map(|item| self.lower_mod_item(&item)).collect())
411 cov_mark::hit!(name_res_works_for_broken_modules);
412 Box::new([]) as Box<[_]>
416 let ast_id = self.source_ast_id_map.ast_id(module);
417 let res = Mod { name, visibility, kind, ast_id };
418 Some(id(self.data().mods.alloc(res)))
421 fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
422 let name = trait_def.name()?.as_name();
423 let visibility = self.lower_visibility(trait_def);
424 let generic_params = self.lower_generic_params(GenericsOwner::Trait(trait_def), trait_def);
425 let is_auto = trait_def.auto_token().is_some();
426 let is_unsafe = trait_def.unsafe_token().is_some();
427 let items = trait_def.assoc_item_list().map(|list| {
429 self.with_inherited_visibility(visibility, |this| {
432 let attrs = RawAttrs::new(db, &item, this.hygiene());
433 this.lower_assoc_item(&item).map(|item| {
434 this.add_attrs(ModItem::from(item).into(), attrs);
441 let ast_id = self.source_ast_id_map.ast_id(trait_def);
448 items: items.unwrap_or_default(),
451 Some(id(self.data().traits.alloc(res)))
454 fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
455 let generic_params = self.lower_generic_params(GenericsOwner::Impl, impl_def);
456 // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
457 // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
459 let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
460 let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
461 let is_negative = impl_def.excl_token().is_some();
463 // We cannot use `assoc_items()` here as that does not include macro calls.
467 .flat_map(|it| it.assoc_items())
469 let assoc = self.lower_assoc_item(&item)?;
470 let attrs = RawAttrs::new(self.db, &item, self.hygiene());
471 self.add_attrs(ModItem::from(assoc).into(), attrs);
475 let ast_id = self.source_ast_id_map.ast_id(impl_def);
476 let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
477 Some(id(self.data().impls.alloc(res)))
480 fn lower_use(&mut self, use_item: &ast::Use) -> Option<FileItemTreeId<Import>> {
481 let visibility = self.lower_visibility(use_item);
482 let ast_id = self.source_ast_id_map.ast_id(use_item);
483 let (use_tree, _) = lower_use_tree(self.db, self.hygiene(), use_item.use_tree()?)?;
485 let res = Import { visibility, ast_id, use_tree };
486 Some(id(self.data().imports.alloc(res)))
489 fn lower_extern_crate(
491 extern_crate: &ast::ExternCrate,
492 ) -> Option<FileItemTreeId<ExternCrate>> {
493 let name = extern_crate.name_ref()?.as_name();
494 let alias = extern_crate.rename().map(|a| {
495 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
497 let visibility = self.lower_visibility(extern_crate);
498 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
500 let res = ExternCrate { name, alias, visibility, ast_id };
501 Some(id(self.data().extern_crates.alloc(res)))
504 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
505 let path = Interned::new(ModPath::from_src(self.db.upcast(), m.path()?, self.hygiene())?);
506 let ast_id = self.source_ast_id_map.ast_id(m);
507 let expand_to = hir_expand::ExpandTo::from_call_site(m);
508 let res = MacroCall { path, ast_id, expand_to };
509 Some(id(self.data().macro_calls.alloc(res)))
512 fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
513 let name = m.name().map(|it| it.as_name())?;
514 let ast_id = self.source_ast_id_map.ast_id(m);
516 let res = MacroRules { name, ast_id };
517 Some(id(self.data().macro_rules.alloc(res)))
520 fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
521 let name = m.name().map(|it| it.as_name())?;
523 let ast_id = self.source_ast_id_map.ast_id(m);
524 let visibility = self.lower_visibility(m);
526 let res = MacroDef { name, ast_id, visibility };
527 Some(id(self.data().macro_defs.alloc(res)))
530 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> FileItemTreeId<ExternBlock> {
531 let ast_id = self.source_ast_id_map.ast_id(block);
532 let abi = block.abi().map(lower_abi);
533 let children: Box<[_]> = block.extern_item_list().map_or(Box::new([]), |list| {
536 // Note: All items in an `extern` block need to be lowered as if they're outside of one
537 // (in other words, the knowledge that they're in an extern block must not be used).
538 // This is because an extern block can contain macros whose ItemTree's top-level items
539 // should be considered to be in an extern block too.
540 let attrs = RawAttrs::new(self.db, &item, self.hygiene());
541 let id: ModItem = match item {
542 ast::ExternItem::Fn(ast) => {
543 let func_id = self.lower_function(&ast)?;
544 let func = &mut self.data().functions[func_id.index];
545 if is_intrinsic_fn_unsafe(&func.name) {
546 // FIXME: this breaks in macros
547 func.flags.bits |= FnFlags::IS_UNSAFE;
551 ast::ExternItem::Static(ast) => self.lower_static(&ast)?.into(),
552 ast::ExternItem::TypeAlias(ty) => self.lower_type_alias(&ty)?.into(),
553 ast::ExternItem::MacroCall(call) => {
554 // FIXME: we need some way of tracking that the macro call is in an
556 self.lower_macro_call(&call)?.into()
559 self.add_attrs(id.into(), attrs);
565 let res = ExternBlock { abi, ast_id, children };
566 id(self.data().extern_blocks.alloc(res))
569 fn lower_generic_params(
571 owner: GenericsOwner<'_>,
572 node: &dyn ast::HasGenericParams,
573 ) -> Interned<GenericParams> {
574 let mut generics = GenericParams::default();
576 GenericsOwner::Function(_)
577 | GenericsOwner::Struct
578 | GenericsOwner::Enum
579 | GenericsOwner::Union
580 | GenericsOwner::TypeAlias => {
581 generics.fill(&self.body_ctx, node);
583 GenericsOwner::Trait(trait_def) => {
584 // traits get the Self type as an implicit first type parameter
587 name: Some(name![Self]),
589 provenance: TypeParamProvenance::TraitSelf,
593 // add super traits as bounds on Self
594 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
595 let self_param = TypeRef::Path(name![Self].into());
596 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
597 generics.fill(&self.body_ctx, node);
599 GenericsOwner::Impl => {
600 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
601 // type-parameter, but rather is a type-alias for impl's target
602 // type, so this is handled by the resolver.
603 generics.fill(&self.body_ctx, node);
607 generics.shrink_to_fit();
608 Interned::new(generics)
611 fn lower_type_bounds(&mut self, node: &dyn ast::HasTypeBounds) -> Vec<Interned<TypeBound>> {
612 match node.type_bound_list() {
613 Some(bound_list) => bound_list
615 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
621 fn lower_visibility(&mut self, item: &dyn ast::HasVisibility) -> RawVisibilityId {
622 let vis = match self.forced_visibility {
623 Some(vis) => return vis,
625 RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), self.hygiene())
629 self.data().vis.alloc(vis)
632 fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
633 let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
634 Some(Interned::new(trait_ref))
637 fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
638 let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
642 fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
643 match type_ref.map(|ty| self.lower_type_ref(&ty)) {
645 None => Interned::new(TypeRef::Error),
649 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
650 fn with_inherited_visibility<R>(
652 vis: RawVisibilityId,
653 f: impl FnOnce(&mut Self) -> R,
655 let old = mem::replace(&mut self.forced_visibility, Some(vis));
657 self.forced_visibility = old;
661 fn next_field_idx(&self) -> Idx<Field> {
662 Idx::from_raw(RawIdx::from(
663 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
666 fn next_variant_idx(&self) -> Idx<Variant> {
667 Idx::from_raw(RawIdx::from(
668 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
671 fn next_param_idx(&self) -> Idx<Param> {
672 Idx::from_raw(RawIdx::from(
673 self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
678 fn desugar_future_path(orig: TypeRef) -> Path {
679 let path = path![core::future::Future];
680 let mut generic_args: Vec<_> =
681 std::iter::repeat(None).take(path.segments().len() - 1).collect();
682 let mut last = GenericArgs::empty();
684 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
685 last.bindings.push(binding);
686 generic_args.push(Some(Interned::new(last)));
688 Path::from_known_path(path, generic_args)
691 enum GenericsOwner<'a> {
692 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
694 Function(&'a Function),
698 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
699 Trait(&'a ast::Trait),
704 /// Returns `true` if the given intrinsic is unsafe to call, or false otherwise.
705 fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
706 // Should be kept in sync with https://github.com/rust-lang/rust/blob/532d2b14c05f9bc20b2d27cbb5f4550d28343a36/compiler/rustc_typeck/src/check/intrinsic.rs#L72-L106
709 known::add_with_overflow,
713 known::caller_location,
717 known::discriminant_value,
725 known::mul_with_overflow,
727 known::ptr_guaranteed_eq,
728 known::ptr_guaranteed_ne,
732 known::saturating_add,
733 known::saturating_sub,
735 known::sub_with_overflow,
739 known::variant_count,
747 fn lower_abi(abi: ast::Abi) -> Interned<str> {
748 // FIXME: Abi::abi() -> Option<SyntaxToken>?
749 match abi.syntax().last_token() {
750 Some(tok) if tok.kind() == SyntaxKind::STRING => {
751 // FIXME: Better way to unescape?
752 Interned::new_str(tok.text().trim_matches('"'))
755 // `extern` default to be `extern "C"`.
756 Interned::new_str("C")
761 struct UseTreeLowering<'a> {
762 db: &'a dyn DefDatabase,
763 hygiene: &'a Hygiene,
764 mapping: Arena<ast::UseTree>,
767 impl UseTreeLowering<'_> {
768 fn lower_use_tree(&mut self, tree: ast::UseTree) -> Option<UseTree> {
769 if let Some(use_tree_list) = tree.use_tree_list() {
770 let prefix = match tree.path() {
771 // E.g. use something::{{{inner}}};
773 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
774 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
776 match ModPath::from_src(self.db.upcast(), path, self.hygiene) {
777 Some(it) => Some(it),
778 None => return None, // FIXME: report errors somewhere
784 use_tree_list.use_trees().filter_map(|tree| self.lower_use_tree(tree)).collect();
788 UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
793 let is_glob = tree.star_token().is_some();
794 let path = match tree.path() {
795 Some(path) => Some(ModPath::from_src(self.db.upcast(), path, self.hygiene)?),
798 let alias = tree.rename().map(|a| {
799 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
801 if alias.is_some() && is_glob {
805 match (path, alias, is_glob) {
806 (path, None, true) => {
808 cov_mark::hit!(glob_enum_group);
810 Some(self.use_tree(UseTreeKind::Glob { path: path.map(Interned::new) }, tree))
812 // Globs can't be renamed
813 (_, Some(_), true) | (None, None, false) => None,
814 // `bla::{ as Name}` is invalid
815 (None, Some(_), false) => None,
816 (Some(path), alias, false) => Some(
817 self.use_tree(UseTreeKind::Single { path: Interned::new(path), alias }, tree),
823 fn use_tree(&mut self, kind: UseTreeKind, ast: ast::UseTree) -> UseTree {
824 let index = self.mapping.alloc(ast);
825 UseTree { index, kind }
829 pub(super) fn lower_use_tree(
830 db: &dyn DefDatabase,
833 ) -> Option<(UseTree, Arena<ast::UseTree>)> {
834 let mut lowering = UseTreeLowering { db, hygiene, mapping: Arena::new() };
835 let tree = lowering.lower_use_tree(tree)?;
836 Some((tree, lowering.mapping))