]>
Commit | Line | Data |
---|---|---|
dfeec247 | 1 | use super::{AnonymousLifetimeMode, LoweringContext, ParamMode}; |
f035d41b | 2 | use super::{ImplTraitContext, ImplTraitPosition}; |
ba9703b0 | 3 | use crate::Arena; |
dfeec247 | 4 | |
74b04a01 | 5 | use rustc_ast::node_id::NodeMap; |
ba9703b0 | 6 | use rustc_ast::ptr::P; |
3dfed10e XL |
7 | use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; |
8 | use rustc_ast::*; | |
f035d41b | 9 | use rustc_data_structures::fx::FxHashSet; |
dfeec247 XL |
10 | use rustc_errors::struct_span_err; |
11 | use rustc_hir as hir; | |
12 | use rustc_hir::def::{DefKind, Res}; | |
ba9703b0 | 13 | use rustc_hir::def_id::LocalDefId; |
dfeec247 | 14 | use rustc_span::source_map::{respan, DesugaringKind}; |
f9f354fc | 15 | use rustc_span::symbol::{kw, sym, Ident}; |
dfeec247 | 16 | use rustc_span::Span; |
60c5eb7d | 17 | use rustc_target::spec::abi; |
dfeec247 | 18 | use smallvec::{smallvec, SmallVec}; |
3dfed10e | 19 | use tracing::debug; |
60c5eb7d | 20 | |
6a06907d XL |
21 | use std::mem; |
22 | ||
dfeec247 XL |
23 | pub(super) struct ItemLowerer<'a, 'lowering, 'hir> { |
24 | pub(super) lctx: &'a mut LoweringContext<'lowering, 'hir>, | |
416331ca XL |
25 | } |
26 | ||
dfeec247 XL |
27 | impl ItemLowerer<'_, '_, '_> { |
28 | fn with_trait_impl_ref(&mut self, impl_ref: &Option<TraitRef>, f: impl FnOnce(&mut Self)) { | |
416331ca | 29 | let old = self.lctx.is_in_trait_impl; |
1b1a35ee | 30 | self.lctx.is_in_trait_impl = impl_ref.is_some(); |
416331ca XL |
31 | f(self); |
32 | self.lctx.is_in_trait_impl = old; | |
33 | } | |
34 | } | |
35 | ||
dfeec247 | 36 | impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> { |
dfeec247 | 37 | fn visit_item(&mut self, item: &'a Item) { |
416331ca XL |
38 | let mut item_hir_id = None; |
39 | self.lctx.with_hir_id_owner(item.id, |lctx| { | |
e1599b0c XL |
40 | lctx.without_in_scope_lifetime_defs(|lctx| { |
41 | if let Some(hir_item) = lctx.lower_item(item) { | |
6a06907d XL |
42 | let id = lctx.insert_item(hir_item); |
43 | item_hir_id = Some(id); | |
e1599b0c XL |
44 | } |
45 | }) | |
416331ca XL |
46 | }); |
47 | ||
48 | if let Some(hir_id) = item_hir_id { | |
49 | self.lctx.with_parent_item_lifetime_defs(hir_id, |this| { | |
50 | let this = &mut ItemLowerer { lctx: this }; | |
6a06907d XL |
51 | match item.kind { |
52 | ItemKind::Mod(..) => { | |
53 | let def_id = this.lctx.lower_node_id(item.id).expect_owner(); | |
54 | let old_current_module = | |
55 | mem::replace(&mut this.lctx.current_module, def_id); | |
56 | visit::walk_item(this, item); | |
57 | this.lctx.current_module = old_current_module; | |
58 | } | |
59 | ItemKind::Impl(box ImplKind { ref of_trait, .. }) => { | |
60 | this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item)); | |
61 | } | |
62 | _ => visit::walk_item(this, item), | |
416331ca XL |
63 | } |
64 | }); | |
65 | } | |
66 | } | |
67 | ||
3dfed10e XL |
68 | fn visit_fn(&mut self, fk: FnKind<'a>, sp: Span, _: NodeId) { |
69 | match fk { | |
70 | FnKind::Fn(FnCtxt::Foreign, _, sig, _, _) => { | |
71 | self.visit_fn_header(&sig.header); | |
72 | visit::walk_fn_decl(self, &sig.decl); | |
73 | // Don't visit the foreign function body even if it has one, since lowering the | |
74 | // body would have no meaning and will have already been caught as a parse error. | |
75 | } | |
76 | _ => visit::walk_fn(self, fk, sp), | |
77 | } | |
78 | } | |
79 | ||
74b04a01 XL |
80 | fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) { |
81 | self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt { | |
82 | AssocCtxt::Trait => { | |
83 | let hir_item = lctx.lower_trait_item(item); | |
6a06907d | 84 | let id = hir_item.trait_item_id(); |
74b04a01 | 85 | lctx.trait_items.insert(id, hir_item); |
6a06907d | 86 | lctx.modules.entry(lctx.current_module).or_default().trait_items.insert(id); |
74b04a01 XL |
87 | } |
88 | AssocCtxt::Impl => { | |
89 | let hir_item = lctx.lower_impl_item(item); | |
6a06907d | 90 | let id = hir_item.impl_item_id(); |
74b04a01 | 91 | lctx.impl_items.insert(id, hir_item); |
6a06907d | 92 | lctx.modules.entry(lctx.current_module).or_default().impl_items.insert(id); |
74b04a01 | 93 | } |
416331ca XL |
94 | }); |
95 | ||
74b04a01 | 96 | visit::walk_assoc_item(self, item, ctxt); |
416331ca | 97 | } |
fc512014 XL |
98 | |
99 | fn visit_foreign_item(&mut self, item: &'a ForeignItem) { | |
100 | self.lctx.allocate_hir_id_counter(item.id); | |
101 | self.lctx.with_hir_id_owner(item.id, |lctx| { | |
102 | let hir_item = lctx.lower_foreign_item(item); | |
6a06907d | 103 | let id = hir_item.foreign_item_id(); |
fc512014 | 104 | lctx.foreign_items.insert(id, hir_item); |
6a06907d | 105 | lctx.modules.entry(lctx.current_module).or_default().foreign_items.insert(id); |
fc512014 XL |
106 | }); |
107 | ||
108 | visit::walk_foreign_item(self, item); | |
109 | } | |
416331ca XL |
110 | } |
111 | ||
dfeec247 | 112 | impl<'hir> LoweringContext<'_, 'hir> { |
416331ca XL |
113 | // Same as the method above, but accepts `hir::GenericParam`s |
114 | // instead of `ast::GenericParam`s. | |
115 | // This should only be used with generics that have already had their | |
116 | // in-band lifetimes added. In practice, this means that this function is | |
117 | // only used when lowering a child item of a trait or impl. | |
118 | fn with_parent_item_lifetime_defs<T>( | |
119 | &mut self, | |
6a06907d | 120 | parent_hir_id: hir::ItemId, |
dfeec247 | 121 | f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T, |
416331ca XL |
122 | ) -> T { |
123 | let old_len = self.in_scope_lifetimes.len(); | |
124 | ||
e74abb32 | 125 | let parent_generics = match self.items.get(&parent_hir_id).unwrap().kind { |
5869c6ff | 126 | hir::ItemKind::Impl(hir::Impl { ref generics, .. }) |
6a06907d | 127 | | hir::ItemKind::Trait(_, _, ref generics, ..) => generics.params, |
416331ca XL |
128 | _ => &[], |
129 | }; | |
130 | let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind { | |
ba9703b0 | 131 | hir::GenericParamKind::Lifetime { .. } => Some(param.name.normalize_to_macros_2_0()), |
416331ca XL |
132 | _ => None, |
133 | }); | |
134 | self.in_scope_lifetimes.extend(lt_def_names); | |
135 | ||
136 | let res = f(self); | |
137 | ||
138 | self.in_scope_lifetimes.truncate(old_len); | |
139 | res | |
140 | } | |
141 | ||
e1599b0c XL |
142 | // Clears (and restores) the `in_scope_lifetimes` field. Used when |
143 | // visiting nested items, which never inherit in-scope lifetimes | |
144 | // from their surrounding environment. | |
145 | fn without_in_scope_lifetime_defs<T>( | |
146 | &mut self, | |
dfeec247 | 147 | f: impl FnOnce(&mut LoweringContext<'_, '_>) -> T, |
e1599b0c | 148 | ) -> T { |
6a06907d | 149 | let old_in_scope_lifetimes = mem::replace(&mut self.in_scope_lifetimes, vec![]); |
e1599b0c XL |
150 | |
151 | // this vector is only used when walking over impl headers, | |
152 | // input types, and the like, and should not be non-empty in | |
153 | // between items | |
154 | assert!(self.lifetimes_to_define.is_empty()); | |
155 | ||
156 | let res = f(self); | |
157 | ||
158 | assert!(self.in_scope_lifetimes.is_empty()); | |
159 | self.in_scope_lifetimes = old_in_scope_lifetimes; | |
160 | ||
161 | res | |
162 | } | |
163 | ||
6a06907d | 164 | pub(super) fn lower_mod(&mut self, items: &[P<Item>], inner: Span) -> hir::Mod<'hir> { |
416331ca | 165 | hir::Mod { |
6a06907d XL |
166 | inner, |
167 | item_ids: self.arena.alloc_from_iter(items.iter().flat_map(|x| self.lower_item_id(x))), | |
416331ca XL |
168 | } |
169 | } | |
170 | ||
171 | pub(super) fn lower_item_id(&mut self, i: &Item) -> SmallVec<[hir::ItemId; 1]> { | |
e74abb32 | 172 | let node_ids = match i.kind { |
416331ca XL |
173 | ItemKind::Use(ref use_tree) => { |
174 | let mut vec = smallvec![i.id]; | |
175 | self.lower_item_id_use_tree(use_tree, i.id, &mut vec); | |
176 | vec | |
177 | } | |
178 | ItemKind::MacroDef(..) => SmallVec::new(), | |
5869c6ff XL |
179 | ItemKind::Fn(..) | ItemKind::Impl(box ImplKind { of_trait: None, .. }) => { |
180 | smallvec![i.id] | |
181 | } | |
416331ca XL |
182 | _ => smallvec![i.id], |
183 | }; | |
184 | ||
dfeec247 XL |
185 | node_ids |
186 | .into_iter() | |
6a06907d XL |
187 | .map(|node_id| hir::ItemId { |
188 | def_id: self.allocate_hir_id_counter(node_id).expect_owner(), | |
189 | }) | |
dfeec247 | 190 | .collect() |
416331ca XL |
191 | } |
192 | ||
193 | fn lower_item_id_use_tree( | |
194 | &mut self, | |
195 | tree: &UseTree, | |
196 | base_id: NodeId, | |
dfeec247 | 197 | vec: &mut SmallVec<[NodeId; 1]>, |
416331ca XL |
198 | ) { |
199 | match tree.kind { | |
dfeec247 XL |
200 | UseTreeKind::Nested(ref nested_vec) => { |
201 | for &(ref nested, id) in nested_vec { | |
202 | vec.push(id); | |
203 | self.lower_item_id_use_tree(nested, id, vec); | |
204 | } | |
205 | } | |
416331ca XL |
206 | UseTreeKind::Glob => {} |
207 | UseTreeKind::Simple(_, id1, id2) => { | |
dfeec247 XL |
208 | for (_, &id) in |
209 | self.expect_full_res_from_use(base_id).skip(1).zip([id1, id2].iter()) | |
416331ca XL |
210 | { |
211 | vec.push(id); | |
212 | } | |
dfeec247 | 213 | } |
416331ca XL |
214 | } |
215 | } | |
216 | ||
dfeec247 | 217 | pub fn lower_item(&mut self, i: &Item) -> Option<hir::Item<'hir>> { |
416331ca XL |
218 | let mut ident = i.ident; |
219 | let mut vis = self.lower_visibility(&i.vis, None); | |
416331ca | 220 | |
ba9703b0 | 221 | if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind { |
3dfed10e | 222 | if !macro_rules || self.sess.contains_name(&i.attrs, sym::macro_export) { |
416331ca | 223 | let hir_id = self.lower_node_id(i.id); |
6a06907d | 224 | self.lower_attrs(hir_id, &i.attrs); |
ba9703b0 | 225 | let body = P(self.lower_mac_args(body)); |
416331ca | 226 | self.exported_macros.push(hir::MacroDef { |
ba9703b0 | 227 | ident, |
416331ca | 228 | vis, |
6a06907d | 229 | def_id: hir_id.expect_owner(), |
416331ca | 230 | span: i.span, |
ba9703b0 | 231 | ast: MacroDef { body, macro_rules }, |
416331ca XL |
232 | }); |
233 | } else { | |
6a06907d XL |
234 | for a in i.attrs.iter() { |
235 | let a = self.lower_attr(a); | |
236 | self.non_exported_macro_attrs.push(a); | |
237 | } | |
416331ca XL |
238 | } |
239 | return None; | |
240 | } | |
241 | ||
6a06907d XL |
242 | let hir_id = self.lower_node_id(i.id); |
243 | let attrs = self.lower_attrs(hir_id, &i.attrs); | |
244 | let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind); | |
245 | Some(hir::Item { def_id: hir_id.expect_owner(), ident, kind, vis, span: i.span }) | |
416331ca XL |
246 | } |
247 | ||
248 | fn lower_item_kind( | |
249 | &mut self, | |
dfeec247 | 250 | span: Span, |
416331ca | 251 | id: NodeId, |
6a06907d | 252 | hir_id: hir::HirId, |
416331ca | 253 | ident: &mut Ident, |
6a06907d | 254 | attrs: Option<&'hir [Attribute]>, |
dfeec247 | 255 | vis: &mut hir::Visibility<'hir>, |
416331ca | 256 | i: &ItemKind, |
dfeec247 | 257 | ) -> hir::ItemKind<'hir> { |
416331ca XL |
258 | match *i { |
259 | ItemKind::ExternCrate(orig_name) => hir::ItemKind::ExternCrate(orig_name), | |
260 | ItemKind::Use(ref use_tree) => { | |
261 | // Start with an empty prefix. | |
1b1a35ee | 262 | let prefix = Path { segments: vec![], span: use_tree.span, tokens: None }; |
416331ca XL |
263 | |
264 | self.lower_use_tree(use_tree, &prefix, id, vis, ident, attrs) | |
265 | } | |
266 | ItemKind::Static(ref t, m, ref e) => { | |
74b04a01 XL |
267 | let (ty, body_id) = self.lower_const_item(t, span, e.as_deref()); |
268 | hir::ItemKind::Static(ty, m, body_id) | |
416331ca | 269 | } |
74b04a01 XL |
270 | ItemKind::Const(_, ref t, ref e) => { |
271 | let (ty, body_id) = self.lower_const_item(t, span, e.as_deref()); | |
272 | hir::ItemKind::Const(ty, body_id) | |
416331ca | 273 | } |
5869c6ff | 274 | ItemKind::Fn(box FnKind( |
3dfed10e XL |
275 | _, |
276 | FnSig { ref decl, header, span: fn_sig_span }, | |
277 | ref generics, | |
278 | ref body, | |
5869c6ff | 279 | )) => { |
f035d41b | 280 | let fn_def_id = self.resolver.local_def_id(id); |
416331ca XL |
281 | self.with_new_scopes(|this| { |
282 | this.current_item = Some(ident.span); | |
283 | ||
284 | // Note: we don't need to change the return type from `T` to | |
285 | // `impl Future<Output = T>` here because lower_body | |
286 | // only cares about the input argument patterns in the function | |
287 | // declaration (decl), not the return types. | |
74b04a01 | 288 | let asyncness = header.asyncness; |
dfeec247 | 289 | let body_id = |
74b04a01 | 290 | this.lower_maybe_async_body(span, &decl, asyncness, body.as_deref()); |
416331ca | 291 | |
60c5eb7d | 292 | let (generics, decl) = this.add_in_band_defs( |
416331ca XL |
293 | generics, |
294 | fn_def_id, | |
295 | AnonymousLifetimeMode::PassThrough, | |
dfeec247 | 296 | |this, idty| { |
74b04a01 | 297 | let ret_id = asyncness.opt_return_id(); |
ba9703b0 XL |
298 | this.lower_fn_decl( |
299 | &decl, | |
300 | Some((fn_def_id.to_def_id(), idty)), | |
301 | true, | |
302 | ret_id, | |
303 | ) | |
dfeec247 | 304 | }, |
416331ca | 305 | ); |
3dfed10e XL |
306 | let sig = hir::FnSig { |
307 | decl, | |
5869c6ff | 308 | header: this.lower_fn_header(header, fn_sig_span, id), |
3dfed10e XL |
309 | span: fn_sig_span, |
310 | }; | |
60c5eb7d | 311 | hir::ItemKind::Fn(sig, generics, body_id) |
416331ca XL |
312 | }) |
313 | } | |
6a06907d XL |
314 | ItemKind::Mod(_, ref mod_kind) => match mod_kind { |
315 | ModKind::Loaded(items, _, inner_span) => { | |
316 | hir::ItemKind::Mod(self.lower_mod(items, *inner_span)) | |
317 | } | |
318 | ModKind::Unloaded => panic!("`mod` items should have been loaded by now"), | |
319 | }, | |
5869c6ff XL |
320 | ItemKind::ForeignMod(ref fm) => { |
321 | if fm.abi.is_none() { | |
6a06907d | 322 | self.maybe_lint_missing_abi(span, id, abi::Abi::C { unwind: false }); |
5869c6ff XL |
323 | } |
324 | hir::ItemKind::ForeignMod { | |
6a06907d | 325 | abi: fm.abi.map_or(abi::Abi::C { unwind: false }, |abi| self.lower_abi(abi)), |
5869c6ff XL |
326 | items: self |
327 | .arena | |
328 | .alloc_from_iter(fm.items.iter().map(|x| self.lower_foreign_item_ref(x))), | |
329 | } | |
330 | } | |
416331ca | 331 | ItemKind::GlobalAsm(ref ga) => hir::ItemKind::GlobalAsm(self.lower_global_asm(ga)), |
5869c6ff | 332 | ItemKind::TyAlias(box TyAliasKind(_, ref gen, _, Some(ref ty))) => { |
f035d41b XL |
333 | // We lower |
334 | // | |
335 | // type Foo = impl Trait | |
336 | // | |
337 | // to | |
338 | // | |
339 | // type Foo = Foo1 | |
340 | // opaque type Foo1: Trait | |
341 | let ty = self.lower_ty( | |
342 | ty, | |
343 | ImplTraitContext::OtherOpaqueTy { | |
344 | capturable_lifetimes: &mut FxHashSet::default(), | |
6a06907d | 345 | origin: hir::OpaqueTyOrigin::TyAlias, |
f035d41b XL |
346 | }, |
347 | ); | |
348 | let generics = self.lower_generics(gen, ImplTraitContext::disallowed()); | |
349 | hir::ItemKind::TyAlias(ty, generics) | |
350 | } | |
5869c6ff | 351 | ItemKind::TyAlias(box TyAliasKind(_, ref generics, _, None)) => { |
74b04a01 XL |
352 | let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err)); |
353 | let generics = self.lower_generics(generics, ImplTraitContext::disallowed()); | |
354 | hir::ItemKind::TyAlias(ty, generics) | |
355 | } | |
dfeec247 XL |
356 | ItemKind::Enum(ref enum_definition, ref generics) => hir::ItemKind::Enum( |
357 | hir::EnumDef { | |
358 | variants: self.arena.alloc_from_iter( | |
359 | enum_definition.variants.iter().map(|x| self.lower_variant(x)), | |
360 | ), | |
361 | }, | |
362 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
363 | ), | |
416331ca | 364 | ItemKind::Struct(ref struct_def, ref generics) => { |
6a06907d | 365 | let struct_def = self.lower_variant_data(hir_id, struct_def); |
416331ca XL |
366 | hir::ItemKind::Struct( |
367 | struct_def, | |
368 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
369 | ) | |
370 | } | |
371 | ItemKind::Union(ref vdata, ref generics) => { | |
6a06907d | 372 | let vdata = self.lower_variant_data(hir_id, vdata); |
416331ca XL |
373 | hir::ItemKind::Union( |
374 | vdata, | |
375 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
376 | ) | |
377 | } | |
5869c6ff | 378 | ItemKind::Impl(box ImplKind { |
416331ca XL |
379 | unsafety, |
380 | polarity, | |
381 | defaultness, | |
dfeec247 XL |
382 | constness, |
383 | generics: ref ast_generics, | |
384 | of_trait: ref trait_ref, | |
385 | self_ty: ref ty, | |
386 | items: ref impl_items, | |
5869c6ff | 387 | }) => { |
416331ca XL |
388 | // Lower the "impl header" first. This ordering is important |
389 | // for in-band lifetimes! Consider `'a` here: | |
390 | // | |
391 | // impl Foo<'a> for u32 { | |
392 | // fn method(&'a self) { .. } | |
393 | // } | |
394 | // | |
395 | // Because we start by lowering the `Foo<'a> for u32` | |
396 | // part, we will add `'a` to the list of generics on | |
397 | // the impl. When we then encounter it later in the | |
398 | // method, it will not be considered an in-band | |
399 | // lifetime to be added, but rather a reference to a | |
400 | // parent lifetime. | |
6a06907d | 401 | let lowered_trait_def_id = self.lower_node_id(id).expect_owner(); |
416331ca XL |
402 | let (generics, (trait_ref, lowered_ty)) = self.add_in_band_defs( |
403 | ast_generics, | |
6a06907d | 404 | lowered_trait_def_id, |
416331ca XL |
405 | AnonymousLifetimeMode::CreateParameter, |
406 | |this, _| { | |
407 | let trait_ref = trait_ref.as_ref().map(|trait_ref| { | |
408 | this.lower_trait_ref(trait_ref, ImplTraitContext::disallowed()) | |
409 | }); | |
410 | ||
411 | if let Some(ref trait_ref) = trait_ref { | |
412 | if let Res::Def(DefKind::Trait, def_id) = trait_ref.path.res { | |
dfeec247 XL |
413 | this.trait_impls |
414 | .entry(def_id) | |
415 | .or_default() | |
6a06907d | 416 | .push(lowered_trait_def_id); |
416331ca XL |
417 | } |
418 | } | |
419 | ||
420 | let lowered_ty = this.lower_ty(ty, ImplTraitContext::disallowed()); | |
421 | ||
422 | (trait_ref, lowered_ty) | |
423 | }, | |
424 | ); | |
425 | ||
dfeec247 XL |
426 | let new_impl_items = |
427 | self.with_in_scope_lifetime_defs(&ast_generics.params, |this| { | |
428 | this.arena.alloc_from_iter( | |
429 | impl_items.iter().map(|item| this.lower_impl_item_ref(item)), | |
430 | ) | |
431 | }); | |
416331ca | 432 | |
ba9703b0 XL |
433 | // `defaultness.has_value()` is never called for an `impl`, always `true` in order |
434 | // to not cause an assertion failure inside the `lower_defaultness` function. | |
435 | let has_val = true; | |
436 | let (defaultness, defaultness_span) = self.lower_defaultness(defaultness, has_val); | |
5869c6ff | 437 | hir::ItemKind::Impl(hir::Impl { |
74b04a01 | 438 | unsafety: self.lower_unsafety(unsafety), |
60c5eb7d | 439 | polarity, |
ba9703b0 XL |
440 | defaultness, |
441 | defaultness_span, | |
74b04a01 | 442 | constness: self.lower_constness(constness), |
416331ca | 443 | generics, |
dfeec247 XL |
444 | of_trait: trait_ref, |
445 | self_ty: lowered_ty, | |
446 | items: new_impl_items, | |
5869c6ff | 447 | }) |
416331ca | 448 | } |
5869c6ff XL |
449 | ItemKind::Trait(box TraitKind( |
450 | is_auto, | |
451 | unsafety, | |
452 | ref generics, | |
453 | ref bounds, | |
454 | ref items, | |
455 | )) => { | |
416331ca | 456 | let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed()); |
dfeec247 XL |
457 | let items = self |
458 | .arena | |
459 | .alloc_from_iter(items.iter().map(|item| self.lower_trait_item_ref(item))); | |
416331ca | 460 | hir::ItemKind::Trait( |
60c5eb7d | 461 | is_auto, |
74b04a01 | 462 | self.lower_unsafety(unsafety), |
416331ca XL |
463 | self.lower_generics(generics, ImplTraitContext::disallowed()), |
464 | bounds, | |
465 | items, | |
466 | ) | |
467 | } | |
468 | ItemKind::TraitAlias(ref generics, ref bounds) => hir::ItemKind::TraitAlias( | |
469 | self.lower_generics(generics, ImplTraitContext::disallowed()), | |
470 | self.lower_param_bounds(bounds, ImplTraitContext::disallowed()), | |
471 | ), | |
ba9703b0 XL |
472 | ItemKind::MacroDef(..) | ItemKind::MacCall(..) => { |
473 | panic!("`TyMac` should have been expanded by now") | |
dfeec247 | 474 | } |
416331ca | 475 | } |
416331ca XL |
476 | } |
477 | ||
74b04a01 XL |
478 | fn lower_const_item( |
479 | &mut self, | |
480 | ty: &Ty, | |
481 | span: Span, | |
482 | body: Option<&Expr>, | |
483 | ) -> (&'hir hir::Ty<'hir>, hir::BodyId) { | |
f035d41b | 484 | let mut capturable_lifetimes; |
74b04a01 | 485 | let itctx = if self.sess.features_untracked().impl_trait_in_bindings { |
f035d41b XL |
486 | capturable_lifetimes = FxHashSet::default(); |
487 | ImplTraitContext::OtherOpaqueTy { | |
488 | capturable_lifetimes: &mut capturable_lifetimes, | |
489 | origin: hir::OpaqueTyOrigin::Misc, | |
490 | } | |
74b04a01 XL |
491 | } else { |
492 | ImplTraitContext::Disallowed(ImplTraitPosition::Binding) | |
493 | }; | |
494 | let ty = self.lower_ty(ty, itctx); | |
495 | (ty, self.lower_const_body(span, body)) | |
496 | } | |
497 | ||
416331ca XL |
498 | fn lower_use_tree( |
499 | &mut self, | |
500 | tree: &UseTree, | |
501 | prefix: &Path, | |
502 | id: NodeId, | |
dfeec247 | 503 | vis: &mut hir::Visibility<'hir>, |
416331ca | 504 | ident: &mut Ident, |
6a06907d | 505 | attrs: Option<&'hir [Attribute]>, |
dfeec247 | 506 | ) -> hir::ItemKind<'hir> { |
416331ca XL |
507 | debug!("lower_use_tree(tree={:?})", tree); |
508 | debug!("lower_use_tree: vis = {:?}", vis); | |
509 | ||
510 | let path = &tree.prefix; | |
dfeec247 | 511 | let segments = prefix.segments.iter().chain(path.segments.iter()).cloned().collect(); |
416331ca XL |
512 | |
513 | match tree.kind { | |
514 | UseTreeKind::Simple(rename, id1, id2) => { | |
515 | *ident = tree.ident(); | |
516 | ||
517 | // First, apply the prefix to the path. | |
1b1a35ee | 518 | let mut path = Path { segments, span: path.span, tokens: None }; |
416331ca XL |
519 | |
520 | // Correctly resolve `self` imports. | |
521 | if path.segments.len() > 1 | |
522 | && path.segments.last().unwrap().ident.name == kw::SelfLower | |
523 | { | |
524 | let _ = path.segments.pop(); | |
525 | if rename.is_none() { | |
526 | *ident = path.segments.last().unwrap().ident; | |
527 | } | |
528 | } | |
529 | ||
530 | let mut resolutions = self.expect_full_res_from_use(id); | |
531 | // We want to return *something* from this function, so hold onto the first item | |
532 | // for later. | |
533 | let ret_res = self.lower_res(resolutions.next().unwrap_or(Res::Err)); | |
534 | ||
535 | // Here, we are looping over namespaces, if they exist for the definition | |
536 | // being imported. We only handle type and value namespaces because we | |
537 | // won't be dealing with macros in the rest of the compiler. | |
538 | // Essentially a single `use` which imports two names is desugared into | |
539 | // two imports. | |
540 | for (res, &new_node_id) in resolutions.zip([id1, id2].iter()) { | |
541 | let ident = *ident; | |
542 | let mut path = path.clone(); | |
543 | for seg in &mut path.segments { | |
60c5eb7d | 544 | seg.id = self.resolver.next_node_id(); |
416331ca XL |
545 | } |
546 | let span = path.span; | |
547 | ||
548 | self.with_hir_id_owner(new_node_id, |this| { | |
549 | let new_id = this.lower_node_id(new_node_id); | |
550 | let res = this.lower_res(res); | |
dfeec247 XL |
551 | let path = this.lower_path_extra(res, &path, ParamMode::Explicit, None); |
552 | let kind = hir::ItemKind::Use(path, hir::UseKind::Single); | |
416331ca | 553 | let vis = this.rebuild_vis(&vis); |
6a06907d XL |
554 | if let Some(attrs) = attrs { |
555 | this.attrs.insert(new_id, attrs); | |
556 | } | |
416331ca | 557 | |
dfeec247 | 558 | this.insert_item(hir::Item { |
6a06907d | 559 | def_id: new_id.expect_owner(), |
dfeec247 | 560 | ident, |
dfeec247 XL |
561 | kind, |
562 | vis, | |
563 | span, | |
564 | }); | |
416331ca XL |
565 | }); |
566 | } | |
567 | ||
dfeec247 | 568 | let path = self.lower_path_extra(ret_res, &path, ParamMode::Explicit, None); |
416331ca XL |
569 | hir::ItemKind::Use(path, hir::UseKind::Single) |
570 | } | |
571 | UseTreeKind::Glob => { | |
1b1a35ee XL |
572 | let path = self.lower_path( |
573 | id, | |
574 | &Path { segments, span: path.span, tokens: None }, | |
575 | ParamMode::Explicit, | |
576 | ); | |
416331ca XL |
577 | hir::ItemKind::Use(path, hir::UseKind::Glob) |
578 | } | |
579 | UseTreeKind::Nested(ref trees) => { | |
580 | // Nested imports are desugared into simple imports. | |
581 | // So, if we start with | |
582 | // | |
583 | // ``` | |
584 | // pub(x) use foo::{a, b}; | |
585 | // ``` | |
586 | // | |
587 | // we will create three items: | |
588 | // | |
589 | // ``` | |
590 | // pub(x) use foo::a; | |
591 | // pub(x) use foo::b; | |
592 | // pub(x) use foo::{}; // <-- this is called the `ListStem` | |
593 | // ``` | |
594 | // | |
595 | // The first two are produced by recursively invoking | |
596 | // `lower_use_tree` (and indeed there may be things | |
597 | // like `use foo::{a::{b, c}}` and so forth). They | |
598 | // wind up being directly added to | |
599 | // `self.items`. However, the structure of this | |
600 | // function also requires us to return one item, and | |
601 | // for that we return the `{}` import (called the | |
602 | // `ListStem`). | |
603 | ||
1b1a35ee | 604 | let prefix = Path { segments, span: prefix.span.to(path.span), tokens: None }; |
416331ca XL |
605 | |
606 | // Add all the nested `PathListItem`s to the HIR. | |
607 | for &(ref use_tree, id) in trees { | |
608 | let new_hir_id = self.lower_node_id(id); | |
609 | ||
610 | let mut prefix = prefix.clone(); | |
611 | ||
612 | // Give the segments new node-ids since they are being cloned. | |
613 | for seg in &mut prefix.segments { | |
60c5eb7d | 614 | seg.id = self.resolver.next_node_id(); |
416331ca XL |
615 | } |
616 | ||
617 | // Each `use` import is an item and thus are owners of the | |
618 | // names in the path. Up to this point the nested import is | |
619 | // the current owner, since we want each desugared import to | |
620 | // own its own names, we have to adjust the owner before | |
621 | // lowering the rest of the import. | |
622 | self.with_hir_id_owner(id, |this| { | |
623 | let mut vis = this.rebuild_vis(&vis); | |
624 | let mut ident = *ident; | |
625 | ||
dfeec247 XL |
626 | let kind = |
627 | this.lower_use_tree(use_tree, &prefix, id, &mut vis, &mut ident, attrs); | |
6a06907d XL |
628 | if let Some(attrs) = attrs { |
629 | this.attrs.insert(new_hir_id, attrs); | |
630 | } | |
dfeec247 XL |
631 | |
632 | this.insert_item(hir::Item { | |
6a06907d | 633 | def_id: new_hir_id.expect_owner(), |
dfeec247 | 634 | ident, |
dfeec247 XL |
635 | kind, |
636 | vis, | |
637 | span: use_tree.span, | |
638 | }); | |
416331ca XL |
639 | }); |
640 | } | |
641 | ||
642 | // Subtle and a bit hacky: we lower the privacy level | |
643 | // of the list stem to "private" most of the time, but | |
644 | // not for "restricted" paths. The key thing is that | |
645 | // we don't want it to stay as `pub` (with no caveats) | |
646 | // because that affects rustdoc and also the lints | |
647 | // about `pub` items. But we can't *always* make it | |
648 | // private -- particularly not for restricted paths -- | |
649 | // because it contains node-ids that would then be | |
650 | // unused, failing the check that HirIds are "densely | |
651 | // assigned". | |
652 | match vis.node { | |
dfeec247 XL |
653 | hir::VisibilityKind::Public |
654 | | hir::VisibilityKind::Crate(_) | |
655 | | hir::VisibilityKind::Inherited => { | |
416331ca XL |
656 | *vis = respan(prefix.span.shrink_to_lo(), hir::VisibilityKind::Inherited); |
657 | } | |
658 | hir::VisibilityKind::Restricted { .. } => { | |
659 | // Do nothing here, as described in the comment on the match. | |
660 | } | |
661 | } | |
662 | ||
663 | let res = self.expect_full_res_from_use(id).next().unwrap_or(Res::Err); | |
664 | let res = self.lower_res(res); | |
dfeec247 | 665 | let path = self.lower_path_extra(res, &prefix, ParamMode::Explicit, None); |
416331ca XL |
666 | hir::ItemKind::Use(path, hir::UseKind::ListStem) |
667 | } | |
668 | } | |
669 | } | |
670 | ||
671 | /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated | |
672 | /// many times in the HIR tree; for each occurrence, we need to assign distinct | |
673 | /// `NodeId`s. (See, e.g., #56128.) | |
dfeec247 | 674 | fn rebuild_use_path(&mut self, path: &hir::Path<'hir>) -> &'hir hir::Path<'hir> { |
416331ca | 675 | debug!("rebuild_use_path(path = {:?})", path); |
dfeec247 XL |
676 | let segments = |
677 | self.arena.alloc_from_iter(path.segments.iter().map(|seg| hir::PathSegment { | |
678 | ident: seg.ident, | |
679 | hir_id: seg.hir_id.map(|_| self.next_id()), | |
680 | res: seg.res, | |
681 | args: None, | |
682 | infer_args: seg.infer_args, | |
683 | })); | |
684 | self.arena.alloc(hir::Path { span: path.span, res: path.res, segments }) | |
416331ca XL |
685 | } |
686 | ||
dfeec247 | 687 | fn rebuild_vis(&mut self, vis: &hir::Visibility<'hir>) -> hir::Visibility<'hir> { |
416331ca XL |
688 | let vis_kind = match vis.node { |
689 | hir::VisibilityKind::Public => hir::VisibilityKind::Public, | |
690 | hir::VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar), | |
691 | hir::VisibilityKind::Inherited => hir::VisibilityKind::Inherited, | |
692 | hir::VisibilityKind::Restricted { ref path, hir_id: _ } => { | |
693 | hir::VisibilityKind::Restricted { | |
dfeec247 | 694 | path: self.rebuild_use_path(path), |
416331ca XL |
695 | hir_id: self.next_id(), |
696 | } | |
697 | } | |
698 | }; | |
699 | respan(vis.span, vis_kind) | |
700 | } | |
701 | ||
dfeec247 | 702 | fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> { |
6a06907d XL |
703 | let hir_id = self.lower_node_id(i.id); |
704 | let def_id = hir_id.expect_owner(); | |
705 | self.lower_attrs(hir_id, &i.attrs); | |
416331ca | 706 | hir::ForeignItem { |
6a06907d | 707 | def_id, |
416331ca | 708 | ident: i.ident, |
e74abb32 | 709 | kind: match i.kind { |
5869c6ff | 710 | ForeignItemKind::Fn(box FnKind(_, ref sig, ref generics, _)) => { |
74b04a01 | 711 | let fdec = &sig.decl; |
416331ca XL |
712 | let (generics, (fn_dec, fn_args)) = self.add_in_band_defs( |
713 | generics, | |
714 | def_id, | |
715 | AnonymousLifetimeMode::PassThrough, | |
716 | |this, _| { | |
717 | ( | |
e1599b0c | 718 | // Disallow `impl Trait` in foreign items. |
416331ca | 719 | this.lower_fn_decl(fdec, None, false, None), |
e1599b0c | 720 | this.lower_fn_params_to_names(fdec), |
416331ca XL |
721 | ) |
722 | }, | |
723 | ); | |
724 | ||
725 | hir::ForeignItemKind::Fn(fn_dec, fn_args, generics) | |
726 | } | |
74b04a01 | 727 | ForeignItemKind::Static(ref t, m, _) => { |
dfeec247 XL |
728 | let ty = self.lower_ty(t, ImplTraitContext::disallowed()); |
729 | hir::ForeignItemKind::Static(ty, m) | |
416331ca | 730 | } |
74b04a01 | 731 | ForeignItemKind::TyAlias(..) => hir::ForeignItemKind::Type, |
ba9703b0 | 732 | ForeignItemKind::MacCall(_) => panic!("macro shouldn't exist here"), |
416331ca XL |
733 | }, |
734 | vis: self.lower_visibility(&i.vis, None), | |
735 | span: i.span, | |
736 | } | |
737 | } | |
738 | ||
fc512014 XL |
739 | fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef<'hir> { |
740 | hir::ForeignItemRef { | |
6a06907d | 741 | id: hir::ForeignItemId { def_id: self.lower_node_id(i.id).expect_owner() }, |
fc512014 XL |
742 | ident: i.ident, |
743 | span: i.span, | |
744 | vis: self.lower_visibility(&i.vis, Some(i.id)), | |
416331ca XL |
745 | } |
746 | } | |
747 | ||
dfeec247 XL |
748 | fn lower_global_asm(&mut self, ga: &GlobalAsm) -> &'hir hir::GlobalAsm { |
749 | self.arena.alloc(hir::GlobalAsm { asm: ga.asm }) | |
416331ca XL |
750 | } |
751 | ||
dfeec247 | 752 | fn lower_variant(&mut self, v: &Variant) -> hir::Variant<'hir> { |
6a06907d XL |
753 | let id = self.lower_node_id(v.id); |
754 | self.lower_attrs(id, &v.attrs); | |
e1599b0c | 755 | hir::Variant { |
6a06907d XL |
756 | id, |
757 | data: self.lower_variant_data(id, &v.data), | |
e1599b0c | 758 | disr_expr: v.disr_expr.as_ref().map(|e| self.lower_anon_const(e)), |
e1599b0c | 759 | ident: v.ident, |
416331ca XL |
760 | span: v.span, |
761 | } | |
762 | } | |
763 | ||
6a06907d XL |
764 | fn lower_variant_data( |
765 | &mut self, | |
766 | parent_id: hir::HirId, | |
767 | vdata: &VariantData, | |
768 | ) -> hir::VariantData<'hir> { | |
416331ca XL |
769 | match *vdata { |
770 | VariantData::Struct(ref fields, recovered) => hir::VariantData::Struct( | |
dfeec247 | 771 | self.arena |
6a06907d | 772 | .alloc_from_iter(fields.iter().enumerate().map(|f| self.lower_field_def(f))), |
416331ca XL |
773 | recovered, |
774 | ), | |
6a06907d XL |
775 | VariantData::Tuple(ref fields, id) => { |
776 | let ctor_id = self.lower_node_id(id); | |
777 | self.alias_attrs(ctor_id, parent_id); | |
778 | hir::VariantData::Tuple( | |
779 | self.arena.alloc_from_iter( | |
780 | fields.iter().enumerate().map(|f| self.lower_field_def(f)), | |
781 | ), | |
782 | ctor_id, | |
783 | ) | |
784 | } | |
785 | VariantData::Unit(id) => { | |
786 | let ctor_id = self.lower_node_id(id); | |
787 | self.alias_attrs(ctor_id, parent_id); | |
788 | hir::VariantData::Unit(ctor_id) | |
789 | } | |
416331ca XL |
790 | } |
791 | } | |
792 | ||
6a06907d | 793 | fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> { |
e74abb32 | 794 | let ty = if let TyKind::Path(ref qself, ref path) = f.ty.kind { |
416331ca XL |
795 | let t = self.lower_path_ty( |
796 | &f.ty, | |
797 | qself, | |
798 | path, | |
799 | ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124) | |
dfeec247 | 800 | ImplTraitContext::disallowed(), |
416331ca | 801 | ); |
dfeec247 | 802 | self.arena.alloc(t) |
416331ca XL |
803 | } else { |
804 | self.lower_ty(&f.ty, ImplTraitContext::disallowed()) | |
805 | }; | |
6a06907d XL |
806 | let hir_id = self.lower_node_id(f.id); |
807 | self.lower_attrs(hir_id, &f.attrs); | |
808 | hir::FieldDef { | |
416331ca | 809 | span: f.span, |
6a06907d | 810 | hir_id, |
416331ca XL |
811 | ident: match f.ident { |
812 | Some(ident) => ident, | |
813 | // FIXME(jseyfried): positional field hygiene. | |
814 | None => Ident::new(sym::integer(index), f.span), | |
815 | }, | |
816 | vis: self.lower_visibility(&f.vis, None), | |
817 | ty, | |
416331ca XL |
818 | } |
819 | } | |
820 | ||
dfeec247 | 821 | fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> { |
6a06907d XL |
822 | let hir_id = self.lower_node_id(i.id); |
823 | let trait_item_def_id = hir_id.expect_owner(); | |
416331ca | 824 | |
e74abb32 | 825 | let (generics, kind) = match i.kind { |
74b04a01 | 826 | AssocItemKind::Const(_, ref ty, ref default) => { |
dfeec247 | 827 | let ty = self.lower_ty(ty, ImplTraitContext::disallowed()); |
74b04a01 XL |
828 | let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x))); |
829 | (hir::Generics::empty(), hir::TraitItemKind::Const(ty, body)) | |
dfeec247 | 830 | } |
5869c6ff | 831 | AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, None)) => { |
e1599b0c | 832 | let names = self.lower_fn_params_to_names(&sig.decl); |
dfeec247 | 833 | let (generics, sig) = |
5869c6ff | 834 | self.lower_method_sig(generics, sig, trait_item_def_id, false, None, i.id); |
ba9703b0 | 835 | (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names))) |
416331ca | 836 | } |
5869c6ff | 837 | AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, Some(ref body))) => { |
dfeec247 XL |
838 | let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body)); |
839 | let (generics, sig) = | |
5869c6ff | 840 | self.lower_method_sig(generics, sig, trait_item_def_id, false, None, i.id); |
ba9703b0 | 841 | (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id))) |
416331ca | 842 | } |
5869c6ff | 843 | AssocItemKind::TyAlias(box TyAliasKind(_, ref generics, ref bounds, ref default)) => { |
dfeec247 | 844 | let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed())); |
74b04a01 | 845 | let generics = self.lower_generics(generics, ImplTraitContext::disallowed()); |
e74abb32 | 846 | let kind = hir::TraitItemKind::Type( |
416331ca | 847 | self.lower_param_bounds(bounds, ImplTraitContext::disallowed()), |
dfeec247 | 848 | ty, |
416331ca XL |
849 | ); |
850 | ||
e74abb32 | 851 | (generics, kind) |
dfeec247 | 852 | } |
ba9703b0 | 853 | AssocItemKind::MacCall(..) => panic!("macro item shouldn't exist at this point"), |
416331ca XL |
854 | }; |
855 | ||
6a06907d XL |
856 | self.lower_attrs(hir_id, &i.attrs); |
857 | hir::TraitItem { def_id: trait_item_def_id, ident: i.ident, generics, kind, span: i.span } | |
416331ca XL |
858 | } |
859 | ||
dfeec247 | 860 | fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef { |
74b04a01 XL |
861 | let (kind, has_default) = match &i.kind { |
862 | AssocItemKind::Const(_, _, default) => (hir::AssocItemKind::Const, default.is_some()), | |
5869c6ff | 863 | AssocItemKind::TyAlias(box TyAliasKind(_, _, _, default)) => { |
74b04a01 XL |
864 | (hir::AssocItemKind::Type, default.is_some()) |
865 | } | |
5869c6ff | 866 | AssocItemKind::Fn(box FnKind(_, sig, _, default)) => { |
ba9703b0 | 867 | (hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }, default.is_some()) |
416331ca | 868 | } |
ba9703b0 | 869 | AssocItemKind::MacCall(..) => unimplemented!(), |
416331ca | 870 | }; |
6a06907d | 871 | let id = hir::TraitItemId { def_id: self.lower_node_id(i.id).expect_owner() }; |
74b04a01 XL |
872 | let defaultness = hir::Defaultness::Default { has_value: has_default }; |
873 | hir::TraitItemRef { id, ident: i.ident, span: i.span, defaultness, kind } | |
416331ca XL |
874 | } |
875 | ||
dfeec247 | 876 | /// Construct `ExprKind::Err` for the given `span`. |
ba9703b0 | 877 | crate fn expr_err(&mut self, span: Span) -> hir::Expr<'hir> { |
dfeec247 XL |
878 | self.expr(span, hir::ExprKind::Err, AttrVec::new()) |
879 | } | |
880 | ||
881 | fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> { | |
f035d41b | 882 | let impl_item_def_id = self.resolver.local_def_id(i.id); |
416331ca | 883 | |
74b04a01 XL |
884 | let (generics, kind) = match &i.kind { |
885 | AssocItemKind::Const(_, ty, expr) => { | |
dfeec247 XL |
886 | let ty = self.lower_ty(ty, ImplTraitContext::disallowed()); |
887 | ( | |
74b04a01 | 888 | hir::Generics::empty(), |
dfeec247 XL |
889 | hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())), |
890 | ) | |
891 | } | |
5869c6ff | 892 | AssocItemKind::Fn(box FnKind(_, sig, generics, body)) => { |
416331ca | 893 | self.current_item = Some(i.span); |
74b04a01 XL |
894 | let asyncness = sig.header.asyncness; |
895 | let body_id = | |
896 | self.lower_maybe_async_body(i.span, &sig.decl, asyncness, body.as_deref()); | |
416331ca XL |
897 | let impl_trait_return_allow = !self.is_in_trait_impl; |
898 | let (generics, sig) = self.lower_method_sig( | |
74b04a01 | 899 | generics, |
416331ca XL |
900 | sig, |
901 | impl_item_def_id, | |
902 | impl_trait_return_allow, | |
74b04a01 | 903 | asyncness.opt_return_id(), |
5869c6ff | 904 | i.id, |
416331ca XL |
905 | ); |
906 | ||
ba9703b0 | 907 | (generics, hir::ImplItemKind::Fn(sig, body_id)) |
416331ca | 908 | } |
5869c6ff | 909 | AssocItemKind::TyAlias(box TyAliasKind(_, generics, _, ty)) => { |
74b04a01 | 910 | let generics = self.lower_generics(generics, ImplTraitContext::disallowed()); |
dfeec247 | 911 | let kind = match ty { |
60c5eb7d | 912 | None => { |
dfeec247 | 913 | let ty = self.arena.alloc(self.ty(i.span, hir::TyKind::Err)); |
60c5eb7d XL |
914 | hir::ImplItemKind::TyAlias(ty) |
915 | } | |
f035d41b XL |
916 | Some(ty) => { |
917 | let ty = self.lower_ty( | |
918 | ty, | |
919 | ImplTraitContext::OtherOpaqueTy { | |
920 | capturable_lifetimes: &mut FxHashSet::default(), | |
6a06907d | 921 | origin: hir::OpaqueTyOrigin::TyAlias, |
f035d41b XL |
922 | }, |
923 | ); | |
924 | hir::ImplItemKind::TyAlias(ty) | |
925 | } | |
60c5eb7d XL |
926 | }; |
927 | (generics, kind) | |
dfeec247 | 928 | } |
ba9703b0 | 929 | AssocItemKind::MacCall(..) => panic!("`TyMac` should have been expanded by now"), |
416331ca XL |
930 | }; |
931 | ||
ba9703b0 XL |
932 | // Since `default impl` is not yet implemented, this is always true in impls. |
933 | let has_value = true; | |
934 | let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); | |
6a06907d XL |
935 | let hir_id = self.lower_node_id(i.id); |
936 | self.lower_attrs(hir_id, &i.attrs); | |
416331ca | 937 | hir::ImplItem { |
6a06907d | 938 | def_id: hir_id.expect_owner(), |
416331ca | 939 | ident: i.ident, |
416331ca XL |
940 | generics, |
941 | vis: self.lower_visibility(&i.vis, None), | |
ba9703b0 | 942 | defaultness, |
e74abb32 | 943 | kind, |
416331ca XL |
944 | span: i.span, |
945 | } | |
416331ca XL |
946 | } |
947 | ||
dfeec247 | 948 | fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef<'hir> { |
ba9703b0 XL |
949 | // Since `default impl` is not yet implemented, this is always true in impls. |
950 | let has_value = true; | |
951 | let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value); | |
416331ca | 952 | hir::ImplItemRef { |
6a06907d | 953 | id: hir::ImplItemId { def_id: self.lower_node_id(i.id).expect_owner() }, |
416331ca XL |
954 | ident: i.ident, |
955 | span: i.span, | |
956 | vis: self.lower_visibility(&i.vis, Some(i.id)), | |
ba9703b0 | 957 | defaultness, |
60c5eb7d | 958 | kind: match &i.kind { |
dfeec247 | 959 | AssocItemKind::Const(..) => hir::AssocItemKind::Const, |
f035d41b | 960 | AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type, |
5869c6ff | 961 | AssocItemKind::Fn(box FnKind(_, sig, ..)) => { |
ba9703b0 | 962 | hir::AssocItemKind::Fn { has_self: sig.decl.has_self() } |
dfeec247 | 963 | } |
ba9703b0 | 964 | AssocItemKind::MacCall(..) => unimplemented!(), |
416331ca XL |
965 | }, |
966 | } | |
416331ca XL |
967 | } |
968 | ||
969 | /// If an `explicit_owner` is given, this method allocates the `HirId` in | |
970 | /// the address space of that item instead of the item currently being | |
971 | /// lowered. This can happen during `lower_impl_item_ref()` where we need to | |
972 | /// lower a `Visibility` value although we haven't lowered the owning | |
973 | /// `ImplItem` in question yet. | |
974 | fn lower_visibility( | |
975 | &mut self, | |
976 | v: &Visibility, | |
977 | explicit_owner: Option<NodeId>, | |
dfeec247 | 978 | ) -> hir::Visibility<'hir> { |
1b1a35ee | 979 | let node = match v.kind { |
416331ca XL |
980 | VisibilityKind::Public => hir::VisibilityKind::Public, |
981 | VisibilityKind::Crate(sugar) => hir::VisibilityKind::Crate(sugar), | |
982 | VisibilityKind::Restricted { ref path, id } => { | |
983 | debug!("lower_visibility: restricted path id = {:?}", id); | |
984 | let lowered_id = if let Some(owner) = explicit_owner { | |
985 | self.lower_node_id_with_owner(id, owner) | |
986 | } else { | |
987 | self.lower_node_id(id) | |
988 | }; | |
989 | let res = self.expect_full_res(id); | |
990 | let res = self.lower_res(res); | |
991 | hir::VisibilityKind::Restricted { | |
dfeec247 | 992 | path: self.lower_path_extra(res, path, ParamMode::Explicit, explicit_owner), |
416331ca XL |
993 | hir_id: lowered_id, |
994 | } | |
dfeec247 | 995 | } |
416331ca XL |
996 | VisibilityKind::Inherited => hir::VisibilityKind::Inherited, |
997 | }; | |
998 | respan(v.span, node) | |
999 | } | |
1000 | ||
ba9703b0 XL |
1001 | fn lower_defaultness( |
1002 | &self, | |
1003 | d: Defaultness, | |
1004 | has_value: bool, | |
1005 | ) -> (hir::Defaultness, Option<Span>) { | |
416331ca | 1006 | match d { |
ba9703b0 | 1007 | Defaultness::Default(sp) => (hir::Defaultness::Default { has_value }, Some(sp)), |
416331ca XL |
1008 | Defaultness::Final => { |
1009 | assert!(has_value); | |
ba9703b0 | 1010 | (hir::Defaultness::Final, None) |
416331ca XL |
1011 | } |
1012 | } | |
1013 | } | |
1014 | ||
dfeec247 XL |
1015 | fn record_body( |
1016 | &mut self, | |
1017 | params: &'hir [hir::Param<'hir>], | |
1018 | value: hir::Expr<'hir>, | |
1019 | ) -> hir::BodyId { | |
1020 | let body = hir::Body { generator_kind: self.generator_kind, params, value }; | |
416331ca XL |
1021 | let id = body.id(); |
1022 | self.bodies.insert(id, body); | |
1023 | id | |
1024 | } | |
1025 | ||
ba9703b0 | 1026 | pub(super) fn lower_body( |
416331ca | 1027 | &mut self, |
dfeec247 | 1028 | f: impl FnOnce(&mut Self) -> (&'hir [hir::Param<'hir>], hir::Expr<'hir>), |
416331ca XL |
1029 | ) -> hir::BodyId { |
1030 | let prev_gen_kind = self.generator_kind.take(); | |
ba9703b0 | 1031 | let task_context = self.task_context.take(); |
e1599b0c XL |
1032 | let (parameters, result) = f(self); |
1033 | let body_id = self.record_body(parameters, result); | |
ba9703b0 | 1034 | self.task_context = task_context; |
416331ca XL |
1035 | self.generator_kind = prev_gen_kind; |
1036 | body_id | |
1037 | } | |
1038 | ||
dfeec247 | 1039 | fn lower_param(&mut self, param: &Param) -> hir::Param<'hir> { |
6a06907d XL |
1040 | let hir_id = self.lower_node_id(param.id); |
1041 | self.lower_attrs(hir_id, ¶m.attrs); | |
e1599b0c | 1042 | hir::Param { |
6a06907d | 1043 | hir_id, |
e1599b0c | 1044 | pat: self.lower_pat(¶m.pat), |
3dfed10e | 1045 | ty_span: param.ty.span, |
e1599b0c | 1046 | span: param.span, |
416331ca XL |
1047 | } |
1048 | } | |
1049 | ||
1050 | pub(super) fn lower_fn_body( | |
1051 | &mut self, | |
1052 | decl: &FnDecl, | |
dfeec247 | 1053 | body: impl FnOnce(&mut Self) -> hir::Expr<'hir>, |
416331ca | 1054 | ) -> hir::BodyId { |
dfeec247 XL |
1055 | self.lower_body(|this| { |
1056 | ( | |
1057 | this.arena.alloc_from_iter(decl.inputs.iter().map(|x| this.lower_param(x))), | |
1058 | body(this), | |
1059 | ) | |
1060 | }) | |
416331ca XL |
1061 | } |
1062 | ||
dfeec247 XL |
1063 | fn lower_fn_body_block( |
1064 | &mut self, | |
1065 | span: Span, | |
1066 | decl: &FnDecl, | |
1067 | body: Option<&Block>, | |
1068 | ) -> hir::BodyId { | |
1069 | self.lower_fn_body(decl, |this| this.lower_block_expr_opt(span, body)) | |
416331ca XL |
1070 | } |
1071 | ||
dfeec247 XL |
1072 | fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Expr<'hir> { |
1073 | match block { | |
1074 | Some(block) => self.lower_block_expr(block), | |
1075 | None => self.expr_err(span), | |
1076 | } | |
1077 | } | |
1078 | ||
1079 | pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId { | |
1080 | self.lower_body(|this| { | |
1081 | ( | |
1082 | &[], | |
1083 | match expr { | |
1084 | Some(expr) => this.lower_expr_mut(expr), | |
1085 | None => this.expr_err(span), | |
1086 | }, | |
1087 | ) | |
1088 | }) | |
416331ca XL |
1089 | } |
1090 | ||
1091 | fn lower_maybe_async_body( | |
1092 | &mut self, | |
dfeec247 | 1093 | span: Span, |
416331ca | 1094 | decl: &FnDecl, |
74b04a01 | 1095 | asyncness: Async, |
dfeec247 | 1096 | body: Option<&Block>, |
416331ca XL |
1097 | ) -> hir::BodyId { |
1098 | let closure_id = match asyncness { | |
74b04a01 XL |
1099 | Async::Yes { closure_id, .. } => closure_id, |
1100 | Async::No => return self.lower_fn_body_block(span, decl, body), | |
416331ca XL |
1101 | }; |
1102 | ||
1103 | self.lower_body(|this| { | |
dfeec247 XL |
1104 | let mut parameters: Vec<hir::Param<'_>> = Vec::new(); |
1105 | let mut statements: Vec<hir::Stmt<'_>> = Vec::new(); | |
416331ca | 1106 | |
e1599b0c | 1107 | // Async function parameters are lowered into the closure body so that they are |
416331ca XL |
1108 | // captured and so that the drop order matches the equivalent non-async functions. |
1109 | // | |
1110 | // from: | |
1111 | // | |
1112 | // async fn foo(<pattern>: <ty>, <pattern>: <ty>, <pattern>: <ty>) { | |
e1599b0c | 1113 | // <body> |
416331ca XL |
1114 | // } |
1115 | // | |
1116 | // into: | |
1117 | // | |
1118 | // fn foo(__arg0: <ty>, __arg1: <ty>, __arg2: <ty>) { | |
1119 | // async move { | |
1120 | // let __arg2 = __arg2; | |
1121 | // let <pattern> = __arg2; | |
1122 | // let __arg1 = __arg1; | |
1123 | // let <pattern> = __arg1; | |
1124 | // let __arg0 = __arg0; | |
1125 | // let <pattern> = __arg0; | |
e1599b0c | 1126 | // drop-temps { <body> } // see comments later in fn for details |
416331ca XL |
1127 | // } |
1128 | // } | |
1129 | // | |
1130 | // If `<pattern>` is a simple ident, then it is lowered to a single | |
1131 | // `let <pattern> = <pattern>;` statement as an optimization. | |
e1599b0c XL |
1132 | // |
1133 | // Note that the body is embedded in `drop-temps`; an | |
1134 | // equivalent desugaring would be `return { <body> | |
1135 | // };`. The key point is that we wish to drop all the | |
1136 | // let-bound variables and temporaries created in the body | |
1137 | // (and its tail expression!) before we drop the | |
1138 | // parameters (c.f. rust-lang/rust#64512). | |
1139 | for (index, parameter) in decl.inputs.iter().enumerate() { | |
1140 | let parameter = this.lower_param(parameter); | |
1141 | let span = parameter.pat.span; | |
416331ca XL |
1142 | |
1143 | // Check if this is a binding pattern, if so, we can optimize and avoid adding a | |
e1599b0c | 1144 | // `let <pat> = __argN;` statement. In this case, we do not rename the parameter. |
e74abb32 | 1145 | let (ident, is_simple_parameter) = match parameter.pat.kind { |
29967ef6 XL |
1146 | hir::PatKind::Binding( |
1147 | hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable, | |
1148 | _, | |
1149 | ident, | |
1150 | _, | |
1151 | ) => (ident, true), | |
1152 | // For `ref mut` or wildcard arguments, we can't reuse the binding, but | |
1153 | // we can keep the same name for the parameter. | |
1154 | // This lets rustdoc render it correctly in documentation. | |
1155 | hir::PatKind::Binding(_, _, ident, _) => (ident, false), | |
1156 | hir::PatKind::Wild => { | |
1157 | (Ident::with_dummy_span(rustc_span::symbol::kw::Underscore), false) | |
dfeec247 | 1158 | } |
416331ca XL |
1159 | _ => { |
1160 | // Replace the ident for bindings that aren't simple. | |
1161 | let name = format!("__arg{}", index); | |
1162 | let ident = Ident::from_str(&name); | |
1163 | ||
1164 | (ident, false) | |
dfeec247 | 1165 | } |
416331ca XL |
1166 | }; |
1167 | ||
dfeec247 | 1168 | let desugared_span = this.mark_span_with_reason(DesugaringKind::Async, span, None); |
416331ca | 1169 | |
e1599b0c | 1170 | // Construct a parameter representing `__argN: <ty>` to replace the parameter of the |
416331ca XL |
1171 | // async function. |
1172 | // | |
e1599b0c XL |
1173 | // If this is the simple case, this parameter will end up being the same as the |
1174 | // original parameter, but with a different pattern id. | |
6a06907d | 1175 | let stmt_attrs = this.attrs.get(¶meter.hir_id).copied(); |
e1599b0c XL |
1176 | let (new_parameter_pat, new_parameter_id) = this.pat_ident(desugared_span, ident); |
1177 | let new_parameter = hir::Param { | |
e1599b0c XL |
1178 | hir_id: parameter.hir_id, |
1179 | pat: new_parameter_pat, | |
3dfed10e | 1180 | ty_span: parameter.ty_span, |
e1599b0c | 1181 | span: parameter.span, |
416331ca XL |
1182 | }; |
1183 | ||
e1599b0c | 1184 | if is_simple_parameter { |
416331ca XL |
1185 | // If this is the simple case, then we only insert one statement that is |
1186 | // `let <pat> = <pat>;`. We re-use the original argument's pattern so that | |
1187 | // `HirId`s are densely assigned. | |
e1599b0c | 1188 | let expr = this.expr_ident(desugared_span, ident, new_parameter_id); |
416331ca XL |
1189 | let stmt = this.stmt_let_pat( |
1190 | stmt_attrs, | |
1191 | desugared_span, | |
dfeec247 | 1192 | Some(expr), |
e1599b0c | 1193 | parameter.pat, |
dfeec247 | 1194 | hir::LocalSource::AsyncFn, |
416331ca XL |
1195 | ); |
1196 | statements.push(stmt); | |
1197 | } else { | |
1198 | // If this is not the simple case, then we construct two statements: | |
1199 | // | |
1200 | // ``` | |
1201 | // let __argN = __argN; | |
1202 | // let <pat> = __argN; | |
1203 | // ``` | |
1204 | // | |
e1599b0c | 1205 | // The first statement moves the parameter into the closure and thus ensures |
416331ca XL |
1206 | // that the drop order is correct. |
1207 | // | |
1208 | // The second statement creates the bindings that the user wrote. | |
1209 | ||
1210 | // Construct the `let mut __argN = __argN;` statement. It must be a mut binding | |
1211 | // because the user may have specified a `ref mut` binding in the next | |
1212 | // statement. | |
1213 | let (move_pat, move_id) = this.pat_ident_binding_mode( | |
dfeec247 XL |
1214 | desugared_span, |
1215 | ident, | |
1216 | hir::BindingAnnotation::Mutable, | |
1217 | ); | |
e1599b0c | 1218 | let move_expr = this.expr_ident(desugared_span, ident, new_parameter_id); |
416331ca | 1219 | let move_stmt = this.stmt_let_pat( |
6a06907d | 1220 | None, |
416331ca | 1221 | desugared_span, |
dfeec247 | 1222 | Some(move_expr), |
416331ca | 1223 | move_pat, |
dfeec247 | 1224 | hir::LocalSource::AsyncFn, |
416331ca XL |
1225 | ); |
1226 | ||
1227 | // Construct the `let <pat> = __argN;` statement. We re-use the original | |
e1599b0c | 1228 | // parameter's pattern so that `HirId`s are densely assigned. |
416331ca XL |
1229 | let pattern_expr = this.expr_ident(desugared_span, ident, move_id); |
1230 | let pattern_stmt = this.stmt_let_pat( | |
1231 | stmt_attrs, | |
1232 | desugared_span, | |
dfeec247 | 1233 | Some(pattern_expr), |
e1599b0c | 1234 | parameter.pat, |
dfeec247 | 1235 | hir::LocalSource::AsyncFn, |
416331ca XL |
1236 | ); |
1237 | ||
1238 | statements.push(move_stmt); | |
1239 | statements.push(pattern_stmt); | |
1240 | }; | |
1241 | ||
e1599b0c | 1242 | parameters.push(new_parameter); |
416331ca XL |
1243 | } |
1244 | ||
dfeec247 | 1245 | let body_span = body.map_or(span, |b| b.span); |
416331ca | 1246 | let async_expr = this.make_async_expr( |
e74abb32 XL |
1247 | CaptureBy::Value, |
1248 | closure_id, | |
1249 | None, | |
dfeec247 | 1250 | body_span, |
e74abb32 | 1251 | hir::AsyncGeneratorKind::Fn, |
416331ca | 1252 | |this| { |
e1599b0c | 1253 | // Create a block from the user's function body: |
dfeec247 | 1254 | let user_body = this.lower_block_expr_opt(body_span, body); |
e1599b0c XL |
1255 | |
1256 | // Transform into `drop-temps { <user-body> }`, an expression: | |
dfeec247 XL |
1257 | let desugared_span = |
1258 | this.mark_span_with_reason(DesugaringKind::Async, user_body.span, None); | |
e1599b0c XL |
1259 | let user_body = this.expr_drop_temps( |
1260 | desugared_span, | |
dfeec247 XL |
1261 | this.arena.alloc(user_body), |
1262 | AttrVec::new(), | |
e1599b0c XL |
1263 | ); |
1264 | ||
1265 | // As noted above, create the final block like | |
1266 | // | |
1267 | // ``` | |
1268 | // { | |
1269 | // let $param_pattern = $raw_param; | |
1270 | // ... | |
1271 | // drop-temps { <user-body> } | |
1272 | // } | |
1273 | // ``` | |
1274 | let body = this.block_all( | |
1275 | desugared_span, | |
dfeec247 XL |
1276 | this.arena.alloc_from_iter(statements), |
1277 | Some(user_body), | |
e1599b0c | 1278 | ); |
dfeec247 XL |
1279 | |
1280 | this.expr_block(body, AttrVec::new()) | |
1281 | }, | |
1282 | ); | |
1283 | ||
1284 | ( | |
1285 | this.arena.alloc_from_iter(parameters), | |
1286 | this.expr(body_span, async_expr, AttrVec::new()), | |
1287 | ) | |
416331ca XL |
1288 | }) |
1289 | } | |
1290 | ||
1291 | fn lower_method_sig( | |
1292 | &mut self, | |
1293 | generics: &Generics, | |
60c5eb7d | 1294 | sig: &FnSig, |
ba9703b0 | 1295 | fn_def_id: LocalDefId, |
416331ca XL |
1296 | impl_trait_return_allow: bool, |
1297 | is_async: Option<NodeId>, | |
5869c6ff | 1298 | id: NodeId, |
dfeec247 | 1299 | ) -> (hir::Generics<'hir>, hir::FnSig<'hir>) { |
5869c6ff | 1300 | let header = self.lower_fn_header(sig.header, sig.span, id); |
416331ca XL |
1301 | let (generics, decl) = self.add_in_band_defs( |
1302 | generics, | |
1303 | fn_def_id, | |
1304 | AnonymousLifetimeMode::PassThrough, | |
dfeec247 XL |
1305 | |this, idty| { |
1306 | this.lower_fn_decl( | |
1307 | &sig.decl, | |
ba9703b0 | 1308 | Some((fn_def_id.to_def_id(), idty)), |
dfeec247 XL |
1309 | impl_trait_return_allow, |
1310 | is_async, | |
1311 | ) | |
1312 | }, | |
416331ca | 1313 | ); |
3dfed10e | 1314 | (generics, hir::FnSig { header, decl, span: sig.span }) |
416331ca XL |
1315 | } |
1316 | ||
5869c6ff | 1317 | fn lower_fn_header(&mut self, h: FnHeader, span: Span, id: NodeId) -> hir::FnHeader { |
416331ca | 1318 | hir::FnHeader { |
74b04a01 XL |
1319 | unsafety: self.lower_unsafety(h.unsafety), |
1320 | asyncness: self.lower_asyncness(h.asyncness), | |
1321 | constness: self.lower_constness(h.constness), | |
5869c6ff | 1322 | abi: self.lower_extern(h.ext, span, id), |
416331ca XL |
1323 | } |
1324 | } | |
1325 | ||
60c5eb7d XL |
1326 | pub(super) fn lower_abi(&mut self, abi: StrLit) -> abi::Abi { |
1327 | abi::lookup(&abi.symbol_unescaped.as_str()).unwrap_or_else(|| { | |
1328 | self.error_on_invalid_abi(abi); | |
1329 | abi::Abi::Rust | |
1330 | }) | |
416331ca XL |
1331 | } |
1332 | ||
5869c6ff | 1333 | pub(super) fn lower_extern(&mut self, ext: Extern, span: Span, id: NodeId) -> abi::Abi { |
60c5eb7d XL |
1334 | match ext { |
1335 | Extern::None => abi::Abi::Rust, | |
5869c6ff | 1336 | Extern::Implicit => { |
6a06907d XL |
1337 | self.maybe_lint_missing_abi(span, id, abi::Abi::C { unwind: false }); |
1338 | abi::Abi::C { unwind: false } | |
5869c6ff | 1339 | } |
60c5eb7d | 1340 | Extern::Explicit(abi) => self.lower_abi(abi), |
416331ca XL |
1341 | } |
1342 | } | |
1343 | ||
60c5eb7d | 1344 | fn error_on_invalid_abi(&self, abi: StrLit) { |
dfeec247 XL |
1345 | struct_span_err!(self.sess, abi.span, E0703, "invalid ABI: found `{}`", abi.symbol) |
1346 | .span_label(abi.span, "invalid ABI") | |
1347 | .help(&format!("valid ABIs: {}", abi::all_names().join(", "))) | |
1348 | .emit(); | |
60c5eb7d XL |
1349 | } |
1350 | ||
74b04a01 | 1351 | fn lower_asyncness(&mut self, a: Async) -> hir::IsAsync { |
416331ca | 1352 | match a { |
74b04a01 XL |
1353 | Async::Yes { .. } => hir::IsAsync::Async, |
1354 | Async::No => hir::IsAsync::NotAsync, | |
1355 | } | |
1356 | } | |
1357 | ||
1358 | fn lower_constness(&mut self, c: Const) -> hir::Constness { | |
1359 | match c { | |
1360 | Const::Yes(_) => hir::Constness::Const, | |
1361 | Const::No => hir::Constness::NotConst, | |
1362 | } | |
1363 | } | |
1364 | ||
1365 | pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety { | |
1366 | match u { | |
1367 | Unsafe::Yes(_) => hir::Unsafety::Unsafe, | |
1368 | Unsafe::No => hir::Unsafety::Normal, | |
416331ca XL |
1369 | } |
1370 | } | |
1371 | ||
dfeec247 | 1372 | pub(super) fn lower_generics_mut( |
416331ca XL |
1373 | &mut self, |
1374 | generics: &Generics, | |
dfeec247 XL |
1375 | itctx: ImplTraitContext<'_, 'hir>, |
1376 | ) -> GenericsCtor<'hir> { | |
416331ca XL |
1377 | // Collect `?Trait` bounds in where clause and move them to parameter definitions. |
1378 | // FIXME: this could probably be done with less rightward drift. It also looks like two | |
1379 | // control paths where `report_error` is called are the only paths that advance to after the | |
1380 | // match statement, so the error reporting could probably just be moved there. | |
1381 | let mut add_bounds: NodeMap<Vec<_>> = Default::default(); | |
1382 | for pred in &generics.where_clause.predicates { | |
1383 | if let WherePredicate::BoundPredicate(ref bound_pred) = *pred { | |
1384 | 'next_bound: for bound in &bound_pred.bounds { | |
1385 | if let GenericBound::Trait(_, TraitBoundModifier::Maybe) = *bound { | |
1386 | let report_error = |this: &mut Self| { | |
1387 | this.diagnostic().span_err( | |
1388 | bound_pred.bounded_ty.span, | |
1389 | "`?Trait` bounds are only permitted at the \ | |
1390 | point where a type parameter is declared", | |
1391 | ); | |
1392 | }; | |
1393 | // Check if the where clause type is a plain type parameter. | |
e74abb32 | 1394 | match bound_pred.bounded_ty.kind { |
416331ca XL |
1395 | TyKind::Path(None, ref path) |
1396 | if path.segments.len() == 1 | |
1397 | && bound_pred.bound_generic_params.is_empty() => | |
1398 | { | |
dfeec247 XL |
1399 | if let Some(Res::Def(DefKind::TyParam, def_id)) = self |
1400 | .resolver | |
416331ca XL |
1401 | .get_partial_res(bound_pred.bounded_ty.id) |
1402 | .map(|d| d.base_res()) | |
1403 | { | |
f9f354fc | 1404 | if let Some(def_id) = def_id.as_local() { |
416331ca | 1405 | for param in &generics.params { |
ba9703b0 | 1406 | if let GenericParamKind::Type { .. } = param.kind { |
f035d41b | 1407 | if def_id == self.resolver.local_def_id(param.id) { |
ba9703b0 XL |
1408 | add_bounds |
1409 | .entry(param.id) | |
1410 | .or_default() | |
1411 | .push(bound.clone()); | |
1412 | continue 'next_bound; | |
416331ca | 1413 | } |
416331ca XL |
1414 | } |
1415 | } | |
1416 | } | |
1417 | } | |
1418 | report_error(self) | |
1419 | } | |
1420 | _ => report_error(self), | |
1421 | } | |
1422 | } | |
1423 | } | |
1424 | } | |
1425 | } | |
1426 | ||
dfeec247 XL |
1427 | GenericsCtor { |
1428 | params: self.lower_generic_params_mut(&generics.params, &add_bounds, itctx).collect(), | |
416331ca XL |
1429 | where_clause: self.lower_where_clause(&generics.where_clause), |
1430 | span: generics.span, | |
1431 | } | |
1432 | } | |
1433 | ||
dfeec247 XL |
1434 | pub(super) fn lower_generics( |
1435 | &mut self, | |
1436 | generics: &Generics, | |
1437 | itctx: ImplTraitContext<'_, 'hir>, | |
1438 | ) -> hir::Generics<'hir> { | |
1439 | let generics_ctor = self.lower_generics_mut(generics, itctx); | |
1440 | generics_ctor.into_generics(self.arena) | |
1441 | } | |
1442 | ||
1443 | fn lower_where_clause(&mut self, wc: &WhereClause) -> hir::WhereClause<'hir> { | |
1444 | self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| { | |
1445 | hir::WhereClause { | |
1446 | predicates: this.arena.alloc_from_iter( | |
1447 | wc.predicates.iter().map(|predicate| this.lower_where_predicate(predicate)), | |
1448 | ), | |
1449 | span: wc.span, | |
1450 | } | |
1451 | }) | |
416331ca XL |
1452 | } |
1453 | ||
dfeec247 | 1454 | fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> { |
416331ca XL |
1455 | match *pred { |
1456 | WherePredicate::BoundPredicate(WhereBoundPredicate { | |
1457 | ref bound_generic_params, | |
1458 | ref bounded_ty, | |
1459 | ref bounds, | |
1460 | span, | |
1461 | }) => { | |
dfeec247 XL |
1462 | self.with_in_scope_lifetime_defs(&bound_generic_params, |this| { |
1463 | hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate { | |
1464 | bound_generic_params: this.lower_generic_params( | |
1465 | bound_generic_params, | |
1466 | &NodeMap::default(), | |
1467 | ImplTraitContext::disallowed(), | |
1468 | ), | |
1469 | bounded_ty: this.lower_ty(bounded_ty, ImplTraitContext::disallowed()), | |
1470 | bounds: this.arena.alloc_from_iter(bounds.iter().filter_map(|bound| { | |
1471 | match *bound { | |
1472 | // Ignore `?Trait` bounds. | |
1473 | // They were copied into type parameters already. | |
1474 | GenericBound::Trait(_, TraitBoundModifier::Maybe) => None, | |
1475 | _ => Some( | |
1476 | this.lower_param_bound(bound, ImplTraitContext::disallowed()), | |
1477 | ), | |
1478 | } | |
1479 | })), | |
1480 | span, | |
1481 | }) | |
1482 | }) | |
416331ca XL |
1483 | } |
1484 | WherePredicate::RegionPredicate(WhereRegionPredicate { | |
1485 | ref lifetime, | |
1486 | ref bounds, | |
1487 | span, | |
1488 | }) => hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { | |
1489 | span, | |
1490 | lifetime: self.lower_lifetime(lifetime), | |
1491 | bounds: self.lower_param_bounds(bounds, ImplTraitContext::disallowed()), | |
1492 | }), | |
dfeec247 | 1493 | WherePredicate::EqPredicate(WhereEqPredicate { id, ref lhs_ty, ref rhs_ty, span }) => { |
416331ca XL |
1494 | hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { |
1495 | hir_id: self.lower_node_id(id), | |
1496 | lhs_ty: self.lower_ty(lhs_ty, ImplTraitContext::disallowed()), | |
1497 | rhs_ty: self.lower_ty(rhs_ty, ImplTraitContext::disallowed()), | |
1498 | span, | |
1499 | }) | |
dfeec247 XL |
1500 | } |
1501 | } | |
1502 | } | |
1503 | } | |
1504 | ||
1505 | /// Helper struct for delayed construction of Generics. | |
1506 | pub(super) struct GenericsCtor<'hir> { | |
1507 | pub(super) params: SmallVec<[hir::GenericParam<'hir>; 4]>, | |
1508 | where_clause: hir::WhereClause<'hir>, | |
1509 | span: Span, | |
1510 | } | |
1511 | ||
1512 | impl<'hir> GenericsCtor<'hir> { | |
1513 | pub(super) fn into_generics(self, arena: &'hir Arena<'hir>) -> hir::Generics<'hir> { | |
1514 | hir::Generics { | |
1515 | params: arena.alloc_from_iter(self.params), | |
1516 | where_clause: self.where_clause, | |
1517 | span: self.span, | |
416331ca XL |
1518 | } |
1519 | } | |
1520 | } |