1 //! AST -> `ItemTree` lowering code.
3 use std::{collections::hash_map::Entry, sync::Arc};
5 use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, 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>,
27 pub(super) fn new(db: &'a dyn DefDatabase, file: HirFileId) -> Self {
30 tree: ItemTree::default(),
31 source_ast_id_map: db.ast_id_map(file),
32 body_ctx: crate::body::LowerCtx::new(db, file),
36 pub(super) fn hygiene(&self) -> &Hygiene {
37 self.body_ctx.hygiene()
40 pub(super) fn lower_module_items(mut self, item_owner: &dyn HasModuleItem) -> ItemTree {
42 item_owner.items().flat_map(|item| self.lower_mod_item(&item)).collect();
46 pub(super) fn lower_macro_stmts(mut self, stmts: ast::MacroStmts) -> ItemTree {
47 self.tree.top_level = stmts
51 ast::Stmt::Item(item) => Some(item),
52 // Macro calls can be both items and expressions. The syntax library always treats
53 // them as expressions here, so we undo that.
54 ast::Stmt::ExprStmt(es) => match es.expr()? {
55 ast::Expr::MacroExpr(expr) => {
56 cov_mark::hit!(macro_call_in_macro_stmts_is_added_to_item_tree);
57 Some(expr.macro_call()?.into())
64 .flat_map(|item| self.lower_mod_item(&item))
67 if let Some(ast::Expr::MacroExpr(tail_macro)) = stmts.expr() {
68 if let Some(call) = tail_macro.macro_call() {
69 cov_mark::hit!(macro_stmt_with_trailing_macro_expr);
70 if let Some(mod_item) = self.lower_mod_item(&call.into()) {
71 self.tree.top_level.push(mod_item);
79 pub(super) fn lower_block(mut self, block: &ast::BlockExpr) -> ItemTree {
80 self.tree.top_level = block
82 .filter_map(|stmt| match stmt {
83 ast::Stmt::Item(item) => self.lower_mod_item(&item),
84 // Macro calls can be both items and expressions. The syntax library always treats
85 // them as expressions here, so we undo that.
86 ast::Stmt::ExprStmt(es) => match es.expr()? {
87 ast::Expr::MacroExpr(expr) => self.lower_mod_item(&expr.macro_call()?.into()),
97 fn data(&mut self) -> &mut ItemTreeData {
101 fn lower_mod_item(&mut self, item: &ast::Item) -> Option<ModItem> {
102 let attrs = RawAttrs::new(self.db, item, self.hygiene());
103 let item: ModItem = match item {
104 ast::Item::Struct(ast) => self.lower_struct(ast)?.into(),
105 ast::Item::Union(ast) => self.lower_union(ast)?.into(),
106 ast::Item::Enum(ast) => self.lower_enum(ast)?.into(),
107 ast::Item::Fn(ast) => self.lower_function(ast)?.into(),
108 ast::Item::TypeAlias(ast) => self.lower_type_alias(ast)?.into(),
109 ast::Item::Static(ast) => self.lower_static(ast)?.into(),
110 ast::Item::Const(ast) => self.lower_const(ast).into(),
111 ast::Item::Module(ast) => self.lower_module(ast)?.into(),
112 ast::Item::Trait(ast) => self.lower_trait(ast)?.into(),
113 ast::Item::Impl(ast) => self.lower_impl(ast)?.into(),
114 ast::Item::Use(ast) => self.lower_use(ast)?.into(),
115 ast::Item::ExternCrate(ast) => self.lower_extern_crate(ast)?.into(),
116 ast::Item::MacroCall(ast) => self.lower_macro_call(ast)?.into(),
117 ast::Item::MacroRules(ast) => self.lower_macro_rules(ast)?.into(),
118 ast::Item::MacroDef(ast) => self.lower_macro_def(ast)?.into(),
119 ast::Item::ExternBlock(ast) => self.lower_extern_block(ast).into(),
122 self.add_attrs(item.into(), attrs);
127 fn add_attrs(&mut self, item: AttrOwner, attrs: RawAttrs) {
128 match self.tree.attrs.entry(item) {
129 Entry::Occupied(mut entry) => {
130 *entry.get_mut() = entry.get().merge(attrs);
132 Entry::Vacant(entry) => {
138 fn lower_assoc_item(&mut self, item: &ast::AssocItem) -> Option<AssocItem> {
140 ast::AssocItem::Fn(ast) => self.lower_function(ast).map(Into::into),
141 ast::AssocItem::TypeAlias(ast) => self.lower_type_alias(ast).map(Into::into),
142 ast::AssocItem::Const(ast) => Some(self.lower_const(ast).into()),
143 ast::AssocItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
147 fn lower_struct(&mut self, strukt: &ast::Struct) -> Option<FileItemTreeId<Struct>> {
148 let visibility = self.lower_visibility(strukt);
149 let name = strukt.name()?.as_name();
150 let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
151 let fields = self.lower_fields(&strukt.kind());
152 let ast_id = self.source_ast_id_map.ast_id(strukt);
153 let res = Struct { name, visibility, generic_params, fields, ast_id };
154 Some(id(self.data().structs.alloc(res)))
157 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
159 ast::StructKind::Record(it) => {
160 let range = self.lower_record_fields(it);
161 Fields::Record(range)
163 ast::StructKind::Tuple(it) => {
164 let range = self.lower_tuple_fields(it);
167 ast::StructKind::Unit => Fields::Unit,
171 fn lower_record_fields(&mut self, fields: &ast::RecordFieldList) -> IdxRange<Field> {
172 let start = self.next_field_idx();
173 for field in fields.fields() {
174 if let Some(data) = self.lower_record_field(&field) {
175 let idx = self.data().fields.alloc(data);
176 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
179 let end = self.next_field_idx();
180 IdxRange::new(start..end)
183 fn lower_record_field(&mut self, field: &ast::RecordField) -> Option<Field> {
184 let name = field.name()?.as_name();
185 let visibility = self.lower_visibility(field);
186 let type_ref = self.lower_type_ref_opt(field.ty());
187 let res = Field { name, type_ref, visibility };
191 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldList) -> IdxRange<Field> {
192 let start = self.next_field_idx();
193 for (i, field) in fields.fields().enumerate() {
194 let data = self.lower_tuple_field(i, &field);
195 let idx = self.data().fields.alloc(data);
196 self.add_attrs(idx.into(), RawAttrs::new(self.db, &field, self.hygiene()));
198 let end = self.next_field_idx();
199 IdxRange::new(start..end)
202 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleField) -> Field {
203 let name = Name::new_tuple_field(idx);
204 let visibility = self.lower_visibility(field);
205 let type_ref = self.lower_type_ref_opt(field.ty());
206 Field { name, type_ref, visibility }
209 fn lower_union(&mut self, union: &ast::Union) -> Option<FileItemTreeId<Union>> {
210 let visibility = self.lower_visibility(union);
211 let name = union.name()?.as_name();
212 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
213 let fields = match union.record_field_list() {
214 Some(record_field_list) => self.lower_fields(&StructKind::Record(record_field_list)),
215 None => Fields::Record(IdxRange::new(self.next_field_idx()..self.next_field_idx())),
217 let ast_id = self.source_ast_id_map.ast_id(union);
218 let res = Union { name, visibility, generic_params, fields, ast_id };
219 Some(id(self.data().unions.alloc(res)))
222 fn lower_enum(&mut self, enum_: &ast::Enum) -> Option<FileItemTreeId<Enum>> {
223 let visibility = self.lower_visibility(enum_);
224 let name = enum_.name()?.as_name();
225 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
226 let variants = match &enum_.variant_list() {
227 Some(variant_list) => self.lower_variants(variant_list),
228 None => IdxRange::new(self.next_variant_idx()..self.next_variant_idx()),
230 let ast_id = self.source_ast_id_map.ast_id(enum_);
231 let res = Enum { name, visibility, generic_params, variants, ast_id };
232 Some(id(self.data().enums.alloc(res)))
235 fn lower_variants(&mut self, variants: &ast::VariantList) -> IdxRange<Variant> {
236 let start = self.next_variant_idx();
237 for variant in variants.variants() {
238 if let Some(data) = self.lower_variant(&variant) {
239 let idx = self.data().variants.alloc(data);
240 self.add_attrs(idx.into(), RawAttrs::new(self.db, &variant, self.hygiene()));
243 let end = self.next_variant_idx();
244 IdxRange::new(start..end)
247 fn lower_variant(&mut self, variant: &ast::Variant) -> Option<Variant> {
248 let name = variant.name()?.as_name();
249 let fields = self.lower_fields(&variant.kind());
250 let res = Variant { name, fields };
254 fn lower_function(&mut self, func: &ast::Fn) -> Option<FileItemTreeId<Function>> {
255 let visibility = self.lower_visibility(func);
256 let name = func.name()?.as_name();
258 let mut has_self_param = false;
259 let start_param = self.next_param_idx();
260 if let Some(param_list) = func.param_list() {
261 if let Some(self_param) = param_list.self_param() {
262 let self_type = match self_param.ty() {
263 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
265 let self_type = TypeRef::Path(name![Self].into());
266 match self_param.kind() {
267 ast::SelfParamKind::Owned => self_type,
268 ast::SelfParamKind::Ref => TypeRef::Reference(
270 self_param.lifetime().as_ref().map(LifetimeRef::new),
273 ast::SelfParamKind::MutRef => TypeRef::Reference(
275 self_param.lifetime().as_ref().map(LifetimeRef::new),
281 let ty = Interned::new(self_type);
282 let idx = self.data().params.alloc(Param::Normal(None, ty));
283 self.add_attrs(idx.into(), RawAttrs::new(self.db, &self_param, self.hygiene()));
284 has_self_param = true;
286 for param in param_list.params() {
287 let idx = match param.dotdotdot_token() {
288 Some(_) => self.data().params.alloc(Param::Varargs),
290 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ty());
291 let ty = Interned::new(type_ref);
292 let mut pat = param.pat();
293 // FIXME: This really shouldn't be here, in fact FunctionData/ItemTree's function shouldn't know about
294 // pattern names at all
295 let name = 'name: loop {
297 Some(ast::Pat::RefPat(ref_pat)) => pat = ref_pat.pat(),
298 Some(ast::Pat::IdentPat(ident)) => {
299 break 'name ident.name().map(|it| it.as_name())
301 _ => break 'name None,
304 self.data().params.alloc(Param::Normal(name, ty))
307 self.add_attrs(idx.into(), RawAttrs::new(self.db, ¶m, self.hygiene()));
310 let end_param = self.next_param_idx();
311 let params = IdxRange::new(start_param..end_param);
313 let ret_type = match func.ret_type() {
314 Some(rt) => match rt.ty() {
315 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
316 None if rt.thin_arrow_token().is_some() => TypeRef::Error,
317 None => TypeRef::unit(),
319 None => TypeRef::unit(),
322 let (ret_type, async_ret_type) = if func.async_token().is_some() {
323 let async_ret_type = ret_type.clone();
324 let future_impl = desugar_future_path(ret_type);
325 let ty_bound = Interned::new(TypeBound::Path(future_impl, TraitBoundModifier::None));
326 (TypeRef::ImplTrait(vec![ty_bound]), Some(async_ret_type))
331 let abi = func.abi().map(lower_abi);
333 let ast_id = self.source_ast_id_map.ast_id(func);
335 let mut flags = FnFlags::default();
336 if func.body().is_some() {
337 flags |= FnFlags::HAS_BODY;
340 flags |= FnFlags::HAS_SELF_PARAM;
342 if func.default_token().is_some() {
343 flags |= FnFlags::HAS_DEFAULT_KW;
345 if func.const_token().is_some() {
346 flags |= FnFlags::HAS_CONST_KW;
348 if func.async_token().is_some() {
349 flags |= FnFlags::HAS_ASYNC_KW;
351 if func.unsafe_token().is_some() {
352 flags |= FnFlags::HAS_UNSAFE_KW;
355 let mut res = Function {
358 explicit_generic_params: Interned::new(GenericParams::default()),
361 ret_type: Interned::new(ret_type),
362 async_ret_type: async_ret_type.map(Interned::new),
366 res.explicit_generic_params =
367 self.lower_generic_params(GenericsOwner::Function(&res), func);
369 Some(id(self.data().functions.alloc(res)))
374 type_alias: &ast::TypeAlias,
375 ) -> Option<FileItemTreeId<TypeAlias>> {
376 let name = type_alias.name()?.as_name();
377 let type_ref = type_alias.ty().map(|it| self.lower_type_ref(&it));
378 let visibility = self.lower_visibility(type_alias);
379 let bounds = self.lower_type_bounds(type_alias);
380 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
381 let ast_id = self.source_ast_id_map.ast_id(type_alias);
382 let res = TypeAlias {
385 bounds: bounds.into_boxed_slice(),
390 Some(id(self.data().type_aliases.alloc(res)))
393 fn lower_static(&mut self, static_: &ast::Static) -> Option<FileItemTreeId<Static>> {
394 let name = static_.name()?.as_name();
395 let type_ref = self.lower_type_ref_opt(static_.ty());
396 let visibility = self.lower_visibility(static_);
397 let mutable = static_.mut_token().is_some();
398 let ast_id = self.source_ast_id_map.ast_id(static_);
399 let res = Static { name, visibility, mutable, type_ref, ast_id };
400 Some(id(self.data().statics.alloc(res)))
403 fn lower_const(&mut self, konst: &ast::Const) -> FileItemTreeId<Const> {
404 let name = konst.name().map(|it| it.as_name());
405 let type_ref = self.lower_type_ref_opt(konst.ty());
406 let visibility = self.lower_visibility(konst);
407 let ast_id = self.source_ast_id_map.ast_id(konst);
408 let res = Const { name, visibility, type_ref, ast_id };
409 id(self.data().consts.alloc(res))
412 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
413 let name = module.name()?.as_name();
414 let visibility = self.lower_visibility(module);
415 let kind = if module.semicolon_token().is_some() {
421 .map(|list| list.items().flat_map(|item| self.lower_mod_item(&item)).collect())
423 cov_mark::hit!(name_res_works_for_broken_modules);
424 Box::new([]) as Box<[_]>
428 let ast_id = self.source_ast_id_map.ast_id(module);
429 let res = Mod { name, visibility, kind, ast_id };
430 Some(id(self.data().mods.alloc(res)))
433 fn lower_trait(&mut self, trait_def: &ast::Trait) -> Option<FileItemTreeId<Trait>> {
434 let name = trait_def.name()?.as_name();
435 let visibility = self.lower_visibility(trait_def);
436 let generic_params = self.lower_generic_params(GenericsOwner::Trait(trait_def), trait_def);
437 let is_auto = trait_def.auto_token().is_some();
438 let is_unsafe = trait_def.unsafe_token().is_some();
439 let items = trait_def.assoc_item_list().map(|list| {
442 let attrs = RawAttrs::new(self.db, &item, self.hygiene());
443 self.lower_assoc_item(&item).map(|item| {
444 self.add_attrs(ModItem::from(item).into(), attrs);
450 let ast_id = self.source_ast_id_map.ast_id(trait_def);
457 items: items.unwrap_or_default(),
460 Some(id(self.data().traits.alloc(res)))
463 fn lower_impl(&mut self, impl_def: &ast::Impl) -> Option<FileItemTreeId<Impl>> {
464 let generic_params = self.lower_generic_params(GenericsOwner::Impl, impl_def);
465 // FIXME: If trait lowering fails, due to a non PathType for example, we treat this impl
466 // as if it was an non-trait impl. Ideally we want to create a unique missing ref that only
468 let target_trait = impl_def.trait_().and_then(|tr| self.lower_trait_ref(&tr));
469 let self_ty = self.lower_type_ref(&impl_def.self_ty()?);
470 let is_negative = impl_def.excl_token().is_some();
472 // We cannot use `assoc_items()` here as that does not include macro calls.
476 .flat_map(|it| it.assoc_items())
478 let assoc = self.lower_assoc_item(&item)?;
479 let attrs = RawAttrs::new(self.db, &item, self.hygiene());
480 self.add_attrs(ModItem::from(assoc).into(), attrs);
484 let ast_id = self.source_ast_id_map.ast_id(impl_def);
485 let res = Impl { generic_params, target_trait, self_ty, is_negative, items, ast_id };
486 Some(id(self.data().impls.alloc(res)))
489 fn lower_use(&mut self, use_item: &ast::Use) -> Option<FileItemTreeId<Import>> {
490 let visibility = self.lower_visibility(use_item);
491 let ast_id = self.source_ast_id_map.ast_id(use_item);
492 let (use_tree, _) = lower_use_tree(self.db, self.hygiene(), use_item.use_tree()?)?;
494 let res = Import { visibility, ast_id, use_tree };
495 Some(id(self.data().imports.alloc(res)))
498 fn lower_extern_crate(
500 extern_crate: &ast::ExternCrate,
501 ) -> Option<FileItemTreeId<ExternCrate>> {
502 let name = extern_crate.name_ref()?.as_name();
503 let alias = extern_crate.rename().map(|a| {
504 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
506 let visibility = self.lower_visibility(extern_crate);
507 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
509 let res = ExternCrate { name, alias, visibility, ast_id };
510 Some(id(self.data().extern_crates.alloc(res)))
513 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
514 let path = Interned::new(ModPath::from_src(self.db.upcast(), m.path()?, self.hygiene())?);
515 let ast_id = self.source_ast_id_map.ast_id(m);
516 let expand_to = hir_expand::ExpandTo::from_call_site(m);
517 let res = MacroCall { path, ast_id, expand_to };
518 Some(id(self.data().macro_calls.alloc(res)))
521 fn lower_macro_rules(&mut self, m: &ast::MacroRules) -> Option<FileItemTreeId<MacroRules>> {
522 let name = m.name().map(|it| it.as_name())?;
523 let ast_id = self.source_ast_id_map.ast_id(m);
525 let res = MacroRules { name, ast_id };
526 Some(id(self.data().macro_rules.alloc(res)))
529 fn lower_macro_def(&mut self, m: &ast::MacroDef) -> Option<FileItemTreeId<MacroDef>> {
530 let name = m.name().map(|it| it.as_name())?;
532 let ast_id = self.source_ast_id_map.ast_id(m);
533 let visibility = self.lower_visibility(m);
535 let res = MacroDef { name, ast_id, visibility };
536 Some(id(self.data().macro_defs.alloc(res)))
539 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> FileItemTreeId<ExternBlock> {
540 let ast_id = self.source_ast_id_map.ast_id(block);
541 let abi = block.abi().map(lower_abi);
542 let children: Box<[_]> = block.extern_item_list().map_or(Box::new([]), |list| {
545 // Note: All items in an `extern` block need to be lowered as if they're outside of one
546 // (in other words, the knowledge that they're in an extern block must not be used).
547 // This is because an extern block can contain macros whose ItemTree's top-level items
548 // should be considered to be in an extern block too.
549 let attrs = RawAttrs::new(self.db, &item, self.hygiene());
550 let id: ModItem = match item {
551 ast::ExternItem::Fn(ast) => self.lower_function(&ast)?.into(),
552 ast::ExternItem::Static(ast) => self.lower_static(&ast)?.into(),
553 ast::ExternItem::TypeAlias(ty) => self.lower_type_alias(&ty)?.into(),
554 ast::ExternItem::MacroCall(call) => self.lower_macro_call(&call)?.into(),
556 self.add_attrs(id.into(), attrs);
562 let res = ExternBlock { abi, ast_id, children };
563 id(self.data().extern_blocks.alloc(res))
566 fn lower_generic_params(
568 owner: GenericsOwner<'_>,
569 node: &dyn ast::HasGenericParams,
570 ) -> Interned<GenericParams> {
571 let mut generics = GenericParams::default();
573 GenericsOwner::Function(_)
574 | GenericsOwner::Struct
575 | GenericsOwner::Enum
576 | GenericsOwner::Union
577 | GenericsOwner::TypeAlias => {
578 generics.fill(&self.body_ctx, node);
580 GenericsOwner::Trait(trait_def) => {
581 // traits get the Self type as an implicit first type parameter
582 generics.type_or_consts.alloc(
584 name: Some(name![Self]),
586 provenance: TypeParamProvenance::TraitSelf,
590 // add super traits as bounds on Self
591 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
592 let self_param = TypeRef::Path(name![Self].into());
593 generics.fill_bounds(&self.body_ctx, trait_def, Either::Left(self_param));
594 generics.fill(&self.body_ctx, node);
596 GenericsOwner::Impl => {
597 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
598 // type-parameter, but rather is a type-alias for impl's target
599 // type, so this is handled by the resolver.
600 generics.fill(&self.body_ctx, node);
604 generics.shrink_to_fit();
605 Interned::new(generics)
608 fn lower_type_bounds(&mut self, node: &dyn ast::HasTypeBounds) -> Vec<Interned<TypeBound>> {
609 match node.type_bound_list() {
610 Some(bound_list) => bound_list
612 .map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
618 fn lower_visibility(&mut self, item: &dyn ast::HasVisibility) -> RawVisibilityId {
619 let vis = RawVisibility::from_ast_with_hygiene(self.db, item.visibility(), self.hygiene());
620 self.data().vis.alloc(vis)
623 fn lower_trait_ref(&mut self, trait_ref: &ast::Type) -> Option<Interned<TraitRef>> {
624 let trait_ref = TraitRef::from_ast(&self.body_ctx, trait_ref.clone())?;
625 Some(Interned::new(trait_ref))
628 fn lower_type_ref(&mut self, type_ref: &ast::Type) -> Interned<TypeRef> {
629 let tyref = TypeRef::from_ast(&self.body_ctx, type_ref.clone());
633 fn lower_type_ref_opt(&mut self, type_ref: Option<ast::Type>) -> Interned<TypeRef> {
634 match type_ref.map(|ty| self.lower_type_ref(&ty)) {
636 None => Interned::new(TypeRef::Error),
640 fn next_field_idx(&self) -> Idx<Field> {
641 Idx::from_raw(RawIdx::from(
642 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
645 fn next_variant_idx(&self) -> Idx<Variant> {
646 Idx::from_raw(RawIdx::from(
647 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
650 fn next_param_idx(&self) -> Idx<Param> {
651 Idx::from_raw(RawIdx::from(
652 self.tree.data.as_ref().map_or(0, |data| data.params.len() as u32),
657 fn desugar_future_path(orig: TypeRef) -> Path {
658 let path = path![core::future::Future];
659 let mut generic_args: Vec<_> =
660 std::iter::repeat(None).take(path.segments().len() - 1).collect();
661 let mut last = GenericArgs::empty();
663 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
664 last.bindings.push(binding);
665 generic_args.push(Some(Interned::new(last)));
667 Path::from_known_path(path, generic_args)
670 enum GenericsOwner<'a> {
671 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
673 Function(&'a Function),
677 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
678 Trait(&'a ast::Trait),
683 fn lower_abi(abi: ast::Abi) -> Interned<str> {
684 // FIXME: Abi::abi() -> Option<SyntaxToken>?
685 match abi.syntax().last_token() {
686 Some(tok) if tok.kind() == SyntaxKind::STRING => {
687 // FIXME: Better way to unescape?
688 Interned::new_str(tok.text().trim_matches('"'))
691 // `extern` default to be `extern "C"`.
692 Interned::new_str("C")
697 struct UseTreeLowering<'a> {
698 db: &'a dyn DefDatabase,
699 hygiene: &'a Hygiene,
700 mapping: Arena<ast::UseTree>,
703 impl UseTreeLowering<'_> {
704 fn lower_use_tree(&mut self, tree: ast::UseTree) -> Option<UseTree> {
705 if let Some(use_tree_list) = tree.use_tree_list() {
706 let prefix = match tree.path() {
707 // E.g. use something::{{{inner}}};
709 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
710 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
712 match ModPath::from_src(self.db.upcast(), path, self.hygiene) {
713 Some(it) => Some(it),
714 None => return None, // FIXME: report errors somewhere
720 use_tree_list.use_trees().filter_map(|tree| self.lower_use_tree(tree)).collect();
724 UseTreeKind::Prefixed { prefix: prefix.map(Interned::new), list },
729 let is_glob = tree.star_token().is_some();
730 let path = match tree.path() {
731 Some(path) => Some(ModPath::from_src(self.db.upcast(), path, self.hygiene)?),
734 let alias = tree.rename().map(|a| {
735 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
737 if alias.is_some() && is_glob {
741 match (path, alias, is_glob) {
742 (path, None, true) => {
744 cov_mark::hit!(glob_enum_group);
746 Some(self.use_tree(UseTreeKind::Glob { path: path.map(Interned::new) }, tree))
748 // Globs can't be renamed
749 (_, Some(_), true) | (None, None, false) => None,
750 // `bla::{ as Name}` is invalid
751 (None, Some(_), false) => None,
752 (Some(path), alias, false) => Some(
753 self.use_tree(UseTreeKind::Single { path: Interned::new(path), alias }, tree),
759 fn use_tree(&mut self, kind: UseTreeKind, ast: ast::UseTree) -> UseTree {
760 let index = self.mapping.alloc(ast);
761 UseTree { index, kind }
765 pub(super) fn lower_use_tree(
766 db: &dyn DefDatabase,
769 ) -> Option<(UseTree, Arena<ast::UseTree>)> {
770 let mut lowering = UseTreeLowering { db, hygiene, mapping: Arena::new() };
771 let tree = lowering.lower_use_tree(tree)?;
772 Some((tree, lowering.mapping))