aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_def/src/item_tree/lower.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_def/src/item_tree/lower.rs')
-rw-r--r--crates/ra_hir_def/src/item_tree/lower.rs695
1 files changed, 695 insertions, 0 deletions
diff --git a/crates/ra_hir_def/src/item_tree/lower.rs b/crates/ra_hir_def/src/item_tree/lower.rs
new file mode 100644
index 000000000..f10ad25f7
--- /dev/null
+++ b/crates/ra_hir_def/src/item_tree/lower.rs
@@ -0,0 +1,695 @@
1//! AST -> `ItemTree` lowering code.
2
3use super::*;
4use crate::{
5 attr::Attrs,
6 generics::{GenericParams, TypeParamData, TypeParamProvenance},
7};
8use hir_expand::{ast_id_map::AstIdMap, hygiene::Hygiene, HirFileId};
9use ra_arena::map::ArenaMap;
10use ra_syntax::{
11 ast::{self, ModuleItemOwner},
12 SyntaxNode,
13};
14use smallvec::SmallVec;
15use std::{collections::hash_map::Entry, mem, sync::Arc};
16
17fn id<N: ItemTreeNode>(index: Idx<N>) -> FileItemTreeId<N> {
18 FileItemTreeId { index, _p: PhantomData }
19}
20
21struct ModItems(SmallVec<[ModItem; 1]>);
22
23impl<T> From<T> for ModItems
24where
25 T: Into<ModItem>,
26{
27 fn from(t: T) -> Self {
28 ModItems(SmallVec::from_buf([t.into(); 1]))
29 }
30}
31
32pub(super) struct Ctx {
33 tree: ItemTree,
34 hygiene: Hygiene,
35 file: HirFileId,
36 source_ast_id_map: Arc<AstIdMap>,
37 body_ctx: crate::body::LowerCtx,
38 inner_items: Vec<ModItem>,
39 forced_visibility: Option<RawVisibilityId>,
40}
41
42impl Ctx {
43 pub(super) fn new(db: &dyn DefDatabase, hygiene: Hygiene, file: HirFileId) -> Self {
44 Self {
45 tree: ItemTree::empty(),
46 hygiene,
47 file,
48 source_ast_id_map: db.ast_id_map(file),
49 body_ctx: crate::body::LowerCtx::new(db, file),
50 inner_items: Vec::new(),
51 forced_visibility: None,
52 }
53 }
54
55 pub(super) fn lower_module_items(mut self, item_owner: &dyn ModuleItemOwner) -> ItemTree {
56 self.tree.top_level = item_owner
57 .items()
58 .flat_map(|item| self.lower_mod_item(&item, false))
59 .flat_map(|items| items.0)
60 .collect();
61 self.tree
62 }
63
64 pub(super) fn lower_inner_items(mut self, within: &SyntaxNode) -> ItemTree {
65 self.collect_inner_items(within);
66 self.tree
67 }
68
69 fn data(&mut self) -> &mut ItemTreeData {
70 self.tree.data_mut()
71 }
72
73 fn lower_mod_item(&mut self, item: &ast::ModuleItem, inner: bool) -> Option<ModItems> {
74 assert!(inner || self.inner_items.is_empty());
75
76 // Collect inner items for 1-to-1-lowered items.
77 match item {
78 ast::ModuleItem::StructDef(_)
79 | ast::ModuleItem::UnionDef(_)
80 | ast::ModuleItem::EnumDef(_)
81 | ast::ModuleItem::FnDef(_)
82 | ast::ModuleItem::TypeAliasDef(_)
83 | ast::ModuleItem::ConstDef(_)
84 | ast::ModuleItem::StaticDef(_)
85 | ast::ModuleItem::MacroCall(_) => {
86 // Skip this if we're already collecting inner items. We'll descend into all nodes
87 // already.
88 if !inner {
89 self.collect_inner_items(item.syntax());
90 }
91 }
92
93 // These are handled in their respective `lower_X` method (since we can't just blindly
94 // walk them).
95 ast::ModuleItem::TraitDef(_)
96 | ast::ModuleItem::ImplDef(_)
97 | ast::ModuleItem::ExternBlock(_) => {}
98
99 // These don't have inner items.
100 ast::ModuleItem::Module(_)
101 | ast::ModuleItem::ExternCrateItem(_)
102 | ast::ModuleItem::UseItem(_) => {}
103 };
104
105 let attrs = Attrs::new(item, &self.hygiene);
106 let items = match item {
107 ast::ModuleItem::StructDef(ast) => self.lower_struct(ast).map(Into::into),
108 ast::ModuleItem::UnionDef(ast) => self.lower_union(ast).map(Into::into),
109 ast::ModuleItem::EnumDef(ast) => self.lower_enum(ast).map(Into::into),
110 ast::ModuleItem::FnDef(ast) => self.lower_function(ast).map(Into::into),
111 ast::ModuleItem::TypeAliasDef(ast) => self.lower_type_alias(ast).map(Into::into),
112 ast::ModuleItem::StaticDef(ast) => self.lower_static(ast).map(Into::into),
113 ast::ModuleItem::ConstDef(ast) => Some(self.lower_const(ast).into()),
114 ast::ModuleItem::Module(ast) => self.lower_module(ast).map(Into::into),
115 ast::ModuleItem::TraitDef(ast) => self.lower_trait(ast).map(Into::into),
116 ast::ModuleItem::ImplDef(ast) => self.lower_impl(ast).map(Into::into),
117 ast::ModuleItem::UseItem(ast) => Some(ModItems(
118 self.lower_use(ast).into_iter().map(Into::into).collect::<SmallVec<_>>(),
119 )),
120 ast::ModuleItem::ExternCrateItem(ast) => self.lower_extern_crate(ast).map(Into::into),
121 ast::ModuleItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
122 ast::ModuleItem::ExternBlock(ast) => {
123 Some(ModItems(self.lower_extern_block(ast).into_iter().collect::<SmallVec<_>>()))
124 }
125 };
126
127 if !attrs.is_empty() {
128 for item in items.iter().flat_map(|items| &items.0) {
129 self.add_attrs(*item, attrs.clone());
130 }
131 }
132
133 items
134 }
135
136 fn add_attrs(&mut self, item: ModItem, attrs: Attrs) {
137 match self.tree.attrs.entry(AttrOwner::ModItem(item)) {
138 Entry::Occupied(mut entry) => {
139 *entry.get_mut() = entry.get().merge(attrs);
140 }
141 Entry::Vacant(entry) => {
142 entry.insert(attrs);
143 }
144 }
145 }
146
147 fn collect_inner_items(&mut self, container: &SyntaxNode) {
148 let forced_vis = self.forced_visibility.take();
149 let mut inner_items = mem::take(&mut self.tree.inner_items);
150 inner_items.extend(
151 container.descendants().skip(1).filter_map(ast::ModuleItem::cast).filter_map(|item| {
152 let ast_id = self.source_ast_id_map.ast_id(&item);
153 Some((ast_id, self.lower_mod_item(&item, true)?.0))
154 }),
155 );
156 self.tree.inner_items = inner_items;
157 self.forced_visibility = forced_vis;
158 }
159
160 fn lower_assoc_item(&mut self, item: &ast::ModuleItem) -> Option<AssocItem> {
161 match item {
162 ast::ModuleItem::FnDef(ast) => self.lower_function(ast).map(Into::into),
163 ast::ModuleItem::TypeAliasDef(ast) => self.lower_type_alias(ast).map(Into::into),
164 ast::ModuleItem::ConstDef(ast) => Some(self.lower_const(ast).into()),
165 ast::ModuleItem::MacroCall(ast) => self.lower_macro_call(ast).map(Into::into),
166 _ => None,
167 }
168 }
169
170 fn lower_struct(&mut self, strukt: &ast::StructDef) -> Option<FileItemTreeId<Struct>> {
171 let visibility = self.lower_visibility(strukt);
172 let name = strukt.name()?.as_name();
173 let generic_params = self.lower_generic_params(GenericsOwner::Struct, strukt);
174 let fields = self.lower_fields(&strukt.kind());
175 let ast_id = self.source_ast_id_map.ast_id(strukt);
176 let kind = match strukt.kind() {
177 ast::StructKind::Record(_) => StructDefKind::Record,
178 ast::StructKind::Tuple(_) => StructDefKind::Tuple,
179 ast::StructKind::Unit => StructDefKind::Unit,
180 };
181 let res = Struct { name, visibility, generic_params, fields, ast_id, kind };
182 Some(id(self.data().structs.alloc(res)))
183 }
184
185 fn lower_fields(&mut self, strukt_kind: &ast::StructKind) -> Fields {
186 match strukt_kind {
187 ast::StructKind::Record(it) => {
188 let range = self.lower_record_fields(it);
189 Fields::Record(range)
190 }
191 ast::StructKind::Tuple(it) => {
192 let range = self.lower_tuple_fields(it);
193 Fields::Tuple(range)
194 }
195 ast::StructKind::Unit => Fields::Unit,
196 }
197 }
198
199 fn lower_record_fields(&mut self, fields: &ast::RecordFieldDefList) -> Range<Idx<Field>> {
200 let start = self.next_field_idx();
201 for field in fields.fields() {
202 if let Some(data) = self.lower_record_field(&field) {
203 self.data().fields.alloc(data);
204 }
205 }
206 let end = self.next_field_idx();
207 start..end
208 }
209
210 fn lower_record_field(&mut self, field: &ast::RecordFieldDef) -> Option<Field> {
211 let name = field.name()?.as_name();
212 let visibility = self.lower_visibility(field);
213 let type_ref = self.lower_type_ref(&field.ascribed_type()?);
214 let res = Field { name, type_ref, visibility };
215 Some(res)
216 }
217
218 fn lower_tuple_fields(&mut self, fields: &ast::TupleFieldDefList) -> Range<Idx<Field>> {
219 let start = self.next_field_idx();
220 for (i, field) in fields.fields().enumerate() {
221 if let Some(data) = self.lower_tuple_field(i, &field) {
222 self.data().fields.alloc(data);
223 }
224 }
225 let end = self.next_field_idx();
226 start..end
227 }
228
229 fn lower_tuple_field(&mut self, idx: usize, field: &ast::TupleFieldDef) -> Option<Field> {
230 let name = Name::new_tuple_field(idx);
231 let visibility = self.lower_visibility(field);
232 let type_ref = self.lower_type_ref(&field.type_ref()?);
233 let res = Field { name, type_ref, visibility };
234 Some(res)
235 }
236
237 fn lower_union(&mut self, union: &ast::UnionDef) -> Option<FileItemTreeId<Union>> {
238 let visibility = self.lower_visibility(union);
239 let name = union.name()?.as_name();
240 let generic_params = self.lower_generic_params(GenericsOwner::Union, union);
241 let fields = match union.record_field_def_list() {
242 Some(record_field_def_list) => {
243 self.lower_fields(&StructKind::Record(record_field_def_list))
244 }
245 None => Fields::Record(self.next_field_idx()..self.next_field_idx()),
246 };
247 let ast_id = self.source_ast_id_map.ast_id(union);
248 let res = Union { name, visibility, generic_params, fields, ast_id };
249 Some(id(self.data().unions.alloc(res)))
250 }
251
252 fn lower_enum(&mut self, enum_: &ast::EnumDef) -> Option<FileItemTreeId<Enum>> {
253 let visibility = self.lower_visibility(enum_);
254 let name = enum_.name()?.as_name();
255 let generic_params = self.lower_generic_params(GenericsOwner::Enum, enum_);
256 let variants = match &enum_.variant_list() {
257 Some(variant_list) => self.lower_variants(variant_list),
258 None => self.next_variant_idx()..self.next_variant_idx(),
259 };
260 let ast_id = self.source_ast_id_map.ast_id(enum_);
261 let res = Enum { name, visibility, generic_params, variants, ast_id };
262 Some(id(self.data().enums.alloc(res)))
263 }
264
265 fn lower_variants(&mut self, variants: &ast::EnumVariantList) -> Range<Idx<Variant>> {
266 let start = self.next_variant_idx();
267 for variant in variants.variants() {
268 if let Some(data) = self.lower_variant(&variant) {
269 self.data().variants.alloc(data);
270 }
271 }
272 let end = self.next_variant_idx();
273 start..end
274 }
275
276 fn lower_variant(&mut self, variant: &ast::EnumVariant) -> Option<Variant> {
277 let name = variant.name()?.as_name();
278 let fields = self.lower_fields(&variant.kind());
279 let res = Variant { name, fields };
280 Some(res)
281 }
282
283 fn lower_function(&mut self, func: &ast::FnDef) -> Option<FileItemTreeId<Function>> {
284 let visibility = self.lower_visibility(func);
285 let name = func.name()?.as_name();
286
287 let mut params = Vec::new();
288 let mut has_self_param = false;
289 if let Some(param_list) = func.param_list() {
290 if let Some(self_param) = param_list.self_param() {
291 let self_type = match self_param.ascribed_type() {
292 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
293 None => {
294 let self_type = TypeRef::Path(name![Self].into());
295 match self_param.kind() {
296 ast::SelfParamKind::Owned => self_type,
297 ast::SelfParamKind::Ref => {
298 TypeRef::Reference(Box::new(self_type), Mutability::Shared)
299 }
300 ast::SelfParamKind::MutRef => {
301 TypeRef::Reference(Box::new(self_type), Mutability::Mut)
302 }
303 }
304 }
305 };
306 params.push(self_type);
307 has_self_param = true;
308 }
309 for param in param_list.params() {
310 let type_ref = TypeRef::from_ast_opt(&self.body_ctx, param.ascribed_type());
311 params.push(type_ref);
312 }
313 }
314 let ret_type = match func.ret_type().and_then(|rt| rt.type_ref()) {
315 Some(type_ref) => TypeRef::from_ast(&self.body_ctx, type_ref),
316 _ => TypeRef::unit(),
317 };
318
319 let ret_type = if func.async_token().is_some() {
320 let future_impl = desugar_future_path(ret_type);
321 let ty_bound = TypeBound::Path(future_impl);
322 TypeRef::ImplTrait(vec![ty_bound])
323 } else {
324 ret_type
325 };
326
327 let ast_id = self.source_ast_id_map.ast_id(func);
328 let mut res = Function {
329 name,
330 visibility,
331 generic_params: GenericParamsId::EMPTY,
332 has_self_param,
333 is_unsafe: func.unsafe_token().is_some(),
334 params: params.into_boxed_slice(),
335 ret_type,
336 ast_id,
337 };
338 res.generic_params = self.lower_generic_params(GenericsOwner::Function(&res), func);
339
340 Some(id(self.data().functions.alloc(res)))
341 }
342
343 fn lower_type_alias(
344 &mut self,
345 type_alias: &ast::TypeAliasDef,
346 ) -> Option<FileItemTreeId<TypeAlias>> {
347 let name = type_alias.name()?.as_name();
348 let type_ref = type_alias.type_ref().map(|it| self.lower_type_ref(&it));
349 let visibility = self.lower_visibility(type_alias);
350 let bounds = self.lower_type_bounds(type_alias);
351 let generic_params = self.lower_generic_params(GenericsOwner::TypeAlias, type_alias);
352 let ast_id = self.source_ast_id_map.ast_id(type_alias);
353 let res = TypeAlias {
354 name,
355 visibility,
356 bounds: bounds.into_boxed_slice(),
357 generic_params,
358 type_ref,
359 ast_id,
360 };
361 Some(id(self.data().type_aliases.alloc(res)))
362 }
363
364 fn lower_static(&mut self, static_: &ast::StaticDef) -> Option<FileItemTreeId<Static>> {
365 let name = static_.name()?.as_name();
366 let type_ref = self.lower_type_ref_opt(static_.ascribed_type());
367 let visibility = self.lower_visibility(static_);
368 let mutable = static_.mut_token().is_some();
369 let ast_id = self.source_ast_id_map.ast_id(static_);
370 let res = Static { name, visibility, mutable, type_ref, ast_id };
371 Some(id(self.data().statics.alloc(res)))
372 }
373
374 fn lower_const(&mut self, konst: &ast::ConstDef) -> FileItemTreeId<Const> {
375 let name = konst.name().map(|it| it.as_name());
376 let type_ref = self.lower_type_ref_opt(konst.ascribed_type());
377 let visibility = self.lower_visibility(konst);
378 let ast_id = self.source_ast_id_map.ast_id(konst);
379 let res = Const { name, visibility, type_ref, ast_id };
380 id(self.data().consts.alloc(res))
381 }
382
383 fn lower_module(&mut self, module: &ast::Module) -> Option<FileItemTreeId<Mod>> {
384 let name = module.name()?.as_name();
385 let visibility = self.lower_visibility(module);
386 let kind = if module.semicolon_token().is_some() {
387 ModKind::Outline {}
388 } else {
389 ModKind::Inline {
390 items: module
391 .item_list()
392 .map(|list| {
393 list.items()
394 .flat_map(|item| self.lower_mod_item(&item, false))
395 .flat_map(|items| items.0)
396 .collect()
397 })
398 .unwrap_or_else(|| {
399 mark::hit!(name_res_works_for_broken_modules);
400 Box::new([]) as Box<[_]>
401 }),
402 }
403 };
404 let ast_id = self.source_ast_id_map.ast_id(module);
405 let res = Mod { name, visibility, kind, ast_id };
406 Some(id(self.data().mods.alloc(res)))
407 }
408
409 fn lower_trait(&mut self, trait_def: &ast::TraitDef) -> Option<FileItemTreeId<Trait>> {
410 let name = trait_def.name()?.as_name();
411 let visibility = self.lower_visibility(trait_def);
412 let generic_params =
413 self.lower_generic_params_and_inner_items(GenericsOwner::Trait(trait_def), trait_def);
414 let auto = trait_def.auto_token().is_some();
415 let items = trait_def.item_list().map(|list| {
416 self.with_inherited_visibility(visibility, |this| {
417 list.items()
418 .filter_map(|item| {
419 let attrs = Attrs::new(&item, &this.hygiene);
420 this.collect_inner_items(item.syntax());
421 this.lower_assoc_item(&item).map(|item| {
422 this.add_attrs(item.into(), attrs);
423 item
424 })
425 })
426 .collect()
427 })
428 });
429 let ast_id = self.source_ast_id_map.ast_id(trait_def);
430 let res = Trait {
431 name,
432 visibility,
433 generic_params,
434 auto,
435 items: items.unwrap_or_default(),
436 ast_id,
437 };
438 Some(id(self.data().traits.alloc(res)))
439 }
440
441 fn lower_impl(&mut self, impl_def: &ast::ImplDef) -> Option<FileItemTreeId<Impl>> {
442 let generic_params =
443 self.lower_generic_params_and_inner_items(GenericsOwner::Impl, impl_def);
444 let target_trait = impl_def.target_trait().map(|tr| self.lower_type_ref(&tr));
445 let target_type = self.lower_type_ref(&impl_def.target_type()?);
446 let is_negative = impl_def.excl_token().is_some();
447
448 // We cannot use `assoc_items()` here as that does not include macro calls.
449 let items = impl_def
450 .item_list()?
451 .items()
452 .filter_map(|item| {
453 self.collect_inner_items(item.syntax());
454 let assoc = self.lower_assoc_item(&item)?;
455 let attrs = Attrs::new(&item, &self.hygiene);
456 self.add_attrs(assoc.into(), attrs);
457 Some(assoc)
458 })
459 .collect();
460 let ast_id = self.source_ast_id_map.ast_id(impl_def);
461 let res = Impl { generic_params, target_trait, target_type, is_negative, items, ast_id };
462 Some(id(self.data().impls.alloc(res)))
463 }
464
465 fn lower_use(&mut self, use_item: &ast::UseItem) -> Vec<FileItemTreeId<Import>> {
466 // FIXME: cfg_attr
467 let is_prelude = use_item.has_atom_attr("prelude_import");
468 let visibility = self.lower_visibility(use_item);
469 let ast_id = self.source_ast_id_map.ast_id(use_item);
470
471 // Every use item can expand to many `Import`s.
472 let mut imports = Vec::new();
473 let tree = self.tree.data_mut();
474 ModPath::expand_use_item(
475 InFile::new(self.file, use_item.clone()),
476 &self.hygiene,
477 |path, _tree, is_glob, alias| {
478 imports.push(id(tree.imports.alloc(Import {
479 path,
480 alias,
481 visibility,
482 is_glob,
483 is_prelude,
484 ast_id,
485 })));
486 },
487 );
488
489 imports
490 }
491
492 fn lower_extern_crate(
493 &mut self,
494 extern_crate: &ast::ExternCrateItem,
495 ) -> Option<FileItemTreeId<ExternCrate>> {
496 let path = ModPath::from_name_ref(&extern_crate.name_ref()?);
497 let alias = extern_crate.alias().map(|a| {
498 a.name().map(|it| it.as_name()).map_or(ImportAlias::Underscore, ImportAlias::Alias)
499 });
500 let visibility = self.lower_visibility(extern_crate);
501 let ast_id = self.source_ast_id_map.ast_id(extern_crate);
502 // FIXME: cfg_attr
503 let is_macro_use = extern_crate.has_atom_attr("macro_use");
504
505 let res = ExternCrate { path, alias, visibility, is_macro_use, ast_id };
506 Some(id(self.data().extern_crates.alloc(res)))
507 }
508
509 fn lower_macro_call(&mut self, m: &ast::MacroCall) -> Option<FileItemTreeId<MacroCall>> {
510 let name = m.name().map(|it| it.as_name());
511 let attrs = Attrs::new(m, &self.hygiene);
512 let path = ModPath::from_src(m.path()?, &self.hygiene)?;
513
514 let ast_id = self.source_ast_id_map.ast_id(m);
515
516 // FIXME: cfg_attr
517 let export_attr = attrs.by_key("macro_export");
518
519 let is_export = export_attr.exists();
520 let is_local_inner = if is_export {
521 export_attr.tt_values().map(|it| &it.token_trees).flatten().any(|it| match it {
522 tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
523 ident.text.contains("local_inner_macros")
524 }
525 _ => false,
526 })
527 } else {
528 false
529 };
530
531 let is_builtin = attrs.by_key("rustc_builtin_macro").exists();
532 let res = MacroCall { name, path, is_export, is_builtin, is_local_inner, ast_id };
533 Some(id(self.data().macro_calls.alloc(res)))
534 }
535
536 fn lower_extern_block(&mut self, block: &ast::ExternBlock) -> Vec<ModItem> {
537 block.extern_item_list().map_or(Vec::new(), |list| {
538 list.extern_items()
539 .filter_map(|item| {
540 self.collect_inner_items(item.syntax());
541 let attrs = Attrs::new(&item, &self.hygiene);
542 let id = match item {
543 ast::ExternItem::FnDef(ast) => {
544 let func = self.lower_function(&ast)?;
545 func.into()
546 }
547 ast::ExternItem::StaticDef(ast) => {
548 let statik = self.lower_static(&ast)?;
549 statik.into()
550 }
551 };
552 self.add_attrs(id, attrs);
553 Some(id)
554 })
555 .collect()
556 })
557 }
558
559 /// Lowers generics defined on `node` and collects inner items defined within.
560 fn lower_generic_params_and_inner_items(
561 &mut self,
562 owner: GenericsOwner<'_>,
563 node: &impl ast::TypeParamsOwner,
564 ) -> GenericParamsId {
565 // Generics are part of item headers and may contain inner items we need to collect.
566 if let Some(params) = node.type_param_list() {
567 self.collect_inner_items(params.syntax());
568 }
569 if let Some(clause) = node.where_clause() {
570 self.collect_inner_items(clause.syntax());
571 }
572
573 self.lower_generic_params(owner, node)
574 }
575
576 fn lower_generic_params(
577 &mut self,
578 owner: GenericsOwner<'_>,
579 node: &impl ast::TypeParamsOwner,
580 ) -> GenericParamsId {
581 let mut sm = &mut ArenaMap::default();
582 let mut generics = GenericParams::default();
583 match owner {
584 GenericsOwner::Function(func) => {
585 generics.fill(&self.body_ctx, sm, node);
586 // lower `impl Trait` in arguments
587 for param in &*func.params {
588 generics.fill_implicit_impl_trait_args(param);
589 }
590 }
591 GenericsOwner::Struct
592 | GenericsOwner::Enum
593 | GenericsOwner::Union
594 | GenericsOwner::TypeAlias => {
595 generics.fill(&self.body_ctx, sm, node);
596 }
597 GenericsOwner::Trait(trait_def) => {
598 // traits get the Self type as an implicit first type parameter
599 let self_param_id = generics.types.alloc(TypeParamData {
600 name: Some(name![Self]),
601 default: None,
602 provenance: TypeParamProvenance::TraitSelf,
603 });
604 sm.insert(self_param_id, Either::Left(trait_def.clone()));
605 // add super traits as bounds on Self
606 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
607 let self_param = TypeRef::Path(name![Self].into());
608 generics.fill_bounds(&self.body_ctx, trait_def, self_param);
609
610 generics.fill(&self.body_ctx, &mut sm, node);
611 }
612 GenericsOwner::Impl => {
613 // Note that we don't add `Self` here: in `impl`s, `Self` is not a
614 // type-parameter, but rather is a type-alias for impl's target
615 // type, so this is handled by the resolver.
616 generics.fill(&self.body_ctx, &mut sm, node);
617 }
618 }
619
620 self.data().generics.alloc(generics)
621 }
622
623 fn lower_type_bounds(&mut self, node: &impl ast::TypeBoundsOwner) -> Vec<TypeBound> {
624 match node.type_bound_list() {
625 Some(bound_list) => {
626 bound_list.bounds().map(|it| TypeBound::from_ast(&self.body_ctx, it)).collect()
627 }
628 None => Vec::new(),
629 }
630 }
631
632 fn lower_visibility(&mut self, item: &impl ast::VisibilityOwner) -> RawVisibilityId {
633 let vis = match self.forced_visibility {
634 Some(vis) => return vis,
635 None => RawVisibility::from_ast_with_hygiene(item.visibility(), &self.hygiene),
636 };
637
638 self.data().vis.alloc(vis)
639 }
640
641 fn lower_type_ref(&self, type_ref: &ast::TypeRef) -> TypeRef {
642 TypeRef::from_ast(&self.body_ctx, type_ref.clone())
643 }
644 fn lower_type_ref_opt(&self, type_ref: Option<ast::TypeRef>) -> TypeRef {
645 type_ref.map(|ty| self.lower_type_ref(&ty)).unwrap_or(TypeRef::Error)
646 }
647
648 /// Forces the visibility `vis` to be used for all items lowered during execution of `f`.
649 fn with_inherited_visibility<R>(
650 &mut self,
651 vis: RawVisibilityId,
652 f: impl FnOnce(&mut Self) -> R,
653 ) -> R {
654 let old = mem::replace(&mut self.forced_visibility, Some(vis));
655 let res = f(self);
656 self.forced_visibility = old;
657 res
658 }
659
660 fn next_field_idx(&self) -> Idx<Field> {
661 Idx::from_raw(RawId::from(
662 self.tree.data.as_ref().map_or(0, |data| data.fields.len() as u32),
663 ))
664 }
665 fn next_variant_idx(&self) -> Idx<Variant> {
666 Idx::from_raw(RawId::from(
667 self.tree.data.as_ref().map_or(0, |data| data.variants.len() as u32),
668 ))
669 }
670}
671
672fn desugar_future_path(orig: TypeRef) -> Path {
673 let path = path![core::future::Future];
674 let mut generic_args: Vec<_> = std::iter::repeat(None).take(path.segments.len() - 1).collect();
675 let mut last = GenericArgs::empty();
676 let binding =
677 AssociatedTypeBinding { name: name![Output], type_ref: Some(orig), bounds: Vec::new() };
678 last.bindings.push(binding);
679 generic_args.push(Some(Arc::new(last)));
680
681 Path::from_known_path(path, generic_args)
682}
683
684enum GenericsOwner<'a> {
685 /// We need access to the partially-lowered `Function` for lowering `impl Trait` in argument
686 /// position.
687 Function(&'a Function),
688 Struct,
689 Enum,
690 Union,
691 /// The `TraitDef` is needed to fill the source map for the implicit `Self` parameter.
692 Trait(&'a ast::TraitDef),
693 TypeAlias,
694 Impl,
695}